Java Server Pages Introduction
Servlet Drawbacks Web page designer will need to know servlets to design the page. Servlet will have to be compiled for every change in presentation. Servlet with too many embedded HTML tags become very difficult to read. Servlet programmer will have to be a page designer also.
JSP advantage JSPs allow web pages to be created dynamically. JSPs are basically files that combine standard HTML and new scripting tags. JSP specification is to simplify the creation and management of dynamic web pages, by separating logic and presentation. JSPs are important part of J2EE specification.
Deciding between Servlet and JSP MVC architecture JSP is mostly used as View Servlet is Controller Models are Java beans or entity beans.
Most common scenario HTML/JSP Page Servlet Form submitted Java Bean Form data validated and passed Form data stored
How does JSP work?
More… It takes longer time for the first JSP page to load. Time taken to load any subsequent requests for the same page is same as that of a servlet. JSP documents are written in plain text and have a.jsp file extension.
JSP Language Basics
Scripting element JSP elements embedded with HTML tags. Scriplets are small pieces of java code added to a JSP page to provide logical functionality. Scriplets are enclose within. Expressions are use to evaluate a single code expression then add the result to the JSP page as text String.. Comments : (Inside scriptlets ): //, /* */.
Example 1: Displays current date and time Example 1 Server date and time is
Local Variables The JSP turns into a servlet class and all the scriptlets are placed inside a single method of this class (called _jspservice() method equivalent to the service() method of the HttpServlet). So, all the variables that is declared inside the scriptlet is local to that method. Therefore, local variables are available locally to all the other code in that page. Example in 1 has a local variable 'now' declared.
Example 1 Server date and time is public class XJSP extends HttpJspPage { public void jspInit(){..} public void jspDestroy(){..} public void _jspService(){ //scriptlet code converted } jspInit(), jspDestroy() and _jspService() are similar to init(), destroy() and service() method of HttpServlet. While implementations for jspInit() and jspDestroy() methods can be provided in the JSP, implementation for _jspService() should never be provided. This method will be generaeted by the container.
JSP Declarations In order to make declarations such that variable is not only available locally to all the other code in that page but also available globally to other parallel requests for that page, we have to use – Methods also can be declared here.
Example 2: Global page counter Example 1 Date and Time: <%! int counter=0; java.util.Date getDate(){ return new java.util.Date() }%> Thank you for visiting this page You are vistor number. jsp/1.pageCounter
9 Implicit JSP objects: 1. request object request object : This object can be used to access lots of information contained in the HTTP request header sent from a browser when requesting a JSP page. The request object is analogous to request object in servlet. Common Examples:
Implicit JSP objects: 2. response object response object: This object is used in response header that are sent to the browser from the server along with the current page. The request object is analogous to request object in servlet. Common Examples:
Implicit JSP objects: 3. application object application object: This object is used to hold references to other objects that may be accessed by multiple users. One such object is database connectivity. Represents the ServletContext object in servlet. Methods: getAttribute(), setAttribute(). Common Examples: <% application.setAttribute("applName", "CollegePortal"); %>
Implicit JSP objects: 4.session object When a JSP page is opened in a browser a unique session identity is allocated for each user accessing that application. Represents HttpSession object in Servlet Methods: getAttribute(), setAttribute(), invalidate(),getId().
Example 3: session object Session ID : <% session.invalidate(); if (session.getId() !=null) %> Session ID : Session has ended
Implicit JSP objects: 5.out object This object handles text output to browser from the JSP page. An instance of javax.servlet.jsp.JspWriter.. Example: " + application.getAttribute("application Name") + " "); %>
6. exception exception object: The exception object is available only to pages which are defined as error pages by setting the value for the attribute isErrorPage in the page directive. More about this later
7. page this
8. pageContext Used to organize references to all of the objects involved in creating a jsp page. JSP engine writes the code that obtains the implicit objects from this object. getException() getPage() getOut() getRequest() getResponse getSession() getResponse() getServletConfig() getServletContext()
9.config Similar to ServletConfig class
Directives
JSP Directives JSP directive are messages that are sent to JSP processor from JSP. These are used to set global values for the jsp page and do not produce any output. The page directive The include directive
Page directive A page can contain any no. of page directives, anywhere in the jsp. However, there can be only one occurrence of any attribute/value pair defined by the page directive in a given jsp. Only exception is the import attributes.
page directive attributes contentType: Specifies the MIME type to be used for JSP page that is going to be generated. (default: text/html) errorPage: Defines a URL to another JSP page, which is invoked if an unchecked runtime exception is thrown. isErrorPage: If true, then current jsp page is an error page for another jsp page. Gives access to a JSP implicit exception variable when true to allow an error to be examined and handled.
import: similar to import statement in java class Classes within the following packages are available by default: java.lang.*, javax.servlet.*, javax.servlet.jsp.*, javax.servlet.http.* Example: session: If true, the implicit object variable session will refer to a session object either already existing for the requesting user, or explicitly created for the page invocation. If false, then any reference to the session implicit object within the JSP page results in a translation-time error. The default is true. If your JSP page is not intended to interact with session objects then creation of session object could be an overhead. If this is the case, then you should ensure that the directive tag is included within your JSP.
Example: using ‘import’ Example 1 Server date and time is
Example: Runtime Error handling Error Handling Number1: divided by Number2: divide.jsp jsp/2.error_handling
Result: <input type="text" name="result" value=" <% String num1=request.getParameter("num1"); String num2=request.getParameter("num2"); if (num1!=null && num2!=null){ int n1=Integer.parseInt(num1); int n2=Integer.parseInt(num2); int r= n1/n2; out.print( r); } } %>">
Error Handling Error: error.jsp
Include directive This tag is useful to merge the content of an external static file with the contents of a JSP page. Example:
JSP tag included The included file may contain any valid JSP tags. These tags will be translated to Java source and included in the JSP page compilation class. One consequence of the fact that the file referenced within the include directive is included during the translation phase is that subsequent changes to the included file will not be picked up by the Web container on subsequent invocations of the JSP. The changes will only be visible when the JSP containing the include directive is itself updated, or its JSP page compilation class is deleted, forcing the translation phase to be carried out. If this behavior is not desirable you can use the include action tag instead.
JSP Action tags
Java Beans A java bean is simply a java class that meet the following criteria: 1. The class must be public. 2. The class must have a no-arguments constructor. 3. The class must provide set and get methods to access variables.
Standard Action Tags These tags translate into to certain predefined java code. They are used so that the JSP file doesn't have to many embedded java code.
This action tag is used to instantiate or create a reference to a Java Class (Bean) inside a JSP page. id: variable name for the Java Class that is going to be used in the JSP. class: Fully qualified class name scope: page, request, session and application. Default is page. type:This is optional. Indicates the type of object to be created. Student s=new Student() ;
Scope page scope means that the object available only to this page. request scope means that the object is now associated with the request. If the request is forwarded (using or tag ) to another JSP, the object is available. This object can be accessed by invoking getAttribute() method on request object. session scope means that object will be available to all JSPs in the current session. application scope means that the object will be available in any JSP page in the same web application. This object can be accessed by invoking getAttribute() method on request object.
and tag is used along with tag, to set values of the bean property. tag is used along with tag, to get values of the bean property.
Attributes Values beanName is the name of the bean instance which has been created using the tag. property: name of the bean property. It can also be ’*’. If so, if request parameters have the same name as the bean property, then the value of the request parameter is automatically set to the bean property. value: Value to be set to the property. param:The name of the request parameter whose value the bean property will be set to. property=“property” value=”value” property=“property” property=“property” param =”param” property=“*”
.. sr.Student -name -reg +String getName() +String getReg() Student.java +void setReg(String reg) +void setName(String nm) JSP page implementation class will attempt to assign the value of request.getParameter(“name”) to the bean property. Displays value of reg request. getParameter(“n m”)
sr.Student -name -reg +String getName() +String getReg() <jsp:useBean id=“stud” class=“sr.Student”> <jsp:setProperty name=“stud” property=“*”/> ….. … Student.java stud.jsp stud.html On submitting the form the name and reg property of the stud bean is automatically set to the values entered by the user. If there is no matching request parameter for a bean property then it remains unset. You should always make sure that your bean’s default constructor sets appropriate default values. +void setName(String nm) +void setReg(String reg)
The Web container will automatically attempt to convert the String into the type of the bean parameter. This conversion will work for the following types: Boolean or boolean Byte or byte Character or char Double or double Integer or int Float or float Long or long
The action is used to provide other tags with additional information in the form of the name- value pairs. It is used in conjunction with the &
This tag allows static or dynamic resource to be included in the current JSP page at the request processing time. Similar to RequestDispatcher’s include() method.
Example The argument can be extracted by using request.getParameter(“p1”) in servlet/jsp.
and Done at the request processing time 2. Done at the translation time.(That is, the contents of the included file will be included in the JSP source at the point where the tag is defined and therefore processed by the JSP page compilation procedure. 3. Both static and dynamic content can be included. 3. The included file may contain both static content and other JSP tags.
This tag allows the JSP to transfer the control to another JSP, servlet or static HTML page. The jsp that forwards the request should not use the output stream that is used to communicate to the client prior to forwarding the request.
Example: Forward action test page Forward action test page Please enter your username: forward.html jsp/4.forward
and password: input type=“submit” value=“Log in”>
<% if ((request.getParameter(“userName”).equal s (“Kumar”)) && (request.getParameter(“password”). equals(“xyzzy”))) { %> forward.jsp
Example: forward2.jsp Forward action test: Login successful! (h1>Forward action test: Login successful! Welcome, jsp/5.param