JavaServer Pages (JSP) first appears in 1999 as an alternative to ASP and PHP for writing server-side software easily.
Like ASP and PHP, JSP allows code (in its case, Java) to be interleaved with HTML. The Java code is delimited by <% and %> and can refer to the following objects:
- out, a PrintWriter
- request, an HttpServletRequest
- response, an HttpServletResponse
- session, an HttpSession. Note that a JSP always runs within a session. This is mandated by the J2EE specs.
Write a small Java web application which:
- allows the user to enter an integer and when submit is clicked
- calculates and shows its factorial by using a JSP. This means that the code for doing the calculation as well as for creating the output needs to belong to the same JSP.
We are going to enhance the web application so that the logic for the calculation of the factorial is encapsulated in a distinct class. We will make that class follow JavaBean conventions so that we can use it easily from a JSP. In essence, a class is a JavaBean if the following are all true:
- It must have a public default constructor
- It must provide getters and setters for accessing attributes
- It must be serializable
JavaBeans can then easily be used, properties set and retrieved
Web applications generally follow a MVC (Model View Controller) architecture. In such an architecture, the application has three types of components:
- Controllers receive HTTP requests, call upon Models for all domain logic and then select a View
- Models manage the domain logic (business rules as well as data)
- Views render HTTP responses
We can enhance our application to become MVC compliant by implementing a controller as a Servlet. The controller gets a request, calls appropriate methods on our existing JavaBean to get the factorial (this is our model), sets the factorial as another attribute of the request and then selects a JSP (our view) for producing an HTML response.
The JSP can then access the attribute from its requestScope using Expression Language. The requestScope maps attribute names to their values. It allows JSP to access the attributes of the request object.
Leave a Reply