Back to: JSP Tutorials for Beginners and Professionals
JSP Architecture
In this article, I am going to discuss the JSP Architecture. Please read our previous article where discussed JSP API. At the end of this article, you will understand the following pointers in detail.
- How JSP Work?
- JSP Architecture
- JSP Processing and its flow
- Model-View-Controller Framework
- Explain about Model, View, and Controller
- Advantages of MVC
- Example of MVC in JSP
JSP Architecture
The web server needs a JSP engine(container) to process JSP pages. The JSP container is liable for intercepting requests for JSP pages. Here we have used Apache which has a built-in JSP container to support JSP page development. A JSP container works with the online server to supply the services a JSP needs and the runtime environment also. It knows the way to understand the special elements that are a part of JSPs.
There are two basic ways of using JSP technology. They are the client/server (page-centric) 2-tier approach and therefore the N-tier approach (dispatcher).
The Page-Centric Approach
Applications built employing a client-server (2-tier) approach contains one or more application programs running on client machines and connecting to a server-based application to figure. With the arrival of Servlets technology, 2-tier applications could even be developed using Java programming language. This model allows JSPs or Servlets direct access to some resources such as databases or legacy applications to service a client’s request. The JSP page is where the incoming request is intercepted, processed and therefore the response sent back to the client. JSPs differ from Servlets during this scenario by providing clean code, separating code from the content by placing data access in EJBs. Even though this model makes application development easier, it doesn’t proportion well for an outsized number of simultaneous clients because it entails a big amount of request processing to be performed and every request must establish or share a potentially scarce/expensive connection to the resource in question.
Page – View:
This basic architecture involves direct request invocations to a server page with embedded Java code and markup tags which dynamically generate output for substitution within the HTML. This approach has been blessed variety of advantages. It is very straight forward and is a low-overhead approach from a development perspective. All the Java code could also be embedded within the HTML, so changes are confined to a really limited area, reducing complexity drastically.
The big trade-off here is within the level of sophistication. As the scale of the system grows, some limitations begin to surface, such as bloating of business logic code in the page instead of factoring forward to a meditating Servlet or Factoring back to a worker bean. It is an incontrovertible fact that utilizing Servlet and helper beans helps to separate developer roles more cleanly and improves the potential for code reuse.
Page-view with bean:
This pattern is employed when the above architecture becomes too cluttered with business-related code and data access code. The Java code representing the business logic and straightforward data storage implementation within the previous model moves from the JSP to the JavaBean worker. This refactoring leaves away cleaner JSP with limited Java code, which may be comfortably owned by a private during a web-production role since it encapsulates mostly markup tags.
The Dispatcher Approach
In this approach, a Servlet or JSP acts as a mediator or controller, delegating requests to JSP pages and JavaBeans. There are three different architectures. They are mediator-view, mediator-composite view, and repair to workers.
In an N-tier application, the server-side of the architecture is choppy into multiple tiers. In this case, the appliance consists of multiple tiers, where the center tier, the JSP, interacts with the rear end resources via another object or EJBs component. The Enterprise JavaBeans server and the EJB provide managed access to resource sharing and performance issues of the 2-tier approach.
The first step is N-tiered application design should be identifying the correct objects and their interaction and the second step is identifying the JSPs or Servlets. These are divided into two categories:
- Front end JSPs or Servlets manage application flow and business logic evaluation. They act to some extent to intercept the HTTP requests coming from the users. They provide one entry point to an application, simplifying security management and making the application state easier to take care of.
- Presentation JSPs or Servlets generate HTML or XML with their main purpose in life being the presentation of dynamic content. They contain the only presentation and rendering logic.
These categories resemble the Modal-View design pattern, where the front-end components are that the model and therefore the presentation component the view. In this approach, JSPs are wont to generate the presentation layer and either JSPs or Servlets to perform process-intensive tasks. The front-end component acts because the controller and is responsible for the request processing and therefore the creation of any beans or objects employed by the presentation JSP, as well as for deciding, counting on the user’s actions, which JSP to forward this request to. There is no processing logic within the presentation JSP itself and it simply liable for retrieving any objects or beans which will are previously created by the Servlet and extracting the dynamic content for insertion within static templates.
JSP Processing and its flow
JSP stands for Java Server Pages. We can develop a web application with dynamic Input Screens and dynamic output screens by using JSP. The current version of JSP is JSP2.2. JSP pages are automatically compiled by the Server, such as Tomcat and Weblogic. Web pages created by using JSP are portable and can be used easily across multiple platforms and WebServers without making any changes. One of the most important benefits of JSP is the separation of business logic from the presentation logic. JSP pages are often accessed directly as an easy HTML page.
- JSP is actually a powerful scripting language (interpreted language) executed on the server-side (like CGI, PHP, ASP.) and not on the client-side (unlike scripts written in JavaScript or Java applets which run in the browser of the user connected to a site).
- JSPs are integrated into a web page in HTML using special tags that will notify the web server that the code included within these tags are to be interpreted. The result (HTML codes) is going to be returned to the client browser.
- Java Server Pages are part of a 3-tier architecture: where a server supporting the Java, server Pages (generally referred to as application server) will act as a mediator between the client browser and a database (generally mentioned as a data server). JSP provides the necessary elements for the connection to the database management system and allows the manipulation of data through SQL.
A page using Java Server Pages is executed during the query, by a JSP engine (generally running with an internet Server or an application server). The JSP model springs from the one used for Java servlets (JSP is indeed how to write down servlets). It is a Java class derived from Servlet class, making use of using doXXX() to return an HTTP response. When a user calls a JSP page, the server calls the JSP engine which creates a Java source code from the JSP script and compiles the class to provide a compiled file (with the .class extension). Note that the JSP engine checks if the date of the .jsp file corresponds to the .class file. The JSP engine will convert and compile the category, as long as the JSP script has been updated. Thus, the very fact that the compilation only takes place when the JSP script is updated, makes JSP, one among the fastest technologies to make dynamic pages. JSPs are used to create servlets, by including specific tags in the JSP code. In this way, they supply a quick technology to make dynamic pages.
JSP Components
Java Server Pages are text files that combine standard HTML and new scripting tags. JSPs appear as if HTML, but they get compiled into Java servlets the primary time they’re invoked. The resulting servlet may be a combination of HTML from the JSP file and embedded dynamic content specified by the new tags. Everything in a JSP page can be divided into two categories:
- Elements that are processed on the server
- Templates data or everything other than elements, that the engine processing the JSP engines.
Elements data or that part of the JSP which is processed on the server can be classified into the following categories:
- Directives
- Scripting Elements
- Standard actions
Directives
JSP Directives function messages to the JSP container from the JSP. They are wont to set global values like class declaration, methods to be implemented, output content type, etc. They do not produce any output to the client. All directives have the scope of the whole JSP file. That is, a directive affects the entire JSP file, and only that JSP file. Directives are characterized by the @character within the tag.
Scripting Elements
Scripting Elements are wont to include scripting code (Java code) within the JSP. They allow the declaration of variables and methods, include arbitrary scripting code and evaluate an expression.
Standard Actions
Standard Actions are specified tags that affect the runtime behavior of the JSP and affect the response sent back to the client. The JSP specification lists some standard action types to be provided by all containers, regardless of the implementation. Standard actions provide page authors with some basic functionality to exploit; the vendor is free to provide other actions to enhance behavior.
What is MVC?
MVC stands for Model-View-Controller. It is a design pattern used for developing web applications. It is a layout pattern used to isolate the information, presentation logic, business logic. Web application Logic is divided into three logics:
- Presentation Logic
- Business Logic
- Persistent Logic
Each one is called Model or Tier. MVC is popular because it isolates the appliance logic from the interface layer and supports the separation of concerns. Here the Controller receives all requests for the appliance then works with the Model to organize any data needed by the View. The View then uses the information prepared by the Controller to get a final presentable response. The MVC abstraction is often graphically represented as follows.
What is a Model?
It is a module or tier which contains persistent logic or database operation. The model uses JDBC, Hibernate, JPA. The Model segment compares to each one among the knowledge related rationale that the client works with. This can speak to either the information that is being exchanged between the View and Controller segments or some other business rationale related information.
What is a Controller?
The controller controls the flow of execution of web applications. In web application development servlet is called a controller. Controller receive request/input from the client and uses other modules to perform operations. The controller contains Business Logic. Controllers set about as an interface amongst Model and consider segments to process all the business rationale and approaching solicitations, control information utilizing the Model part, and cooperate with the Views to render the last yield.
What is View?
The view is used for generating input and output. It contains presentation logic. This is developed using HTML or JSP. The View part is utilized for all the UI rationale of the application.
Advantages of MVC
- The main advantage of using MVC in a Web Application is it makes complex applications easy to manage with divisions of Model, View, and Controllers.
- MVC provides a strong routing mechanism with the Front Controller pattern.
- MVC works well for development with large teams with multiple web developers and designers working simultaneously.
- In MVC, separating the model from View makes the web application more robust and easier to maintain.
- In MVC, separating the Controller from the Model allows configurable mapping of user actions on the Controller to application functions on the Model.
Example of MVC in JSP
In this example, we are showing how to use MVC architecture in JSP. In this example, we are creating an example in which servlet as a controller, JSP as a view component, Java Bean class as a model. In this example, we have created 6 pages.
- index.jsp
- ControllerServlet.java
- LoginBean.java
- login-success.jsp
- login-error.jsp
- web.xml
Where index.jsp helps us to get the input from the user. ControllerServlet.java acts as a controller, login-success.jsp and login-error.jsp file acts as a view component. Login-success.jsp page will show the “Welcome” message if the user will successfully login whereas login-error.jsp page will show the error message and returns you back to the index.jsp page. LoginBean.java acts as a Model Layer and web.xml file is used to mapping the servlet.
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <form action="ControllerServlet" method="post"> Name:<input type="text" name="name"><br> Password:<input type="password" name="password"><br> <input type="submit" value="login"> </form> </body> </html>
LoginBean.java
public class LoginBean { private String name, password; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public boolean validate() { if (password.equals("admin")) { return true; } else { return false; } } }
ControllerServlet.java
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ControllerServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String name = request.getParameter("name"); String password = request.getParameter("password"); LoginBean bean = new LoginBean(); bean.setName(name); bean.setPassword(password); request.setAttribute("bean", bean); boolean status = bean.validate(); if (status) { RequestDispatcher rd = request.getRequestDispatcher("login-success.jsp"); rd.forward(request, response); } else { RequestDispatcher rd = request.getRequestDispatcher("login-error.jsp"); rd.forward(request, response); } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } }
login-succes.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title></title> </head> <body> <% out.print("Welcome"); %> </body> </html>
login-error.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <p>Sorry! username or password error</p> <%@ include file="index.jsp"%> </body> </html>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <servlet> <servlet-name>s1</servlet-name> <servlet-class>ControllerServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>/ControllerServlet</url-pattern> </servlet-mapping> </web-app>
Output
Run your code to get the following output. Enter your Name(any) and Password as “admin” and then click the “login” button.
After clicking on the “login” button, if your password is correct, you will get the following output.
After clicking on the “login” button, if your password is incorrect, you will get the error message and you will be directed back to the index page.
In the next article, I am going to discuss the JSP Life Cycle Phases and Methods. Here, in this article, I try to explain the JSP Architecture. I hope you enjoy this JSP Architecture article.