You are on page 1of 102

Servlets

According to Servlet specification a web application is a collection of web resources. There are two types of web resources. 1) static resources : - html files, xml files, jpg files etc 2) dynamic resources : - servlet, jsp (java server page), asp (active server page), cgi programs. Servlet based application can be developed (placed) on the servlets like Tomcat, web logic, web sphere, etc that supports servlet API (specification). We can develop the web applications using the servlet technology that is part of java enterprise edition. A servlet object is a java object that provides the implementation of javax.servlet.Servlet interface.

implements

implements

extends extends extends

SOne class is not a servlet class. The object based on SOne class is not a servlet object. STwo, SThr, OurSrv classes implements the Servlet interface direct or indirectly. These classes are called as Servlet objects. import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class OurSrv extends HttpServlet { public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out=response.getWriter( ); System.out.println(request.getMethod( )); System.out.println(request.getRequestURI( )); System.out.println(request.getProtocol( )); System.out.println(request.getHeader("User-Agent")); out.println("executed"); } } D:\Pskr>javac OurSrv.java

6 errors Because the path is not set to the current directory, so copy the weblogic.jar or servlet-api.jar to the current directory & set the class path & try again compile D:\Pskr>set CLASSPATH=weblogic.jar;. D:\Pskr>javac OurSrv.java D:\Pskr>

REQUEST

RESPONSE Client Web container (Tomcat, web logic .etc) A web container is product that supports the web application develop using servlet technology. Web containers are developed in java language according to the servlet specification given by java soft. Some of the popular web containers are Tomcat, web logic, web sphere, sun one server, oracle application server . Etc. All these web containers support the HTTP protocol. Every web container vendor provide a jar file that contains servlet related packages (javax.servlet, javax.servlet.http). Procedure for assembling for web application: 1) Create a WEB-ROOT directory ex: - d:\ourwapp 2) Create a directory with the name WEB-INF under the WEB-ROOT directory. 3) Create the following 2 directories under the WEB-INF a) Classes ---- used to place .class files b) lib --- used to place .jar files 4) The static resources like html, xml, jpg etc must be placed under WEB-ROOT or the sub directories of WEB-ROOT except WEB-INF. D:. ourwapp Sdir WEB-INF classes lib 5) Copy the servlet classes under WEB-INF/classes directory 6) Provide the web.xml (deployment descriptor) under WEB-INF directory. 7) create a war file using a jar tool a) open a dos window and use cd command to move to the WEB-ROOT directory D:\Pskr>cd ourwapp b) Use the following command to create a war file D:\Pskr\ourwapp>jar cf ourwapp .

Here cf means create file & . means current directory Copy the OurSrv.class under ourwapp\WEB-INF\classes directory. <html> <head> <title>one.html</title> </head> <body> welcome to one.html </body> </html> Copy the one.html to ourwapp or Sdir. <web-app> <display-name>My Web Application</display-name> <description> info about my app </description> <servlet> <servlet-name>oursrv</servlet-name> <servlet-class>OurSrv</servlet-class> </servlet> <servlet-mapping> <servlet-name>oursrv</servlet-name> <url-pattern>/os</url-pattern> </servlet-mapping> </web-app> Copy the web.xml under ourwapp\WEB-INF directory. To deploy the above web application in web logic copy ourwapp.war to C:\bea\user_projects\domains\sunil\applications. In case of Tomcat the war file is copied must under C:\programfiles\Apache Software Foundation\Tomcat\web apps while starting the web application, web container reads the information available in web.xml file. Web container can not start the web application, if there is a problem in web.xml file. Start the server & Open the internet explorer & type the URL http://localhost:7001/ourwapp/one.html Welcome to one.html Here ourwapp is the context path of the web application When the browser sends the request to one.html (static resource), we (web container) picks of the content of one.html & sends it to the browser as part of the response. http://localhost:7001/ourwapp/os executed GET

/our/os HTTP/1.1 Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) When the browser sends the os (dynamic resource), we execute the service method on os object & the content generated by the code will be sent to the browser as part of the response. out.println --- sends to the browser system.out.println --- sends to the server In case of Tomcat, web logic the exploded directory structure of the web application can copied in place of the war file. What is the difference between static resource & dynamic resource: A) html files are static resources, servlets are dynamic resources. Ex: <html> <head> <title>dd.html</title> </head> <body> welcome <br> Date & time : 1-feb-2008, 1:40 p.m </body> </html> http://localhost:7001/srdr/dd.html welcome Date & time : 1-feb-2008, 1:40 p.m Once again refresh the URL welcome Date & time : 1-feb-2008, 1:40 p.m

dd.html Web container Client When a client sends the request for dd.html, the web container picks up the content of dd.html and sends that to the client as part of the response. In case of the static resources the server picks up the content of the file and sends that to the client as part of the response. <web-app>

<servlet> <servlet-name>ddsrv</servlet-name> <servlet-class>DDSrv</servlet-class> </servlet> <servlet-mapping> <servlet-name>ddsrv</servlet-name> <url-pattern>/date</url-pattern> </servlet-mapping> </web-app> import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class DDSrv extends HttpServlet { public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out=response.getWriter( ); java.util.Date n=new java.util.Date( ); response.setContentType("text/html"); out.println(n); } } D:\Pskr\srdr>javac DDSrv.java http://localhost:7001/srdr/date Date & Time: Mon Feb 04 12:31:08 IST 2008 Once again refresh the URL Date & Time: Mon Feb 04 12:31:54 IST 2008

DDSrv class Web container Client In case of a dynamic resource the web container execute the code to process the request and sends the content generated by the code. To generate the content dynamically we can use asp, port script etc The following steps will be carried out when the client sends a web container for servlet. 1)web container creates req and resp objects. 2)Web container calls the service method by passing req & resp objects created in step one

3)The object generated by the servlet code will be send to the browser 4)Web container unreferenced (removes) req, resp objects. HttpServletRequest, HttpServletResponse are the interface provided by the java soft has part of servlet API. The web container implementers are responsible for providing the class implementing HttpServletRequest, HttpServletResponse interfaces.

extends

implements

implements

extends

implements

implements

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class Hsr extends HttpServlet { public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println(request.getClass( ));

System.out.println(response.getClass( )); } } D:\Pskr\srdr>javac Hsr.java http://localhost:7001/hsr/hsr class weblogic.servlet.internal.ServletRequestImpl class weblogic.servlet.internal.ServletResponseImpl What is the difference between ServletConfig and ServletContext: A) ServletConfig, ServletContext are the interfaces provided by java soft as part of servlet API. The web container vendors are responsible creating the classes implementing these two interfaces. The internal code of the web container is the responsible for creating the ServletContext object, ServletConfig object. We can run multiple web applications as part of a single web container. Web container is responsible for creating one ServletContext object for every web application while starting the web application. Web container is responsible destroy/removing the ServletContext while stopping the web application. import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class Dst extends HttpServlet { public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletConfig config=getServletConfig( ); System.out.println(config.getServletName( )); } } D:\Pskr>javac Dst.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class Dsg extends Dst { public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletConfig config=getServletConfig( ); System.out.println(config.getServletName( )); } } D:\Pskr>javac Dsg.java

<web-app> <servlet> <servlet-name>dst</servlet-name> <servlet-class>Dst</servlet-class> </servlet> <servlet> <servlet-name>dsg</servlet-name> <servlet-class>Dsg</servlet-class> </servlet> <servlet-mapping> <servlet-name>dst</servlet-name> <url-pattern>/dst</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>dsg</servlet-name> <url-pattern>/dsg</url-pattern> </servlet-mapping> </web-app> http://localhost:7001/dst/dst Dst http://localhost:7001/dsg/dsg Dsg

Web container Here SC means ServletConfig As part of a web application there can be multiple servlets. For every servlet web container creates a ServletConfig object. Note: - ServletContext object is called as an application object. It holds context parameters. ServletConfig holds initialization parameters. import javax.servlet.*; import javax.servlet.http.*; import java.io.*;

public class Scsc extends HttpServlet { public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext application=getServletContext( ); ServletConfig config=getServletConfig( ); System.out.println(application.getServerInfo( )); System.out.println(application.getMajorVersion( )); System.out.println(application.getMinorVersion( )); System.out.println(config.getServletName( )); } } D:\Pskr\srdr>javac Scsc.java http://localhost:7001/scsc/sc WebLogic Server 8.1 SP2 Fri Dec 5 15:01:51 PST 2003 316284 2 3 Scsc <web-app> <context-param> <param-name>cpone</param-name> <param-value>valueone</param-value> </context-param> <servlet> <servlet-name>sone</servlet-name> <servlet-class>SOne</servlet-class> <init-param> <param-name>ipone</param-name> <param-value>aaa</param-value> </init-param> </servlet> <servlet> <servlet-name>stwo</servlet-name> <servlet-class>STwo</servlet-class> <init-param> <param-name>iptwo</param-name> <param-value>xxx</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>sone</servlet-name> <url-pattern>/sone</url-pattern> </servlet-mapping> <servlet-mapping>

<servlet-name>stwo</servlet-name> <url-pattern>/stwo</url-pattern> </servlet-mapping> </web-app> Note: - context parameter cpone can be accessed by all the servlets that are part of the application(sone,stwo). Initialization parameters can be accessed by only the servlets for which the initialization parameter is defined (ipone can be accessed by sone servlet and iptwo can be accessed by stwo servlet). import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class SOne extends HttpServlet { public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out=response.getWriter( ); response.setContentType("text/plain"); ServletContext application=getServletContext( ); ServletConfig config=getServletConfig( ); out.println("cpone--->"+application.getInitParameter("cpone")); out.println("ipone--->"+config.getInitParameter("ipone")); out.println("iptwo--->"+config.getInitParameter("iptwo")); } } D:\Pskr\srdr>javac SOne.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class STwo extends HttpServlet { public void service(HttpServletRequest HttpServletResponse response) throws ServletException, IOException { PrintWriter out=response.getWriter( ); response.setContentType("text/plain"); ServletContext application=getServletContext( ); ServletConfig config=getServletConfig( ); out.println("cpone--->"+application.getInitParameter("cpone")); out.println("ipone--->"+config.getInitParameter("ipone")); out.println("iptwo--->"+config.getInitParameter("iptwo")); } }

request,

D:\Pskr\srdr>javac STwo.java http://localhost:8001/ex/sone cpone--->valueone ipone--->aaa iptwo--->null http://localhost:8001/ex/stwo cpone--->valueone ipone--->null iptwo--->xxx We can use response.sendError( ) method to send the information about a failure from the servlet to the client. import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class DBConnect extends HttpServlet { public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out=response.getWriter( ); try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:xe","scott","tiger"); // code to connect to DB out.println("Connected to db"); con.close( ); } catch(Exception e) { response.sendError(502,"error---"+e); } } } D:\Pskr>javac DBConnect.java http://localhost:8000/dbcon/d HTTP Status 502 oracle.jdbc.driver.OracleDriver So copy the ojdbc14.jar into lib directory.

error---

java.lang.ClassNotFoundException:

http://localhost:8000/dbcon/d Connected to db The above servlet DBConnect is not flexible. Whenever the changes made to the database setup (changing the user name or password etc), the above servlet fails to connect to the server. http://localhost:8080/apex

SQL> connect scott/tiger ERROR: ORA-01017: invalid username/password; logon denied SQL> connect scott/sun Connected. SQL> http://localhost:8000/dbcon/d HTTP Status 502 - error---java.sql.SQLException: username/password; logon denied

ORA-01017:

invalid

<web-app> <context-param> <param-name>drvcls</param-name> <param-value>oracle.jdbc.driver.OracleDriver</param-value> </context-param> <context-param> <param-name>url</param-name> <param-value>jdbc:oracle:thin:@localhost:1521:xe</param-value> </context-param> <context-param> <param-name>uname</param-name> <param-value>scott</param-value> </context-param> <context-param> <param-name>pwd</param-name> <param-value>sun</param-value> </context-param> <servlet> <servlet-name>d</servlet-name> <servlet-class>DBConnect1</servlet-class> </servlet>

<servlet-mapping> <servlet-name>d</servlet-name> <url-pattern>/d</url-pattern> </servlet-mapping> </web-app> import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class DBConnect1 extends HttpServlet { public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext application=getServletContext( ); String vdrvcls,vurl,vuname,vpwd; vdrvcls=application.getInitParameter("drvcls"); vurl=application.getInitParameter("url"); vuname=application.getInitParameter("uname"); vpwd=application.getInitParameter("pwd"); PrintWriter out=response.getWriter( ); try { Class.forName(vdrvcls); Connection con=DriverManager. getConnection(vurl,vuname,vpwd); out.println("--connected to db--"); con.close( ); } catch(Exception e) { response.sendError(502,"error---"+e); } } } D:\Pskr>javac DBConnect1.java http://localhost:8000/dbcon1/d --connected to db Once again change the password sun into tiger in to the database. SQL> connect scott/tiger Connected. SQL> http://localhost:8000/dbcon1/d HTTP Status 502 - error---java.sql.SQLException: ORA-01017: username/password; logon denied

invalid

The code of DBConnect1 is not flexible, but it is more flexible into the code of DBConnect. As part of Servlet interface the following 5 methods are provided 1)void init(ServletConfig config) 2)ServletConfig get ServletConfig( ) 3)void service(ServletRequest req, ServletResponse resp) 4)String getServletInfo( ) 5)void destroy( ) Note:- init,service,destroy are called as life-cycle methods of a servlet. import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class SOne implements Servlet { ServletConfig config=null; public void init(ServletConfig config)throws ServletException { this.config=config; System.out.println("----init----"); } public ServletConfig getServletConfig( ) { return this.config; } public void service(ServletRequest req,ServletResponse resp) throws ServletException, IOException { HttpServletRequest request=(HttpServletRequest)req; HttpServletResponse response=(HttpServletResponse)resp; System.out.println("----service----"); } public String getServletInfo( ) { return "srv impliments to learn srv basics;Author:student"; } public void destroy( ) { this.config=null; System.out.println("----destroy----"); } } D:\Pskr>javac SOne.java http://localhost:8000/ser/ser ----init----

----service---Refresh the URL into 4 times. ----init-------service-------service-------service-------service-------service---In this case service method executed from 1 to n times. Open the internet & type the URL http://localhost:8000 & click Tomcat Manager & stop the ser application.

----init-------service-------service-------service-------service-------service-------destroy---newInstance( ) init(ServletConfig config)

destroy( )

service(ServletRequest res,ServletResponse resp) client request for srv As web container call init, service, destroy at various stages of the life of the servlets. These methods are called as life cycle methods. These 3 methods are mint to be called by web container. The code provided by us should not call these 3 methods. According to Servlet specification web container is responsible for calling init( ) method after creating the Servlet. Web container is responsible for calling destroy( ) method before removing/destroying/ un-referencing the servlet object. According to the Servlet specification, web container can create a servlet object at any point of time & destroy the servlet object at any point of time.

If we configure a servlet using load-on-startup element then web container is responsible for creating the servlet object during startup. <web-app> <servlet> <servlet-name>ser</servlet-name> <servlet-class>SOne</servlet-class> <load-on-startup>9</load-on-startup> </servlet> <servlet-mapping> <servlet-name>ser</servlet-name> <url-pattern>/ser</url-pattern> </servlet-mapping> </web-app> The number in load-on-startup is used to describe about the sequence in which the servlet object has to be created. The servlet with the lowest number will be created first & the servlet with the highest number will be created at end. http://localhost:8000/ser/ser ----init---Open the internet & type the URL http://localhost:8000 & click Tomcat Manager & stop the ser application. ----init-------destroy--In this case service method executed from 0 to n times. If load-on-startup is not provided then a web containers creates the servlet object when they receive for the first request for a servlet. If we replace a old servlet class with a new servlet class and send a request then some web containers destroy the old object and creates a new object using the new class. http://localhost:8000/ser/ser ----init-------service--- System.out.println("****New:service****"); (put **** in place of ----) D:\Pskr>javac SOne.java Copy the SOne class into C:\Tomcat5.0\webapps\ser\WEB-INF\classes directory & refresh the URL http://localhost:8000/ser/ser ----init-------service-------service---http://localhost:7001/ser/ser ----init-------service---Copy the SOne class into C:\bea\user_projects\domains\sunil\applications\ser\WEBINF\classes directory & refresh the URL http://localhost:7001/ser/ser ----init----

----service-------destroy---****init**** ****service**** ****New:service**** When a web container receives a request for non existing servlet object and if there is no space for creating a new servlet object, then the web container can remove the existing servlet objects and use that space to create the new servlet object. A web container typically destroys the servlet object while stopping the web application. Can we provide a constructor in a servlet, web containers uses newInstance( ) method for creating a servlet object by using a zero argument constructor only in a servlet (most of the developers avoids the constructors and has code to be executed when the object is created will be provided inside init( ) method). can we call (our code) the destroy method? A) 1. We can provide the code to call the destroy( ) method but it is not recommended. 2. Typically the code in the destroy( ) method un-references ServletConfig object. After un-referencing the ServletConfig object our servlet will fail, if our code tries to use the ServletConfig object. 3. The web container does not remove the servlet object, if our code calls the destroy( ) method. Servlet technology is designed by java soft to be implemented in different kinds of servers like server supporting various protocols (HTTP, SMTP, X protocol etc).

----------Server supporting HTTP Protocol Server supporting X Protocol Server supporting Y Protocol

As shown in the above diagram there can be infinite types of servlets.

implements

extends

extends

Note: - Web container always calls the first init( ) method only. import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class OurSrv extends HttpServlet { public void init( )throws ServletException { System.out.println("----init( )----"); } public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out=response.getWriter( ); ServletConfig config=getServletConfig( ); out.println(config.getServletName( )); } } D:\Pskr>javac OurSrv.java http://localhost:7001/in/in in ----init( )----

When the web container creates the object using OurSrv class the following steps will be carried out. 1) Web container calls the first init method. 2) JVM checks for first init( ) method in OurSrv. Then the JVM checks for the first init( ) method in HttpServlet and then in GenericServlet . As the first init method is available in GenericServlet, the JVM start the execution of first init( ) method of Generic Servlet. 3) When the first init( ) method of GenericServlet calls the second init( ) method. The JVM checks for the second init( ) method in OurSrv class. 4) The second init( ) method is available in OurSrv the JVM executes the second init( ) method of OurSrv Can we provide the first init( ) method in our public void init(ServletConfig config)throws ServletException { // our code as per req } http://localhost:7001/in/in Error 500--Internal Server Error java.lang.NullPointerException When the web container calls the first init( ) method, the JVM execute the first init( ) method provided by us (shown above). In this case the init( ) method of GenericServlet is not executed and the config variable available in the GenericServlet will be null. If our code tries to use the ServletConfig object then it will fail. To avoid the failure we must provide the code for the first init( ) as shown below public void init(ServletConfig config)throws ServletException { super.init(config); // our code as per req } http://localhost:7001/in/in in ----init( )---Most developers implements the second init( ) method instead of implementing the first init( ) method and calling the super class first init( ) method. public void init( )throws ServletException { // our code as per req }

implements

extends

extends

Note: -here Xxx ---- Get, Post, Head, Delete ----- etc. The following steps will be carried out in the server when a clients sends the request for OurSrv. 1) Web container calls the first service( ) method. 2) The JVM start the execution of first service method of HttpServlet class. 3) The first service method of HttpServlet calls the second service method. 4) The JVM executes the second service method of OurSrv. import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class OurSrv extends HttpServlet { public void service(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { System.out.println("----our second service----"); PrintWriter out=response.getWriter( ); out.println("--Http Req method-->"+request.getMethod( )); } } D:\Pskr>javac OurSrv.java http://localhost:8000/se/in --Http Req method-->GET ----our second service----

By implementing the second service method (as shown above), we can deal with any kind of request methods (Get, Post . Etc) To deal with Post request only, doPost( ) method can be provided in the servlet as shown below import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class OurSrv extends HttpServlet { public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { PrintWriter out=response.getWriter( ); out.println("--Http Req method-->"+request.getMethod( )); } } D:\Pskr>javac OurSrv.java http://localhost:8000/se/in --Http Req method-->GET JSP JSP stands for java server page. A java server page is a servlet. JSP technology simplifies the deployment of a web application using servlet technology. one.jsp: - Line one <br> Line two <br> The web container takes care of running the Jspc (JSP compiler) for generating a servlet class from a JSP file. We can follow the steps given below to run the Jspc of weblogic. Steps: - 1) open the dos shell and run setenv command C:\bea\user_projects\domains\sunil>setenv 2) Using cd command move to the directory in witch the JSP file is placed. D:\>cd pskr D:\Pskr>cd jsp D:\Pskr\jsp> 3) Run the JSP compiler using the command shown below. D:\Pskr\jsp>java weblogic.jspc -keepgenerated one.jsp If keepgenerated will not used by JSP compiler removes the .java file that is generated. Template Text one.jsp

XXXoneXXX.java

XXXoneXXX.class Once the class file is generated the web container treats the class as any other Servlet class developrd manuvally. The JSP compiler generates the .java file that contains the code similar to the one shown below. /* compiled from JSP: /one.jsp * * This code was automatically generated at 10:36:40 PM on Feb 20, 2008 * by weblogic.servlet.jsp.Jsp2Java -- do not edit. */ package jsp_servlet; import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; // User imports // built-in init parameters: // boolean _verbose -- wants debugging // Well-known variables: // JspWriter out -- to write to the browser // HttpServletRequest request -- the request object. // HttpServletResponse response -- the response object. // PageContext pageContext -- the page context for this JSP // HttpSession session -- the session object for the client (if any) // ServletContext application -- The servlet (application) context // ServletConfig config -- The ServletConfig for this JSP // Object page -- the instance of this page's implementation class (i.e., 'this') /** * This code was automatically generated at 10:36:40 PM on Feb 20, 2008 * by weblogic.servlet.jsp.Jsp2Java -- do not edit. *

* Copyright (c) 2008 by BEA Systems, Inc. All Rights Reserved. */ public final class __one extends weblogic.servlet.jsp.JspBase implements weblogic.servlet.jsp.StaleIndicator { // StaleIndicator interface public boolean _isStale( ) { weblogic.servlet.jsp.StaleChecker sci = (weblogic.servlet.jsp.StaleChecker)(getServletConfig( ).getServletContext( )); java.io.File f = null; long lastModWhenBuilt = 0L; if (sci.isResourceStale("/one.jsp", 1203527118968L, "8.1.2.0", "Asia/Calcutta")) return true; return false; } public static boolean _staticIsStale(weblogic.servlet.jsp.StaleChecker sci) { java.io.File f = null; long lastModWhenBuilt = 0L; if (sci.isResourceStale("/one.jsp", 1203527118968L, "8.1.2.0", "Asia/Calcutta")) return true; return false; } private static void _writeText(ServletResponse rsp, JspWriter out, String block, byte[] blockBytes) throws IOException { if (!_WL_ENCODED_BYTES_OK || _hasEncodingChanged(rsp)) { out.print(block); } else { ((weblogic.servlet.jsp.ByteWriter)out).write(blockBytes, block); } } private static boolean _hasEncodingChanged(ServletResponse rsp) { String encoding = rsp.getCharacterEncoding( ); if ("ISO-8859-1".equals(encoding) || "Cp1252".equals(encoding) || "ISO8859_1".equals(encoding) || "ASCII".equals(encoding)) { return false; } if (_WL_ORIGINAL_ENCODING.equals(encoding)) { return false; } return true; } private static boolean _WL_ENCODED_BYTES_OK = true; private static final String _WL_ORIGINAL_ENCODING = "Cp1252"; private static byte[] _getBytes(String block) { try { return block.getBytes(_WL_ORIGINAL_ENCODING);

} catch (java.io.UnsupportedEncodingException u) { _WL_ENCODED_BYTES_OK = false; } return null; } private final static String _wl_block0 = "Line one <br>\r\nLine two <br>"; private final static byte[] _wl_block0Bytes = _getBytes(_wl_block0); public void _jspService(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws java.io.IOException, javax.servlet.ServletException { // declare and set well-known variables: javax.servlet.ServletConfig config = getServletConfig( ); javax.servlet.ServletContext application = config.getServletContext( ); javax.servlet.jsp.tagext.Tag _activeTag = null; // variables for Tag extension protocol Object page = this; javax.servlet.jsp.JspWriter out; javax.servlet.jsp.PageContext pageContext = javax.servlet.jsp.JspFactory.getDefaultFactory( ).getPageContext(this, request, response, null, true, 8192, true); out = pageContext.getOut( ); JspWriter _originalOut = out; javax.servlet.http.HttpSession session = request.getSession(true); try { // error page try block _writeText(response, out, _wl_block0, _wl_block0Bytes); } catch (Throwable __ee) { while (out != null && out != _originalOut) out = pageContext.popBody( ); ((weblogic.servlet.jsp.PageContextImpl)pageContext).handlePageException((Throwable)__e e); } //before final close brace... } } The JspWriter class is similar to the PrintWriter class. Note: - JspWriter supports buffering and the methods print, println, write of JspWriter throws java.io.IOException. When there is a problem. __jspService( ) method of the servlet generated by JSP compiler is equivalent to the second service method provided by us in the manually developed servlets. The same one.jsp is run in to the Tomcat we must follow some steps. 1) copy the root directory in to the C:\Tomcat5.0\webapps directory. 2) Run the Tomcat server 3) Type the URL http://localhost:8000/jsp/one.jsp Open the one_jsp file is available in the directory C:\Tomcat5.0\work\Catalina\localhost\jsp\org\ apache\jsp

package org.apache.jsp; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class one_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static java.util.Vector _jspx_dependants; public java.util.List getDependants( ) { return _jspx_dependants; } public void _jspService(HttpServletRequest request, HttpServletResponse response)throws java.io.IOException, ServletException { JspFactory _jspxFactory = null; PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { _jspxFactory = JspFactory.getDefaultFactory( ); response.setContentType("text/html"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext( ); config = pageContext.getServletConfig( ); session = pageContext.getSession( ); out = pageContext.getOut( ); _jspx_out = out; out.write("Line one <br>\r\n"); out.write("Line two <br>"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize( ) != 0) out.clearBuffer( ); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); } } finally { if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context); } } }

The JSP compiler generates the code according to a set of rules. Some times the JSP compiler generates the code that may not be required, but a human being can decide what is required & what is not required and he will be a better position to provide the code that is much more efficient then the code generated by the JSP compiler. In majority cases the servlet generated by the JSP compiler gives acceptable performance. In a rare case if there is too much of logic then the performance of the servlets generated by the JSP compiler may not be in acceptable range and in such a case we can go for manually developed servlets. We can use various types of JSP elements in a JSP page. The JSP elements are 1) Template text 2) Script let 3) JSP declarations 4) JSP directives 5) JSP action tags 6) JSP custom tags (tag libraries) 7) JSP expressions 8) EL (expression language) expressions. Template text

Script let

Template text Two.jsp

Two.jsp Browser xtwox.class Web container http://localhost:7001/jsp/Two.jsp Line one Line two Line three Line four 30 When the browser sends the request for Two.jsp, the web container executes the code of the servlets that represent Two.jsp. When the servlet is executed the client/browser receives the template text as it is & the

java code provided in the script let will be executed in the server. If the java code is provided as part of the template text, then it will not be executed in the server. The java code is send to the browser as it is. The JSP compiler places the template text in out.print/out.write statements in __jspService( ) method. The JSP compiler copies the java code of the script let in __jspService( ) method. As part of JSP declarations we can provide the instance variables, static variables, instance methods & static methods. <%! int i=10; static float f=12.34f; void mone( ) { int x=10; System.out.println("----mone----"+x); } static void mtwo( ) { int y=20; System.out.println("----mtwo----"+y); } %> TT one <br> <% System.out.println("----__jspService( ) ----"); mone( ); mtwo( ); %> TT two <br> http://localhost:8000/jsp/inst.jsp TT one TT two ----__jspService( ) -------mone----10 ----mtwo----20 According to the JSP specification every JSP compiler must generate __jspService( ) method with the following two parameters. HttpServletRequest, HttpServletResponse. The JSP compiler is also responsible for generating the code declaring the following variables as local variables of __jspService( ) method. PageContext pageContext, HttpSession session, ServletContext application, ServletConfig config, JspWriter out, Object page. As the above parameters and local variables and declared as part of __jspService, we

can use these variables in the script let code and JSP expressions. The variables that can be used without declaring are called as implicit variables (well-known variables). <% int i=10; int j=20; out.println(i); out.println(j); Expressiomns out.println(i+j); %> http://localhost:7001/jsp/exp.jsp 10 20 30 i & j becomes the local variables of __jspService( ) method. <% int i=10; int j=20; %> <%=i%> <%=j%> <%=i+j%> <%=new java.util.Date( )%> <%=request.getRequestURI( )%> http://localhost:7001/jsp/expression.jsp 10 20 30 Mon Feb 25 15:01:59 IST 2008 /jsp/expression.jsp When the above JSP expressions are executed, the results of the expressions will be sent to the browser. In case of JSPs we can provide the methods jspInit, jspDestroy in the declarations. jspInit( ) method will be executed after creating the servlet object that represent the JSP. jspDestroy( ) method gets executed before the servlet representing the JSP is removed. We can provide the java code as part of script lets, JSP expressions, JSP declarations. Java soft strongly recommends that we should avoid the java code from the JSPs We can not write the import statements in the JSP as shown below import java.sql.*; import java.util.*; The JSP compiler treats the above tool imports statements as Template text <%@ page %> ---> page directive <%@ include %> ---> include directive <%@ page import="java.util.Date" %> <%@ page import="java.sql.Connection" %> <% Connection con; Date now=new Date( ); %> <%=now%>

http://localhost:7001/jsp/directive.jsp Tue Feb 26 11:33:55 IST 2008 A JSP Directive is a instruction given to the JSP compiler. JSP generates the code according to the directives. <%@ JSP directive %> Ex: - <%@ page import="java.util.Date" %> While compiling the above JSPC adds the following import statement to .java file import java.util.Date; The above directive is called as page directive. <%@ page import="java.io.*,java.net.*" %> can be written as <%@ page import="java.io.*" %> <%@ page import="java.net.*" %> <%@ page info="This JSP is for ----" %> JSPC generates getServetInfo( ) method as part of the servlet class. public String getServletInfo( ) { return "This JSP is for ----"; } <%@ page contentType="text/xml" %> JSPC generates the following line as part of __jspService( ) method response.setContentType("text/xml"); The default value of contentType is text/html (is a page directive is not provided with contentType attribute then the JSPC assumes text/html as the value. <web-app> <context-param> <param-name>drvcls</param-name> <param-value>oracle.jdbc.driver.OracleDriver</param-value> </context-param> <context-param> <param-name>url</param-name> <param-value>jdbc:oracle:thin:@localhost:1521:xe</param-value> </context-param> <context-param> <param-name>uname</param-name> <param-value>scott</param-value> </context-param> <context-param> <param-name>pwd</param-name> <param-value>tiger</param-value> </context-param> <servlet> <servlet-name>d</servlet-name> <servlet-class>DBConnect</servlet-class>

</servlet> <servlet-mapping> <servlet-name>d</servlet-name> <url-pattern>/d</url-pattern> </servlet-mapping> </web-app> <%@ page import="java.sql.*"%> <%@ page import="java.io.*"%> <% String vdrvcls,vurl,vuname,vpwd; vdrvcls=application.getInitParameter("drvcls"); vurl=application.getInitParameter("url"); vuname=application.getInitParameter("uname"); vpwd=application.getInitParameter("pwd"); Class.forName(vdrvcls); Connection con=DriverManager.getConnection(vurl,vuname,vpwd); System.out.println("--connected to db--"); con.close( ); %> http://localhost:8000/jsp/dbc.jsp --connected to db-application is an implicit variable and it refers to ServletContext object. Generally there is no need of providing the information about the JSP in web.xml. if JSP requires initialization parameter then we need to provide the information about JSP in web.xml as shown below <web-app> <servlet> <servlet-name>xxx</servlet-name> <jsp-file>/test.jsp</jsp-file> <init-param> <param-name>ipone</param-name> <param-value> Some value here </param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>xxx</servlet-name> <url-pattern>/xxx</url-pattern> </servlet-mapping> </web-app> <% System.out.println("----test.jsp----"); String vipone=config.getInitParameter("ipone"); out.println(vipone); %>

http://localhost:7001/wapp/test.jsp Some value here ----test.jsp---The implicit variable config reference to ServletConfig objects. SQL> create table student(sno varchar(20),sname varchar(20),fname varchar(20),addr varchar(20)); Table created. SQL> insert into student values(1,'sone','fone','aone'); 1 row created. SQL> insert into student values(2,'stwo','ftwo','atwo'); 1 row created. SQL> insert into student values(3,'sthr','fthr','athr'); 1 row created. SQL> select * from student; SNO SNAME FNAME ADDR -------------------- -------------------- -------------------- ---------------1 sone fone aone 2 stwo ftwo atwo 3 sthr fthr athr SQL> commit; Commit complete. <%@ page import="java.sql.*"%> <% Driver drv=new oracle.jdbc.driver.OracleDriver( ); DriverManager.registerDriver(drv); Connection con=DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:xe","scott","tiger"); String vsql="select * from student"; Statement stmt=con.createStatement( ); ResultSet rs=stmt.executeQuery(vsql); while(rs.next( )) { out.println(rs.getString("sno")+"&nbsp;&nbsp;"); out.println(rs.getString("sname")+"&nbsp;&nbsp;"); out.println(rs.getString("fname")+"&nbsp;&nbsp;"); out.println(rs.getString("addr")+"<br>"); out.println("<br>"); } con.close( ); %> http://localhost:7001/jsp/db.jsp 1 sone fone aone 2 stwo ftwo atwo 3 sthr fthr athr

db.jsp generates a report using the information available in the student table.

browser

database

web container

When the user types the URL pointing to db.jsp for the first time the browser sends a request to the server. Web container executes db.jsp. db.jsp takes the data from student table & sends the content that contains the data obtained from student table to the browser. The browser displays the content & stores the content in it cache. Open internet & choose internet options Click the setting button Chose never & click ok button When the user types the same URL for the second time, the browser instead of sending the request to the server picks up the content available in the cache. This strategy is mint for improving the performance. SQL> insert into student values(4,'sfour','ffour','afour'); 1 row created. SQL> insert into student values(5,'sfive','ffive','afive'); 1 row created. SQL> select * from student; SNO SNAME FNAME ADDR -------------------- -------------------- -------------------- ---------------1 sone fone aone 2 stwo ftwo atwo 3 sthr fthr athr 4 sfour ffour afour 5 sfive ffive afive SQL> commit; Commit complete. http://localhost:7001/jsp/db.jsp

1 sone fone aone 2 stwo ftwo atwo 3 sthr fthr athr If there is a change in the database table student between the 1st request and 2nd request, then the user will not able to see the changed data(current data). The above problem can be solved by setting the expiry date & time for the content generated by db.jsp. <% java.util.Date now=new java.util.Date( ); response.setDateHeader("Expires",0); %> <%=now%> http://localhost:7001/js/date.jsp Thu Feb 28 11:39:35 IST 2008 Internet Explore ---> tools ---> internet options ---> settings ---> view files Refresh the URL http://localhost:7001/js/date.jsp multiple times Thu Feb 28 11:39:35 IST 2008 Same output will be given and same response will be given from cache. If we add the code shown above to our JSP then the Expiry date and time of the content will be sets a value indicating the content is already expired. In this case we can assume then the browser as not cached the content. The code shown below sets the expiry date and time to current date and time one hour. <% java.util.Date now=new java.util.Date( ); long lnow=now.getTime( ); long exp=lnow+(1000*60*60); response.setDateHeader("Expires",exp); %> <%=now%> http://localhost:7001/js/expire.jsp Thu Feb 28 12:06:05 IST 2008 Internet Explore ---> tools ---> internet options ---> settings ---> view files <% java.util.Date now=new java.util.Date( ); response.setHeader("pragma","no-cache"); %> <%=now%> http://localhost:7001/js/pragma.jsp

Fri Feb 29 14:52:57 IST 2008 Refresh the URL http://localhost:7001/js/pragma.jsp Fri Feb 29 14:54:29 IST 2008 <html> <head> <title>fone</title> </head> <body> <form method="GET" action="fnone.jsp"> Field one: <input type="text" name="fone"> <br> Field two: <input type="text" name="ftwo"> <br> <input type="submit" value="send data"> <br> </form> </body> </html>

fone and ftwo are called as names of the fields/parameters/properties. To capture(get) the values provided by the user in a field, request.getParameter( ) can be used. <% System.out.println("---fnone.jsp---"); String vfone=request.getParameter("fone"); String vftwo=request.getParameter("ftwo"); String vfthr=request.getParameter("fthr"); %> <%=vfone%> <br> <%=vftwo%> <br> <%=vfthr%> <br> http://localhost:7001/js/fone.html Field one: Field two:
send data w ater

clicked

---fnone.jsp--water

null When you click the next button String vfone=request.getParameter("fone"); .. returns a String object with water String vftwo=request.getParameter("ftwo"); .. retuens a String object with blank (" ") String vfthr=request.getParameter("fthr"); .. returns a null. request.getParameter returns a blank string, if the field is there in the form but the user not provided the data. This method returns a null, if there is no field in the form. In both the cases our application can assume that the user as not provided the data. What is the difference between GET request & POST request methods? A)

GET request Server Browser When the user provides the data in the form and submits the form by clicking on send data button, the browser appends the data to the URL as a query string and sends a GET request to the server. The browser displays the URL in the address bar ./js/fnone.jsp?fone=AAA&ftwo=XYZ Query string Problems: 1) There is a limit on the length of the URL. A browser can not send more amounts of data, if the length of the URL exceeds the limit after appending the data to the URL. 2) Sensitive information like passwords will be reviled as the URL as displayed in the address bar. <html> <head> <title>GET</title> </head> <body> <form method="GET" action="get.jsp"> User Name: <input type="text" name="uname"> <br> Paasword: <input type="password" name="pwd"> <br> <input type="submit" value="send data"> </form> </body> </html> <% String vuname =request.getParameter("uname");

String vpwd=request.getParameter("pwd"); System.out.println("User name---->"+vuname ); System.out.println("Password ---->"+vpwd); %> http://localhost:7001/js/get.html User Name: Paasword:
send data Sudheer *****

Clicked

http://localhost:7001/js/get.jsp?uname=Sudheer+&pwd=Sunil User name---->Sudheer Password ---->Sunil If we use <form method="POST" action="fnone.jsp"> The browser sends a post Request when the form is submitted. In this case the data will be appended to the URL. The browser sends the data to the server as part of the request body. When the POST method is used, the browser will be able to send huge amount of data to the server and the sensitive information is not reviled in the address bar. The performance of the application can improved slightly using the GET request. How to pass parameters from html to a servlet/jsp? A) By using the Query string. <html> <head> <title>param.html</title> </head> <body> <a href="param.jsp">LOne </a> <br> <a href="param.jsp?pone=aa&ptwo=bb">LTwo </a> <br> <a href="param.jsp?pone=yy&ptwo=zz">LThr </a> <br> </body> </html> <% System.out.println("-----param.jsp----"); String vpone=request.getParameter("pone"); String vptwo=request.getParameter("ptwo"); %> <br> <%=vpone%> <br><%=vptwo%> <br><a href="param.html">Home </a>

http://localhost:7001/js/param.html LOne LTwo LThr -----param.jsp---null null Home Clicked LOne LTwo LThr -----param.jsp---aa bb Home Clicked LOne LTwo LThr Clicked -----param.jsp---yy zz Home SQL> select * from student; no rows selected <html> <head> <title>nsform</title> </head> <body> <form action="ssd.jsp"> Student no: <input type="text" name="sno"> <br> Student name: <input type="text" name="sname"> <br> Father name: <input type="text" name="fname"> <br> Address: <input type="text" name="addr"> <br> <input type="submit" value="store"> <br> </form> </body> </html>

Clicked

Clicked

<%@ page import="java.sql.*" %> <% String vsno=request.getParameter("sno"); String vsname=request.getParameter("sname"); String vfname=request.getParameter("fname"); String vaddr=request.getParameter("addr"); // code to connect DB Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:xe","scott","tiger"); String vsql="insert into student values(?,?,?,?)"; PreparedStatement pstmt=con.prepareStatement(vsql); pstmt.setString(1,vsno); pstmt.setString(2,vsname); pstmt.setString(3,vfname); pstmt.setString(4,vaddr); pstmt.executeUpdate( ); con.close( ); %> Data stored in student table http://localhost:7001/js/nsform.html Student no: Father name: Address:
store aone 1 sone fone

Student name:

Clicked Data stored in student table SQL> select * from student; SNO SNAME FNAME ADDR -------------------- -------------------- -------------------- ---------------1 sone fone aone http://localhost:7001/js/nsform.html Student no: Father name: Address:
store atw o 2 stw o ftw o

Student name:

Clicked http://localhost:7001/js/nsform.html

Student no: Father name: Address:


store

3 sthr fthr

Student name:
athr

Clicked

SQL> select * from student; SNO SNAME FNAME ADDR -------------------- -------------------- -------------------- ---------------1 sone fone aone 2 stwo ftwo atwo 3 sthr fthr athr <html> <head> <title>gsdform</title> </head> <body> <form action="gsd.jsp"> Student no: <input type="text" name="sno"> <br> <input type="submit" value="Get Info"> <br> </form> </body> </html> <%@ page import="java.sql.*" %> <% System.out.println("---student table---"); String vsno=request.getParameter("sno"); String vsql="select * from student where sno="+vsno; Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:xe","scott","tiger"); Statement stmt=con.createStatement( ); ResultSet rs=stmt.executeQuery(vsql); String vsname,vfname,vaddr; if(rs.next( )) { vsno=rs.getString("sno"); vsname=rs.getString("sname"); vfname=rs.getString("fname"); vaddr=rs.getString("addr"); }

else { out.println("No Data"); return; } con.close( ); %> <br><%= vsno%> <br> <%= vsname%> <br> <%= vfname%> <br> <%= vaddr%> http://localhost:7001/js/gsdform.html Student no:
Get Info 1

Clicked ---student table--1 sone fone aone http://localhost:7001/js/gsdform.html Student no:


Get Info 3

Clicked ---student table--1 sthr fthr athr <%@ page import="java.sql.*" %> <% String vsno=request.getParameter("sno"); String vsql="select * from student where sno="+vsno; // code to connect DB Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:xe","scott","tiger"); Statement stmt=con.createStatement( ); ResultSet rs=stmt.executeQuery(vsql); String vsname,vfname,vaddr; if(rs.next( )) { vsno=rs.getString("sno"); vsname=rs.getString("sname"); vfname=rs.getString("fname");

vaddr=rs.getString("addr"); } else { out.println("No Data"); return; } con.close( ); %> <html> <body> <form action="usd.jsp"> <input type="hidden" name="sno" value="<%=vsno%>"> <br> Student Name: <input type="text" name="sname" value="<%=vsname%>"> <br> Father Name: <input type="text" name="fname" value="<%=vfname%>"> <br> Address: <input type="text" name="addr" value="<%=vaddr%>"> <br> <input type="submit" value="Update"> <br> </form> </body> </html> The above jsp generates a form using the data retrieved from student table. <%@ page import="java.sql.*" %> <% String vsno=request.getParameter("sno"); String vsname=request.getParameter("sname"); String vfname=request.getParameter("fname"); String vaddr=request.getParameter("addr"); // code to connect DB Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:xe","scott","tiger"); String vsql="update student set sname=?,fname=?,addr=? where sno=?"; PreparedStatement pstmt=con.prepareStatement(vsql); pstmt.setString(1,vsname); pstmt.setString(2,vfname); pstmt.setString(3,vaddr); pstmt.setString(4,vsno); pstmt.executeUpdate( ); con.close( );%> Data Updated http://localhost:7001/js/gsdform.html Student no:
2

Get Info 2

Clicked
sss fff

Student Name: Father Name: Address:


Update aaa

Clicked

Data Updated SQL> select * from student; SNO SNAME FNAME ADDR -------------------- -------------------- -------------------- ---------------1 sone fone aone 2 sss fff aaa 3 sthr fthr athr <html> <head> <title>dsdform</title> </head> <body> <form action="gsd.jsp"> Student no: <input type="text" name="sno"> <br> <input type="submit" value="Delete"> <br> </form> </body> </html> <%@ page import="java.sql.*" %> <% String vsno=request.getParameter("sno"); // code to connect DB Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:xe","scott","tiger"); String vsql="delete from student where sno="+vsno; Statement stmt=con.createStatement( ); stmt.executeUpdate(vsql); con.close( ); %> Data deleted <br> <a href="dsdform.html">home</a> http://localhost:7001/js/dsdform.html

Student no:
Delete

Clicked

Data deleted home Clicked Student no:


Delete 3

Clicked Data deleted home Clicked Student no:


Delete 1

Clicked Data deleted home SQL> select * from student; no rows selected Error page is a JSP that gets executed when there is a problem. An error page can use the implicit variable exception object that is thrown to indicate the problem. <%@ page isErrorPage="true"%> Failed due to ....... <br> <%= exception %> Save: eh.jsp <%@ page isErrorPage="false"%> <%@ page errorPage="/eh.jsp"%> <% System.out.println("----gsr.jsp----1"); java.io.FileInputStream fis=new java.io.FileInputStream("xxxx"); System.out.println("----gsr.jsp----2"); %> http://localhost:7001/js/gsr.jsp ----gsr.jsp----1 Failed due to ....... java.io.FileNotFoundException: xxxx (The system cannot find the file specified) If gsr.jsp is successfully executed then the web container will not execute eh.jsp. We can not use the implicit variable exception in gsr.jsp. <web-app> <servlet> <servlet-name>sone</servlet-name> <servlet-class>Sone</servlet-class> </servlet> <servlet-mapping>

<servlet-name>sone</servlet-name> <url-pattern>/sone</url-pattern> </servlet-mapping> <servlet> <servlet-name>stwo</servlet-name> <servlet-class>Stwo</servlet-class> </servlet> <servlet-mapping> <servlet-name>stwo</servlet-name> <url-pattern>/stwo</url-pattern> </servlet-mapping> </web-app> import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class Sone extends HttpServlet { public void service(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { ServletContext applicaation=getServletContext( ); RequestDispatcher rd=application.getRequestDispatcher("/stwo"); PrintWriter out=response.getWriter( ); out.println("<br>----Line one of Sone----"); rd.include(request,response); out.println("<br>----Last line of Sone----"); } } import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class Stwo extends HttpServlet { public void service(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { PrintWriter out=response.getWriter( ); out.println("<br>----Line one of Stwo----"); out.println("<br>----Last line of Stwo----"); } } D:\Pskr>java Sone.java D:\Pskr>java Stwo.java

http://localhost:7001/rd/sone ----Line one of Sone-------Line one of Stwo-------Last line of Stwo-------Last line of Sone--- RequestDispatcher is responsible for dispatching / handing over (giving) the request to a resource like Servlet /JSP etc. We can use the methods include and forward of RequestDispatcher to dispatch the request.

Browser Web Container The following Steps will be carried out in the container when it receives the request for Sone Servlet. 1)Web container creates the request and the response objects. 2)Web container calls the Service method on Sone by passing req, resp objects created in Step1 3)When rd.include of Sone is executed web container starts the execution of the service method of Stwo by passing req,resp objects created in Step1. 4)After the execution of Stwo the remaining part of Sone will be executed. 5)Web container removes req,resp objects created in Step1. Notes: 1) Multiple Srevlets invaled in processing a Single request are considered to be part of a Servlet chain (Sone, Stwo are involved in processing a Single request). 2) While processing the request web container passes the Same request object to the Servlets Sone,Stwo. ** 3) When include method is used for dispatching the request, the client receives the output that is the combination of the o/ps generated by the calling servlet (Sone) and the called Servlet(Stwo). **4) When forward is used to dispatch the request web container discards the output generated by the calling Servlet (Sone) and sends the output generated by the called Servlet(Stwo) to the client.

rd.include(request, response); We can replace in this line into rd. forward(request, response); in the above Sone program D:\Pskr>java Sone.java http://localhost:7001/rd/sone ----Line one of Stwo-------Last line of Stwo--- We can use request Dispatcher for dispatching the request in isps without using java code. For this we must use JSP Action Tags. <xxx:tone aone=value one atwo=value two /> Prefix tag name attribute name attribute value end tag <br> ---- Line one of sone.jsp <jsp:include page="/xxx/yyy/stwo.jsp"/> <br> ---- Last line of sone.jsp <br> ---- Line one of stwo.jsp <br> ---- Last line of stwo.jsp http://localhost:7001/jsp/sone.jsp ---- Line one of sone.jsp ---- Line one of stwo.jsp ---- Last line of stwo.jsp ---- Last line of sone.jsp For jsp:include tag, the JSP compiler generates the java code that internally uses rd.include( ) method. When the browser sends the request for sone.jsp, web container executes two Servlets. (sone.jsp, stwo.jsp) and the client will receive the output generated by one.jsp and two.jsp. <br> ---- Line one of sone.jsp <jsp:farward page="/xxx/yyy/stwo.jsp"/> <br> ---- Last line of sone.jsp <br> ---- Line one of stwo.jsp <br> ---- Last line of stwo.jsp http://localhost:7001/jsp/sone.jsp ---- Line one of stwo.jsp ---- Last line of stwo.jsp The JSP compiler generates the java code that uses rd.farward for jsp:farward tag. We can eliminate the java code by using JSP action tags.

<br> ---- Line one of sone.jsp <jsp:include page="/stwo"/> <br> ---- Last line of sone.jsp http://localhost:7001/jsp/sone.jsp ---- Line one of sone.jsp ----Line one of Stwo-------Last line of Stwo------- Last line of sone.jsp Here /stwo is URL pattern of Servlet specified in web.xml. A single JSP/Servlet can dispatch the request to multiple resources using request dispatcher include (jsp:include) Ex: <br> ---- Line one of sone.jsp <jsp:include page="/stwo.jsp"/> <br> ---- Last line of sone.jsp <jsp:include page="/sthr.jsp"/> <br> ---- Line one of sthr.jsp <br> ---- Last line of sthr.jsp http://localhost:7001/jsp/sone.jsp ---- Line one of sone.jsp ---- Line one of stwo.jsp ---- Last line of stwo.jsp ---- Last line of sone.jsp ---- Line one of sthr.jsp ---- Last line of sthr.jsp A single resource can not dispatch the request to multiple resources using rd.forward (jsp:forward). Ex: <br> ---- Line one of sone.jsp <jsp:forward page="/stwo.jsp"/> <br> ---- Last line of sone.jsp <jsp:forward page="/sthr.jsp"/> http://localhost:7001/jsp/sone.jsp ---- Line one of stwo.jsp ---- Last line of stwo.jsp Java Been component: To simplify is development of Java applications. Java soft has designed the component technologies like Java Bean & Enterprise Java Been. A component is a part for developing a Java Bean component we must follow the guidelines /rules/specification provided by Java Soft.

A Java Bean component can support 1) A set of properties 2) A set of Events 3) A set of Additional Methods. A Java Bean can be developed by providing a java class following the rules given below 1)There must be a zero argument constructor in the java class 2)To support a property with name xyz, we must provide a) Type getXyz( ) and/or b) void setXyz(Type) 3)A Java Bean can support an event with the name abc by providing the following methods. Ex:-addAbcListener(AbcListener) and removeAddListener(AbcListener). package org.students; public class StudentBean { int age; String uname; public void setAge(int age) { System.out.println("----setAge---->"+age); this.age=age; } public int getAge( ) { return this.age; } public void setUserName(String uname) { System.out.println("----setUserName---->"+uname); this.uname=uname; } public String getUserName( ) { return this.uname; } public void print( ) { System.out.println("----Age---->"+age); System.out.println("----User Name---->"+uname); } public StudentBean( ) { System.out.println("----StudentBean created----"); }

} D:\Pskr>javac -d . StudentBean.java StudentBean supports the following properties Property type Property name int age String username We can use the JavaBean in a JSP without using the java code. <jsp:useBean id="sb" scope="page" class="org.students.StudentBean"/> 1 <jsp:setProperty name="sb" property="userName" value="Sudheer"/> 2 <jsp:getProperty name="sb" property="userName"/> 3 http://localhost:7001/jsp/usebean.jsp ----StudentBean created---Sudheer The JSP compiler generates the java code for every action tags used in the JSP. When the action tag is evaluated internally the code generated by the JSPC will be executed. Note: - 1) If the StudentBean is available with the attribute name sb in PageContext then the existing object will be used. If the object is not available in the PageContext then a new StudentBean object will be created and it will be stored in the PageContext using the attribute name sb. 2) setUserName( ) method will be call by passing Sudheer as a parameter. 3) The method getUserName( ) will be executed and the value return by the method will be sent to the browser.

Client Web Container At the beginning of the execution of a JSP the PageContext object will be created. After the execution of the JSP the PageContext object will be removed. <% String s=new String("xyz"); org.students.StudentBean sb=new org.students.StudentBean( ); pageContext.setAttribute("aname",s); 1 pageContext.setAttribute("aname",sb); 2 Object o=pageContext.getAttribute("aname"); 3 out.println(o.getClass( )); Object x=pageContext.getAttribute("xxx"); 4 out.println("<br>"+x);

%> http://localhost:7001/jsp/setat.jsp class org.students.StudentBean null 1 The String object will be added to the pageContext object with the attribute name aname. 2 The String object will be replaced with the StudebtBean object in the pageContext. 3 We will get the reference of StudentBean object. 4 A null will be returned specifying that there is no object with the attribute name xxx. <% org.students.StudentBean sb=new org.students.StudentBean( ); pageContext.setAttribute("aname",sb); Object o=pageContext.getAttribute("aname"); out.println(o); pageContext.removeAttribute("aname"); Object y=pageContext.getAttribute("aname"); out.println("<br>"+y); %> http://localhost:7001/jsp/rsetat.jsp org.students.StudentBean@3dcf03 null pageContext.removeAttribute( ) method removes the reference of the java object from pageContext. <% String x=new String("xxx"); StringBuffer y=new StringBuffer("yyy"); pageContext.setAttribute("aone",x); pageContext.setAttribute("atwo",y); Object o=pageContext.getAttribute("atwo"); String s=(String)o; //StringBuffer s=(StringBuffer)o; out.println(s); %> http://localhost:7001/jsp/ts.jsp Error 500--Internal Server Error java.lang.ClassCastException <% String x=new String("xxx"); StringBuffer y=new StringBuffer("yyy"); pageContext.setAttribute("aone",x); pageContext.setAttribute("atwo",y); Object o=pageContext.getAttribute("atwo"); // String s=(String)o; StringBuffer s=(StringBuffer)o; out.println(s);

%> http://localhost:7001/jsp/ts.jsp yyy Storing an object in pageContext is considered as using page scope. aname is called as attribute name/key of attribute/scoped variable name. setAttribute, getAttribute, removeAttribute methods are available on request, session, application also. <jsp:useBean id="sb" scope="page" class="org.students.StudentBean"/> Can also be written as <jsp:useBean id="sb" class="org.students.StudentBean"/> The default scope is page. <jsp:useBean id="sb" scope="page" class="org.students.StudentBean"/> <jsp:forward page="/ptwo.jsp"/> <jsp:useBean id="sb" scope="page" class="org.students.StudentBean"/> http://localhost:7001/jsp/pone.jsp ----StudentBean created-------StudentBean created----

browser

Web Container 1) When the browser sends the request for pone.jsp, we executes two servlets pone.jsp, ptwo.jsp. 2) While executing pone.jsp a StudentBean object will be created and it will be added to the pageContext of pone.jsp 3) While executing ptwo.jsp a StudentBean object will be created and it will be added to the pageContext of ptwo.jsp 4) pone.jsp & ptwo.jsp uses two different StudentBean objects, even though they are involved in processing a single request. 5) If a JSP has to use its own Java Bean object then we must used page scope. <jsp:useBean id="sb" scope="request" class="org.students.StudentBean"/> <% System.out.println("----rone.jsp----");%> <jsp:forward page="/rtwo.jsp"/>

<jsp:useBean id="sb" scope="request" class="org.students.StudentBean"/> <%System.out.println("----rtwo.jsp----");%> http://localhost:7001/jsp/rone.jsp ----StudentBean created-------rone.jsp-------rtwo.jsp--- 1) When the browser sends the request for rone.jsp, web container executes multiple servlets (rone.jsp, rtwo.jsp). 2) As rone.jsp & rtwo.jsp are involved in processing a single request, the same request object will be provided for both the servlets. 3) While executing rone.jsp a StudentBean will be created and it will be stored in the request object.

Browser

Web Container 4) While executing rtwo.jsp the StudentBean object created while executing rone.jsp will be used. 5) In this case rone.jsp, rtwo.jsp uses/shares the same StudentBean object. ** When to use scope="request"? A) When multiple Servlets involved in processing a single request has to use/share the same java object, then the java object must be stored inside the request method. <html> <head> <title>ubf.html</title> </head> <body> <form action="ub.jsp"> Field one: <input type="text" name="fone"> <br> Field two: <input type="text" name="ftwo"> <br> <input type="submit" value="send data"> </body> </html>

The data provided by the user can be captured and stores as the values of the Java Bean using the code shown below <jsp:useBean id="sb" scope="page" class="org.students.StudentBean"/> <jsp:setProperty name="sb" property="userName" value='<%=request.getParameter("fone")%>'/> <jsp:setProperty name="sb" property="age" value='<%=Integer.parseInt(request.getParameter("ftwo"))%>'/> http://localhost:7001/jsp/ubf.html Field one: Field two:
send data sudheer 24

Clicked ----StudentBean created-------setUserName---->sudheer ----setAge---->24 We can simplify the java code in the JSPs using the same names for the properties of a javaBean and the fields of the form <html> <head> <title>gubf.html</title> </head> <body> <form action="gub.jsp"> Field one: <input type="text" name="userName"> <br> Field two: <input type="text" name="age"> <br> <input type="submit" value="send data"> </body> </html>

<jsp:useBean id="sb" scope="page" class="org.students.StudentBean"/> <jsp:setProperty name="sb" property="userName"/> <jsp:setProperty name="sb" property="age"/>

http://localhost:7001/jsp/gubf.html Field one: Field two:


send data sunil 24

----StudentBean created-------setUserName---->sunil ----setAge---->24 SQL> create user sudheer identified by sunil; User created. SQL> grant connect, resource to sudheer; Grant succeeded. SQL> connect sudheer/sunil Connected. SQL> create table appusers(userName varchar(10),password varchar(10),email varchar(30),address varchar(20)); Table created. SQL> select * from appusers; no rows selected

package org.students; import java.sql.*; public class UserBean { private String userName; private String password; private String address; private String email; public void setUserName(String userName) { System.out.println("----setUserName---->"+userName); this.userName=userName; } public String getUserName( ) { return this.userName; }

public void setPassword(String password) { System.out.println("----setPassword---->"+password); this.password=password; } public String getPassword( ) { return this.password; } public void setAddress(String address) { System.out.println("----setAddr---->"+address); this.address=address; } public String getAddress( ) { return this.address; } public void setEmail(String email) { System.out.println("----setEmail---->"+email); this.email=email; } public String getEmail( ) { return this.email; } public void registerUser( ) throws Exception { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:xe","sudheer","sunil"); String vsql="insert into appusers values(?,?,?,?)"; PreparedStatement pstmt=con.prepareStatement(vsql); pstmt.setString(1,this.userName); pstmt.setString(2,this.password); pstmt.setString(3,this.email); pstmt.setString(4,this.address); pstmt.executeUpdate( ); con.close( ); // code to send mail to the new user } } D:\Pskr>javac -d . UserBean.java The code that is part of registerUser( ) method is called as business logic.

The following two tasks are performed by the business logic in registerUser. 1)Store data in appusers table. 2)Send mail to the new user. The code that takes care of dealing with the database is called as data access logic. In the above example the business logic is the combination of data access logic + some other kind of logic that does not deal with database. <html> <head> <title>urform.jsp</title> </head> <body> <form action="ur.jsp"> User Name: <input type="text" name="userName"> <br> Password: <input type="text" name="password"> <br> Email: <input type="text" name="email"> <br> Address: <input type="text" name="address"> <br> <input type="submit" value="Register"> </body> </html> Note: - The names of the 4 fields used in the form are same as the names of the properties of UserBean. When the browser sends the request for urform.jsp, the server executes urform.jsp & sends the content generated by urform.jsp to the browser. The browser presents the content and the user views the content. The logic that is part of urform.jsp is called as presentation logic (the code that is responsible for generating the content that gets presented by the browser is called as presentation logic). urform.jsp is a view component (it contains the presentation logic that generates the content. The content will be ultimately viewed by the user). <% System.out.println("----ur.jsp----");%> <jsp:useBean id="urb" scope="page" class="org.students.UserBean"/> <jsp:setProperty name="urb" property="*"/> <% urb.registerUser( ); %> User Registered <br> Stored the following data in our db <br> <jsp:getProperty name="urb" property="userName"/> <br> <jsp:getProperty name="urb" property="password"/> <br>

<jsp:getProperty name="urb" property="address"/> <br> <jsp:getProperty name="urb" property="email"/> <br> http://localhost:7001/jsp/urform.jsp User Name: Password: Email: Address:
Register sudheer sunil

sudheer_16 anantapur

Clicked ----ur.jsp-------setAddr---->anantapur ----setEmail---->sudheer_1620@localhost ----setPassword---->sunil ----setUserName---->sudheer User Registered Stored the following data in our db sudheer sunil anantapur sudheer_1620@localhost SQL> select * from appusers;
USERNAME PASSWORD EMAIL ADDRESS

------------- ---------------- ---------------------------------- -------------------sudheer sunil sudheer_1620@localhost anantapur ur.jsp decides about using UserBean and it decides about calling the business method registerUser. The code decides about what as to be done by an application when the user interacts with the application is called as controller. ur.jsp acts as a controller component and as a view component. Model is a piece of code that is responsible for managing the data; According to the JSP model one architecture, we must provide the business logic as part of the model classes. In the above application org.students.UserBean is a model class with business logic. A design pattern is a good best solution for a re occurring problem. We can solve most of the problems very easily during the project implementation using the standard design patterns like MVC (model view controller), DAO (data access object), Singleton etc Java soft has specified to standard architectures for the implementation of the web projects. Both these architecture are based on Model-View-Controller design pattern. 1)JSP Model I (also called as MVC I) architecture. 2)JSP Model II (also called as MVC II) architecture. MVC architecture recommends that the software is must be divided in to 3 pieces. 1)Model is responsible for managing the data.

2)View is responsible for presenting the information to the user. 3)Controller is responsible for deciding about what the application as an to do when the user interacts with the application The above application is developed according to JSP model I architecture. JSP Model I architecture is a recommended for small to medium-sized projects. JSP Model II architecture is a recommended for medium to large projects. In JSP model I architecture the java server page acts as a view and as a controller. The Java Bean acts as a model. View controller

1 req 4 req Browser Model Servlet Container 3

Enterprise information System (EIS) In the above application the UserBean object is required only during the execution of ur.jsp. This is why we have specified page scope. The same application can be implemented using two JSPs as shown below <% System.out.println("----ur.jsp----");%> <jsp:useBean id="urb" scope="request" class="org.students.UserBean"/> <jsp:setProperty name="urb" property="*"/> <% urb.registerUser( ); %> <jsp:forward page="/dispinfo.jsp"/> <% System.out.println("----dispinfo.jsp----");%> <jsp:useBean id="urb" scope="request" class="org.students.UserBean"/> User Registered <br> Stored the following data in our db <br> <jsp:getProperty name="urb" property="userName"/> <br> <jsp:getProperty name="urb" property="password"/> <br> <jsp:getProperty name="urb" property="address"/> <br> <jsp:getProperty name="urb" property="email"/> <br> http://localhost:7001/jsp/urform.jsp

User Name: Password: Email: Address:


Register

latha usha

latha_1985@ anantapur

Clicked ----ur.jsp-------setAddr---->anantapur ----setEmail---->latha_1985@localhost ----setPassword---->usha ----setUserName---->latha ----dispinfo.jsp---User Registered Stored the following data in our db latha usha anantapur latha_1985@localhost SQL> select * from appusers;
USERNAME PASSWORD EMAIL ADDRESS

------------- ---------------- ---------------------------------- -------------------sudheer sunil sudheer_1620@localhost anantapur latha usha latha_1985@localhost anantapur

Browser

Web Container What is the difference between static include & dynamic include? A) <% System.out.println("----sione.jsp----");%> <br> ----Line one of sione.jsp---<%@ include file="sitwo.jsp" %> <br> ----Last line of sione.jsp--- <% System.out.println("----sitwo.jsp----");%> <br> ----Line one of sitwo.jsp----

<br> ----Last line of sitwo.jsp---http://localhost:7001/jsp/sione.jsp ----sione.jsp-------sitwo.jsp-------Line one of sione.jsp-------Line one of sitwo.jsp-------Last line of sitwo.jsp -------Last line of sione.jsp---While compile sione.jsp, the JSP compiler merges/combines/includes the content of sitwo.jsp with sione.jsp and generates a single servlet. In this case the process of merging is taking place during compile time. This process is called static include.

xxxx.jsp

xxxx.java When the browser sends the request for sione.jsp only one Servlet will be executed. <% System.out.println("----dione.jsp----");%> <br> ----Line one of dione.jsp---<jsp:include page="/ditwo.jsp"/> <br> ----Last line of dione.jsp---- <% System.out.println("----ditwo.jsp----");%> <br> ----Line one of ditwo.jsp---<br> ----Last line of ditwo.jsp---http://localhost:7001/jsp/dione.jsp ----dione.jsp-------ditwo.jsp-------Line one of dione.jsp-------Line one of ditwo.jsp-------Last line of ditwo.jsp-------Last line of dione.jsp---While compiling dione.jsp, JSP compiler does not merge the content of ditwo.jsp with dione.jsp. The JSP compiler generates a servlet using the code of dione.jsp & another servlet will be generated using the code of ditwo.jsp. When the browser sends the request for dione.jsp, the web container runs/executes two servlets & while running the output generated by ditwo.jsp servlet will be included as part of the content generated by dione.jsp. Static include improves the performance of the applications. But we can not use this

as part of manually developed servlets. What is the difference between rd.forward & response.sendRedirect? A) <% System.out.println("----rdfone.jsp----");%> op of rdfone.jsp <jsp:forward page="/rdftwo.jsp"/> <% System.out.println("----rdftwo.jsp----");%> op of rdftwo.jsp http://localhost:7001/jsp/rdfone.jsp ----rdfone.jsp-------rdftwo.jsp---op of rdftwo.jsp

Browser Web Container When the browser sends the request for rdfone.jsp two Servlets will be executed (rdfone.jsp, rdftwo.jsp). in this case a single request is processed by two servlets & these two servlets receives the same request object. <% System.out.println("----srone.jsp----"); response.sendRedirect("srtwo.jsp"); %> op of srone.jsp <% System.out.println("----srtwo.jsp----");%> op of srtwo.jsp http://localhost:7001/jsp/srone.jsp ----srone.jsp---op of srtwo.jsp http://localhost:7001/jsp/srtwo.jsp ----srtwo.jsp---op of srtwo.jsp req1

req2 Browser

Web Container When the browser sends the request for srone.jsp 1)Container executes srone.jsp. While executing srone.jsp the container creates req, resp objects & gives the objects to srone.jsp. 2)As we used response.sendRedirect the container sends a response with a header called location & the value of this header points to srtwo.jsp. 3)The browser sends a request (req2) for the jsp srtwo. 4)Container crates req, resp objects & passes these objects to srtwo.jsp. In this case the browser sends two requests & srone.jsp, srtwo.jsp receives two different objects. <% System.out.println("----rdfone.jsp----"); request.setAttribute("xxx","yyy"); %> op of rdfone.jsp <jsp:forward page="/rdftwo.jsp"/> <% System.out.println("----rdftwo.jsp----"); out.println(request.getAttribute("xxx")); %> op of rdftwo.jsp http://localhost:7001/jsp/rdfone.jsp ----rdfone.jsp-------rdftwo.jsp---yyy op of rdftwo.jsp <% System.out.println("----srone.jsp----"); request.setAttribute("xxx","yyy"); response.sendRedirect("srtwo.jsp"); %> op of srone.jsp <% System.out.println("----srtwo.jsp----"); out.println(request.getAttribute("xxx")); %> op of srtwo.jsp http://localhost:7001/jsp/srone.jsp ----srone.jsp----

----srtwo.jsp---null op of srtwo.jsp When multiple servlets are dealing with a single request thay can communicate with each other by placing the java objects inside the request object (in case of rdfone.jsp, rdftwo,jsp) The Servlets can not communicate by placing the java objects inside the request object, if they are dealing with different requests (in case of srone.jsp, srtwo,jsp) ** How can servlet one communicate with servlet two when response.sendRedirect is used by servlet one? A) Servlet one can communicate with servlet two using the query string. <% response.sendRedirect("srtwo.jsp?xxx=yyy"); %> op of srone.jsp <% out.println(request.getParameter("xxx")); %> op of srtwo.jsp http://localhost:7001/jsp/srone.jsp yyy op of srtwo.jsp In case of rd.forward the two resources must be available in the same container. But in case of response.sendRedirect the resources can be part of two different containers. req1 Web Container1 Client req2

Web Container2 <% response.sendRedirect("http://localhost:8000/js/srtwo.jsp"); %> op of srone.jsp (place in Web logic)

op of srtwo.jsp (place in Tomcat) http://localhost:7001/jsp/srone.jsp

op of srtwo.jsp And see the URL in address bar http://localhost:8000/js/srtwo.jsp This is the advantage of response.sendRedirect. ** Is it possible to forward the request to a response available in another application running in the same container? A) Yes. The request can be forwarded to a resource running in another application of the same container. For this we must use ServletContext of another application. ServletContext ServletContext

Web Container <% ServletContext anotherApp=application.getContext("/watwo"); RequestDispatcher rd=anotherApp.getRequestDispatcher("/sctwo.jsp"); rd.forward(request,response); %> op of scone.jsp (place in waone/scone.jsp)

op of sctwo.jsp (place in watwo/sctwo.jsp) http://localhost:7001/waone/scone.jsp op of sctwo.jsp What is the difference between getRequestDispatcher & getNamedDispatcher? A) In case of getRequestDispatcher, the path of the resource must be used as a parameter. In case of getNamedDispatcher( ) method, the name of the servlet (specified in web.xml) must be passed as a parameter. <web-app> <servlet> <servlet-name>date</servlet-name> <servlet-class>DateNow</servlet-class> </servlet> <servlet-mapping> <servlet-name>date</servlet-name>

<url-pattern>/date</url-pattern> </servlet-mapping> </web-app> <% RequestDispatcher rd=application.getNamedDispatcher("date"); rd.forward(request,response); %> http://localhost:7001/jsp/rndone.jsp Wed Mar 05 13:44:38 IST 2008 What is the difference between request.getRequestDispatcher methods? A) <web-app> <servlet> <servlet-name>oursrv</servlet-name> <servlet-class>OurSrv</servlet-class> </servlet> <servlet-mapping> <servlet-name>oursrv</servlet-name> <url-pattern>/done/dtwo/stwo</url-pattern> </servlet-mapping> </web-app> application.getRequestDispatcher &

<% RequestDispatcher rd=application.getRequestDispatcher("/done/dtwo/stwo"); rd.forward(request,response); %> http://localhost:7001/jsp/agr.jsp executed GET /jsp/done/dtwo/stwo HTTP/1.1 Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; InfoPath.2) For application.getRequestDispatcher, we must provide the path starting with a slash(/) excluding the context path. For request.getRequestDispatcher, we can pass the relative path of the resource. <% RequestDispatcher rd=request.getRequestDispatcher("done/dtwo/stwo"); rd.forward(request,response); %> http://localhost:7001/jsp/rgr.jsp executed

GET /jsp/done/dtwo/stwo HTTP/1.1 Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; InfoPath.2) If the server can remember the conversational state of the client then the protocol implemented by the server is considered as stateful protocol. If the server can not remember the conversational state of the client then the protocol implemented by the server is called as stateless protocol. HTTP is a stateless protocol. Even though HTTP is stateless, we can develop stateful applications using the following techniques. 1) Hidden fields 2) Using Cookies 3) Session using Cookies 4) Session using URL rewriting. 1) Hidden fields: <html> <head> <title>hform.html</title> </head> <body> <form action="gsf.jsp"> Student no: <input type="text" name="sno"> <br> Student name: <input type="text" name="sname"> <br> <input type="submit" value="Next"> <br> </form> </body> </html> form one

Web container form two When the user provides the data (1,sone) in form one and clicks the next button, the browser sends a request to the server. As part of the request, the browser sends the data to

the server. The server executes gsf.jsp. gsf.jsp performs the following tasks. 1)Captures the data 2)Generates form two with the hidden fields that contains the data captured in step 1 <% String vsno=request.getParameter("sno"); String vsname=request.getParameter("sname"); %> <html> <head> <title>gsf.jsp</title> </head> <body> <form action="hsd.jsp"> <input type="hidden" name="sno" value="<%=vsno%>"> <br> <input type="hidden" name="sname" value="<%=vsname%>"> <br> Father name: <input type="text" name="fname"> <br> Address: <input type="text" name="addr"> <br> <input type="submit" value="store"> <br> </form> </body> </html> When the user provides the data (fone,aone) in form two & click on store button, the browser sends the request with the data 1,sone,fone,aone to the server. The server executes hsd,jsp. The following tasks are performed by hsd.jsp 1)Captures the data 2)Stores the data in to the database 3)Generates the output that contains the data stored in database. <%@ page import="java.sql.*" %> <% String vsno=request.getParameter("sno"); String vsname=request.getParameter("sname"); String vfname=request.getParameter("fname"); String vaddr=request.getParameter("addr"); // code to connect DB Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:xe","scott","tiger"); String vsql="insert into student values(?,?,?,?)"; PreparedStatement pstmt=con.prepareStatement(vsql); pstmt.setString(1,vsno); pstmt.setString(2,vsname);

pstmt.setString(3,vfname); pstmt.setString(4,vaddr); pstmt.executeUpdate( ); con.close( ); %> Data stored in student table <br> <%=vsno%> <br> <%=vsname%> <br> <%=vfname%> <br> <%=vaddr%> <br> http://localhost:7001/jsp/hform.html Student no:
Next sone 1 sone 1

Student name:

Clicked
fone

Father name: Address:


store aone

Clicked Data stored in student table 1 sone fone aone SQL> select * from student; SNO SNAME FNAME ADDR -------------------- -------------------- ---------------------- -----------------1 sone fone aone More amounts of data will be transfer between the client and the server in the above application. 2) Cookies: - A cookie is a small piece of information that is set by the server on the client. <% System.out.println("----setcks.jsp----"); Cookie c1=new Cookie("cnone","value one"); Cookie c2=new Cookie("cntwo","value two"); Cookie c3=new Cookie("cnthree","value three"); response.addCookie(c1); response.addCookie(c2); response.addCookie(c3); %> http://localhost:7001/wapp/setcks.jsp

----setcks.jsp---D:\psr\J2EE>java HWebServer1 8000 http://localhost:8000/wapp/setcks.jsp ...GET /wapp/setcks.jsp HTTP/1.1 Cookie: cnone=value one; cntwo=value two; cnthree=value three; JSESSIONID=HXINUQ cbUktcvM5QKwm5zio40e12oDRsL9Pa0ldYcu83246f1Hxs!628735853 Close the Browser & restart the browser again http://localhost:8000/wapp/setcks.jsp ...GET /wapp/setcks.jsp HTTP/1.1 Note: - The browser is responsible for sending back the Cookies to the server that as set to the cookies earlier. The browser holds the information about cnone, cntwo, cnthree cookies in the memory & these cookies will be lost when we close the browser. The browser uses the header with the name Cookie to send back the information about the Cookie to the server. For example Cookie: cnone=value one; cntwo=value two; cnthree=value three; To get the Cookies that are sent back by the browser, we can use request.getCookies( ) method. If there are no Cookies a null will be returned by this method. <% System.out.println("----getcks.jsp----"); Cookie c[ ]=request.getCookies( ); if(c==null) { out.println("---no Cookies---"); } else { for(int i=0;i<c.length;i++) { out.println(c[i].getName( )); out.println(c[i].getValue( )); out.println("<br>"); } } %> http://localhost:7001/wapp/getcks.jsp ----getcks.jsp---cnone value one cntwo value two cnthree value three JSESSIONID HXN7sL0T911ZaGC6bVCVkEsysz439wZKqLjZ15KFHzPf5tqqB3jn!628735853

Close the Browser & restart the browser again http://localhost:7001/wapp/getcks.jsp ----getcks.jsp------no Cookies--To get the value a specific Cookie we can provide the code as shown below <% System.out.println("----getsvcks.jsp----"); Cookie c[ ]=request.getCookies( ); String vcnone=null; for(int i=0;i<c.length;i++) { if(c[i].getName( ).equals("cnone")) { vcnone=c[i].getValue( ); } } out.println(vcnone); %> http://localhost:7001/wapp/getsvcks.jsp value one SQL> select * from student; no rows selected form one

form two Web container <html> <head> <title>cform</title> </head> <body> <form action="csf.jsp"> Student no:

<input type="text" name="sno"> <br> Student name: <input type="text" name="sname"> <br> <input type="submit" value="Next"> <br> </form> </body> </html> When the form one is submitted web container executes csf.jsp. csf.jsp performs the following tasks. 1)Captures the data 2)Crates the Cookies by using the capture data 3)Sends the Cookies to the browser 4)Generates form two <% String vsno=request.getParameter("sno"); String vsname=request.getParameter("sname"); Cookie c1=new Cookie("csno",vsno); Cookie c2=new Cookie("csname",vsname); response.addCookie(c1); response.addCookie(c2); %> <html> <head> <title>csf.jsp</title> </head> <body> <form action="csd.jsp"> Father name: <input type="text" name="fname"> <br> Address: <input type="text" name="addr"> <br> <input type="submit" value="store"> <br> </form> </body> </html> When the form two is submitted web container executes csd.jsp. csd.jsp performs the following tasks 1)Captures the values of the fields or parameters fname, address 2)Gets the values of the Cookies csno & csname 3)Stores the data into the database 4)Generates the output that contains the data stored in the database <%@ page import="java.sql.*" %> <% String vsno=null, vsname=null; String vfname=request.getParameter("fname"); String vaddr=request.getParameter("addr");

Cookie c[ ]=request.getCookies( ); String vcnone=null; for(int i=0;i<c.length;i++) { if(c[i].getName( ).equals("csno")) { vsno=c[i].getValue( ); } if(c[i].getName( ).equals("csname")) { vsname=c[i].getValue( ); } } // code to connect DB Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:xe","scott","tiger"); String vsql="insert into student values(?,?,?,?)"; PreparedStatement pstmt=con.prepareStatement(vsql); pstmt.setString(1,vsno); pstmt.setString(2,vsname); pstmt.setString(3,vfname); pstmt.setString(4,vaddr); pstmt.executeUpdate( ); con.close( ); %> Stored data in student table <br> <%= vsno%> <br> <%= vsname%> <br> <%= vfname%> <br> <%= vaddr%> <br> http://localhost:7001/wapp/cform.html Student no:
Next 1 sone

Student name:

Clicked
fone aone

Father name: Address:


store

Clicked Stored data in student table 1 sone fone aone

SQL> select * from student; SNO SNAME FNAME ADDR -------------------- -------------------- -------------------- ---------------1 sone fone aone 1) Like hidden field applications more amount of data will be transfer between the client & server 2) The above application will be fail if the Cookies are denied/ rejected/ not accepted by the browser. 3) If too much of information is available then we can not use the Cookies. 4) Cookies are used in developing the application that generates PERSONALIZED CONTENT. 3) Sessions: <% out.println("--sesone.jsp--<br>"); String s=session.getId( ); out.println(s); %> <% out.println("--sesten.jsp--<br>"); String s=session.getId( ); out.println(s); %> http://localhost:7001/wapp/sesone.jsp --sesone.jsp-HXzcdhn8pGB6BjR1VRDluPQba1FrlGJlVTPquIwUoz9l3AsG2BFw!1646299904! 1205318492500 http://localhost:7001/wapp/sesten.jsp --sesten.jsp-HXzcdhn8pGB6BjR1VRDluPQba1FrlGJlVTPquIwUoz9l3AsG2BFw!1646299904! 1205318492500 Open the other browser & send the same above requests. http://localhost:7001/wapp/sesone.jsp --sesone.jsp HX1nzKbSh5McCWk6sbDi8Ymd2NDMrgbMpaiC6g7yvD8LOpQfjiFD!1646299904! 1205319015125 http://localhost:7001/wapp/sesten.jsp --sesten.jsp

HX1nzKbSh5McCWk6sbDi8Ymd2NDMrgbMpaiC6g7yvD8LOpQfjiFD!1646299904! 1205319015125 Browser one

Browser two Web container The web container is responsible for maintaining one session object for every client/ browser that is accessing the web application. Web container assigns (gives) a using id for every session object. The above application can be implementing using the session objects. ** When we need to use session scope? A) If a java object holds any thing specific to the clients & if the object is required while processing multiple request then we must used the session scope. SQL> select * from student; no rows selected Bone(form one)

Btwo(form two) Web container <html> <head>

<title>sform</title> </head> <body> <form action="ssf.jsp"> Student no: <input type="text" name="sno"> <br> Student name: <input type="text" name="sname"> <br> <input type="submit" value="Next"> <br> </form> </body> </html> Web container executes ssf.jsp, when the user submits the form1. The following tasks are performed by ssf.jsp. 1)Capture the data. 2)Stores the capture data in the session object associated(linked) with the browser that as sent to the request. 3)Generates form2. <% String vsno=request.getParameter("sno"); String vsname=request.getParameter("sname"); System.out.println(session.getId( )); session.setAttribute("sno",vsno); session.setAttribute("sname",vsname); %> <html> <head> <title>ssf.jsp</title> </head> <body> <form action="sssd.jsp"> Father name: <input type="text" name="fname"> <br> Address: <input type="text" name="addr"> <br> <input type="submit" value="store"> <br> </form> </body> </html> We execute sssd.jsp when form2 is submitted. This JSP performs the following tasks. 1)Picks up the data available in session object. 2)Capture the data provided by the browser 3)Stores the data in the database. 4)Generates the content to provide the information about the data stored in database.

<%@ page import="java.sql.*" %> <% System.out.println(session.getId( )); String vsno=(String)session.getAttribute("sno"); String vsname=(String)session.getAttribute("sname"); String vfname=request.getParameter("fname"); String vaddr=request.getParameter("addr"); // code to connect DB Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:xe","scott","tiger"); String vsql="insert into student values(?,?,?,?)"; PreparedStatement pstmt=con.prepareStatement(vsql); pstmt.setString(1,vsno); pstmt.setString(2,vsname); pstmt.setString(3,vfname); pstmt.setString(4,vaddr); pstmt.executeUpdate( ); con.close( ); %> Stored data in student table <br> <%= vsno%> <br> <%= vsname%> <br> <%= vfname%> <br> <%= vaddr%> <br> http://localhost:7001/jsp/sform.html Student no:
Next 1 sone

Student name:

Clicked HX2oUgMV00hkJeln5L6PeAHvmHwhIhkQxDFtTa88zxSfNi2nHvsJ!-147352160! 1205337640734


sone 1 fone

Father name:
aone

Address:
store

Clicked HX2oUgMV00hkJeln5L6PeAHvmHwhIhkQxDFtTa88zxSfNi2nHvsJ!-147352160! 1205337640734 Stored data in student table 1 sone fone aone SQL> select * from student;

SNO SNAME FNAME ADDR -------------------- -------------------- ---------------------- -----------------1 sone fone aone The web container manages the session object using the Cookies. If the Cookies are denied then we will not be able to associate(link) the session object properly with the client and the above application will fail. If the above application has to work even if the Cookies are denied then we need to use URL rewriting technique. For using this technique we must use response.encodeURL( ) method. In the above application we must used <form action="<%=response.encodeURL("sssd.jsp")%>"> in place of <form action="sssd.jsp"> For generating the URLs in the form tags, anchor tags, response.encodeURL( ) method must be used. This method appends the sessionid to the URL as shown below sssd.jsp; jsessionid=HG734 response.encodeURL takes a little bit of time for rewriting the URL. This puts additional burden on the server & the performance slightly decreases. ** What is the difference between request.getSession(true) & request.getSession(false)? A) <% HttpSession s=request.getSession(true); out.println("isNew--->"+s.isNew( )); %> http://localhost:7001/wapp/str.jsp isNew--->true refresh the same URL http://localhost:7001/wapp/str.jsp isNew--->false <% HttpSession s=request.getSession(false); out.println(s); %> http://localhost:7001/wapp/sfa.jsp null type the URL http://localhost:7001/wapp/str.jsp isNew--->true type the URL http://localhost:7001/wapp/sfajsp weblogic.servlet.internal.session.MemorySessionData@13ec758 When HttpSession s=request.getSession(true); is executed web container checks for the session object of the browser that has sent the request. If the object is available web container uses the existing object. If the object is not available web container creates a new session object.

When HttpSession s=request.getSession(false); is executed a null will be written, if there is no session object for the browser that has sent to the request. If the session object is available it picks of the existing session object. Note: -In case of JSPs the code generated by JSPC internally uses request.getSession(true). The web container removes a session object in one of the following conditions. 1)When the servlet class session.invalidate( ) method. 2)Is a session object is not used for some amount of time called as session-timeout or maxInactiveInterval, then the session object will be removed by the server. We can set the session-timeout value to 5 minutes by adding the following tags to web.xml. <session-config> <session-timeout>5</session-timeout> </session-config> <% String s=session.getId( ); out.println(s); %> http://localhost:7001/wapp/sesone.jsp HbgojLiNpgG2Donsk3ELC0iQ1x4F63FySDQSJZwzEH1bS0SwgodP!103456190! 1205559464218 Refresh the URL http://localhost:7001/wapp/sesone.jsp HbgojLiNpgG2Donsk3ELC0iQ1x4F63FySDQSJZwzEH1bS0SwgodP!103456190! 1205559464218 After 5 minutes refresh the same URL http://localhost:7001/wapp/sesone.jsp Hbh4vHxgfaH4VxeOoka2Jz6wvkGWks5v1mS1QLVr1FSWhToKrJn2!103456190! 1205559608234 programmatically we can set the value of session-timeout to 10 minutes using the code as shown below <% String s=session.getId( ); session.setMaxInactiveInterval(600); out.println(s); %> http://localhost:7001/wapp/sestwo.jsp HbijrbeglzuINKkSeH4BehI5NYWVF0tFhHow4lLRw11A72kgku4e!128744544! 1205559907750 Refresh the URL http://localhost:7001/wapp/sestwo.jsp HbijrbeglzuINKkSeH4BehI5NYWVF0tFhHow4lLRw11A72kgku4e!128744544! 1205559907750 After 10 minutes refresh the same URL http://localhost:7001/wapp/sestwo.jsp HbiyGVHkVlGcqO4cSaa1SXdKcU88Qw1jLN0ckNpnjPZGfq8Vas47!128744544! 1205560050000 If we open multiple windows (by pressing ctrl+n in internet explorer) as part of a single process, then all the windows will be treated as a single client. In this case only one

session session object will be maintain in the server. If we open multiple windows as part of different process then there will be treated as multiple clients & the server will maintain different session objects. <% Cookie c1=new Cookie("cnone","value one"); c1.setMaxAge(160); Cookie c2=new Cookie("cntwo","value two"); response.addCookie(c1); response.addCookie(c2); %> http://localhost:7001/cookie/cookie.jsp D:\psr\J2EE>java HWebServer1 8000 logging to stdout root=D:\psr\J2EE timeout=5000 workers=5 http://localhost:8000/cookie/cookie.jsp ...GET /cookie/cookie.jsp HTTP/1.1 Cookie: cnone=value one; cntwo=value two; JSESSIONID=Hbv8LAbC7u VIxhYm1B2x7b7m61sal97ZI6ued1J65OtmId6iEcDp!1255848599 After 160 sec refresh the same URL http://localhost:8000/cookie/cookie.jsp ...GET /cookie/cookie.jsp HTTP/1.1 Cookie: cntwo=value two; JSESSIONID= Hbv8LAbC7uVIxhYm1B2x7b7m61 sal97ZI6ued1J65Otm Id6iEcDp!1255848599 The browser stores cnone cookie in the disk & the browser is responsible for holding the cookie for 160 sec. if the user closes the browser before the expiry time then also the browser will hold the cookie with it. SQL> create table newstype(movies varchar(100),sports varchar(50)); Table created. SQL> insert into newstype values('Comedy','Cricket'); 1 row created. SQL> insert into newstype values('Horror','Hockey'); 1 row created. SQL> insert into newstype values('Action','Tennis'); 1 row created. SQL> commit; Commit complete. SQL> select * from newstype; MOVIES SPORTS -------------------------------- ----------------------

Comedy Horror Action

Cricket Hockey Tennis

<html> <head> <title>pers.html</title> </head> <body> <form action="pers.jsp"> News Type(movies,sports): <input type="text" name="ntype"> <br> <input type="submit" value="personalize"> </form> </body> </html> <% String vntype=request.getParameter("ntype"); Cookie c=new Cookie("cntype",vntype); c.setMaxAge(60*60*24*90); response.addCookie(c); System.out.println(c); %> Thanks for using our app <br> <a href="getnews.jsp"> Click to get news </a> <%@ page import="java.sql.*" %> <% Cookie c[ ]=request.getCookies( ); if(c==null) { out.println("<a href=\"pers.html\"> personalize </a>"); return; } String vcntype=null; for(int i=0;i<c.length;i++) { if(c[i].getName( ).equals("cntype")) { vcntype=c[i].getValue( ); } } if(vcntype==null) { out.println("<a href=\"pers.html\"> personalize </a>"); return;

} out.println("News related to --->"+vcntype); // code to get data from db based on ntype String vsql="select * from newstype"; Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:xe","scott","tiger"); Statement stmt=con.createStatement( ); ResultSet rs=stmt.executeQuery(vsql); String ntype; while(rs.next( )) { ntype=rs.getString(vcntype); out.println("<br>"+ntype); } %> http://localhost:7001/cookie/pers.html News Type(movies,sports):
personalize sports

Clicked javax.servlet.http.Cookie@ed3b53 Thanks for using our app Click to get news Clicked News related to --->sports cricket Hockey Tennis http://localhost:7001/cookie/pers.html News Type(movies,sports):
personalize movies

Clicked Thanks for using our app Click to get news Clicked News related to --->movies Comedy Horrer Action ** When do need to use scope=application? A) When a java object holds nothing specific to the client & if it is required while processing multiple request then we must store the java object in application object. Ex: -

config.txt (we can use xml file here) package org.students; import java.sql.*; public class APBean { private String compName; private String address; private String bgcolor; public APBean( ) { // code to get the data from config.txt compName="Xyz Ltd"; address="SR.Nagar,Hyd"; bgcolor="123456"; } public String getCompName( ) { return this.compName; } public String getAddress( ) { return this.address; } public String getBgcolor( ) { return this.bgcolor; } } D:\Pskr>javac -d . APBean.java The above java bean holds nothing specific to the client. <jsp:useBean id="ap" class="org.students.APBean" scope="application"/> welcome to <jsp:getProperty name="ap" property="compName"/> <br> <jsp:getProperty name="ap" property="address"/> <br> some other output of app.jsp http://localhost:7001/app/app.jsp welcome to Xyz Ltd SR.Nagar,Hyd some other output of app.jsp JSP Custom Tag library: - It is a set of JSP tags.

The implementer of a tag library is responsible for providing 1) A TLD (tag library descriptor) file 2) A set of Tag classes. A tag class (TagHandler class) implements javax.servlet.jsp.tagext.Tag interface. Examples of Tag classes: public class XTag implements Tag { -------} public class YTag extends TagSupport { -------} package org.students; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class WelcomeTH extends TagSupport { public int doEndTag( ) throws JspException { System.out.println("----welcomeTh.doEndTag( )----"); try { JspWriter out=pageContext.getOut( ); out.println("---welcome---"); } catch(Exception e) { } return EVAL_PAGE; } } D:\Pskr>javac -d . WelcomeTH.java D:\Pskr>jar cf ourtl.jar . <taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.1</jsp-version> <short-name>stud</short-name> <uri>http://www.compx.com/ourtl</uri> <description> --------</description> <tag> <name>welcome</name> <tag-class>org.students.WelcomeTH</tag-class> </tag> </taglib> Save: - stud.tld

Procedure for using a tag library in a web project: 1) Copy the tld file in WEB-INF directory. 2) Copy the jar file jar file that contains the classes related to the tag library in WEB-INF/lib directory. 3) Provide the information about the tld file in web.xml as shown below <web-app> <taglib> <taglib-uri>http://www.compx.com/ourtl</taglib-uri> <taglib-location>/WEB-INF/stud.tld</taglib-location> </taglib> </web-app> 4) Use taglib directive in the JSP page for importing/ using the tag library. <%@ taglib uri="http://www.compx.com/ourtl" prefix="student" %> <br> ---------- <br> <student:welcome/> <br> xxxxxxxxxx <br> http://localhost:7001/exe/utag.jsp ----welcomeTh.doEndTag( )---------------welcome--xxxxxxxxxx A tag can support an attribute. For supporting an attribute with the name xxx we must provide a method with the name setXxx in our tag class. package org.students; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class AddTH extends TagSupport { int vopOne,vopTwo; public void setOpOne(int opOne) { vopOne=opOne; } public void setOpTwo(int opTwo) { vopTwo=opTwo; } public int doEndTag( ) throws JspException { System.out.println("----welcomeTh.doEndTag( )----"); try { JspWriter out=pageContext.getOut( ); out.println(vopOne+vopTwo); }

catch(Exception e) { } return EVAL_PAGE; } } D:\Pskr>javac -d . AddTH.java <taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.1</jsp-version> <short-name>stud</short-name> <uri>http://www.compx.com/ourtl</uri> <description> --------</description> <tag> <name>add</name> <tag-class>org.students.AddTH</tag-class> </tag> </taglib> <%@ taglib uri="http://www.compx.com/ourtl" prefix="student" %> <student:add opOne="100" opTwo="200"/> http://localhost:7001/exe/atag.jsp ----welcomeTh.doEndTag( )---300 doEndTag( ) can be returns one of the following constants 1)EVAL_PAGE the remaining part of the JSP will be executed. 2)SKIP_PAGE the remaining part of the JSP will be skipped. in the WelcomeTH class we replace SKIP_PAGE in the place of EVAL_PAGE http://localhost:7001/exe/utag.jsp ----welcomeTh.doEndTag( )---------------welcome-- JSP standard tag libraries (JSTL) are a set of tag libraries. 1)JSTL core ---- most important tags like set, out, if, remove, forEach etc are part of core TL. 2)JSTL xml ---- contains the tags that are meant for dealing with xml content. 3)JSTL sql ---- contains the tags for dealing with database servers. 4)JSTL fmt(format) ---- contains the tags that can be used for developing i18n (internationalization) applications. Procedure for using JSTL tag libraries as part of a web application: Step 1: - copy JSTL related tld files in WEB-INF directory.

As part of the JSTL two types of tag libraries are provided. 1)The tag libraries that support EL (Expression language) expressions. (c.tld, sql.tld, x.tld, fmt.tld) 2)The tag libraries that support JSP expressions (also called run time expressions). (crt.tld, sql-rt.tld, x-rt.tld, fmt-rt.tld). rt means runtime. Step 2: - Copy the jar files of JSTL to WEB-INF/ lib directory. Step 3: - Provide the information about the tlds in web.xml file. <web-app> <taglib> <taglib-uri>http://java.sun.com/jstl/core</taglib-uri> <taglib-location>/WEB-INF/c.tld</taglib-location> </taglib> <taglib> <taglib-uri>http://java.sun.com/jstl/core_rt</taglib-uri> <taglib-location>/WEB-INF/c-rt.tld</taglib-location> </taglib> <taglib> <taglib-uri>http://java.sun.com/jstl/sql</taglib-uri> <taglib-location>/WEB-INF/sql.tld</taglib-location> </taglib> <taglib> <taglib-uri>http://java.sun.com/jstl/sql_rt</taglib-uri> <taglib-location>/WEB-INF/sql-rt.tld</taglib-location> </taglib> <taglib> <taglib-uri>http://java.sun.com/jstl/fmt</taglib-uri> <taglib-location>/WEB-INF/fmt.tld</taglib-location> </taglib> <taglib> <taglib-uri>http://java.sun.com/jstl/fmt_rt</taglib-uri> <taglib-location>/WEB-INF/fmt-rt.tld</taglib-location> </taglib> <taglib> <taglib-uri>http://java.sun.com/jstl/xml</taglib-uri> <taglib-location>/WEB-INF/x.tld</taglib-location> </taglib> <taglib> <taglib-uri>http://java.sun.com/jstl/xml_rt</taglib-uri> <taglib-location>/WEB-INF/x-rt.tld</taglib-location> </taglib> </web-app> Step 4: - Use the taglib directive in the directive in the JSP for using the tag libraries. <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <%

pageContext.setAttribute("svone","10"); pageContext.setAttribute("svtwo","20"); %> <c:out value="welcome"/> <br> names of the scoped variables. <c:out value="${svone}"/> <br> <c:out value="${svtwo}"/> <br> EL expressions. <c:out value="${svone+svtwo}"/> <br> http://localhost:7001/jstl/aeln.jsp welcome 10 20 30 We can eliminate the java code from the above JSP using the set tag as shown below <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <c:set var="svone" value="10" scope="page"/> <c:set var="svtwo" value="20" scope="page"/> <c:out value="welcome"/> <br> <c:out value="${svone}"/> <br> <c:out value="${svtwo}"/> <br> <c:out value="${svone+svtwo}"/> <br> http://localhost:7001/jstl/wuaeln.jsp welcome 10 20 30 remove tag can be used to remove the java objects that are stored in various scopes. <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <c:set var="svone" value="10"/> <c:out value="..${svone}.."/> <br> <c:remove var="svone"/> <br> <c:out value="..${svone}.."/> <br> http://localhost:7001/jstl/raeln.jsp ..10.. .... <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <c:set var="svone" value="10" scope="page"/> <c:set var="svtwo" value="20" scope="page"/> <c:set var="svthr" value="30" scope="page"/> <c:out value="${svone+svtwo}"/> <br> <c:out value="${svone-svtwo}"/> <br> <c:out value="${svone*svtwo}"/> <br> <c:out value="${svone/svtwo}"/> <br> <c:out value="${svone>svtwo}"/> <br> <c:out value="${svone<svtwo}"/> <br>

<c:out value="${(svone<svtwo)&&(svtwo<svthr)}"/> <br> http://localhost:7001/jstl/ope.jsp 30 -10 200 0.5 false true true EL expressions can support various implicit variables like param, header, pageScope, reqestScope, sessionScope, applicationScope etc The implicit variable param can be used to access the values of the parameters.

Sno, sname, age are names of the fields (or) parameters. <html> <head> <title>form.html</title> </head> <body> <form action="js.jsp"> Student no: <input type="text" name="sno"> <br> Student name: <input type="text" name="sname"> <br> Age: <input type="text" name="age"> <br> <input type="submit" value="store"> <br> </form> </body> </html> <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> Data provided by you <br> Student no: <c:out value="${param.sno}"/> <br> Student Name: <c:out value="${param.sname}"/> <br>

Age: <c:out value="${param.age}"/> <br> http://localhost:7001/jstl/form.html Student no: Age:


store 25 130 Sudheer Re

Student name:

Clicked Data provided by you Student no: 130 Student Name: Sudheer Reddy Age: 25 We can use the implicit variables pageScope, applicationScope, requestScope etc for accessing the scoped variables available in various scopes. <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <c:set scope="application" var="vone" value="1"/> <c:set scope="request" var="vone" value="2"/> <c:set scope="page" var="vone" value="3"/> <c:set scope="session" var="vone" value="4"/> <c:out value="${vone}"/> http://localhost:7001/jstl/scopes.jsp 3 The order of the scopes is pageScope, requestScope, sessionScope, applicationScope. <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> ---<c:out value="${sessionScope.vone}"/> <br> +++<c:out value="${requestScope.vone}"/> <br> ***<c:out value="${pageScope.vone}"/> <br> ///<c:out value="${applicationScope.vone}"/> <br> http://localhost:7001/jstl/scope.jsp ---3 +++ *** ///1 The EL expressions can be used to access the properties of a Java Bean package org.students; public class StudentBean { int age; String userName; org.students.AddressBean address; public void setAge(int age) {

System.out.println("----setAge---->"+age); this.age=age; } public int getAge( ) { System.out.println("----getAge---->"+this.age); return this.age; } public void setUserName(String userName) { System.out.println("----setUserName---->"+userName); this.userName=userName; } public String getUserName( ) { System.out.println("----getUserName---->"+this.userName); return this.userName; } public void setAddress(org.students.AddressBean address) { System.out.println("----setAddress---->"+address); this.address=address; } public org.students.AddressBean getAddress( ) { System.out.println("----getAddress---->"+this.address); return this.address; } public StudentBean( ) { System.out.println("----StudentBean created----"); } } d:\pskr>javac d . StudentBean.java package org.students; public class AddressBean { String state; String city; String street; public void setState(String state) { System.out.println("----setState---->"+state); this.state=state; } public String getState( )

{ System.out.println("----getState---->"+this.state); return this.state; } public void setCity(String city) { System.out.println("----setCity---->"+city); this.city=city; } public String getCity( ) { System.out.println("----getCity---->"+this.city); return this.city; } public void setStreet(String street) { System.out.println("----setStreet---->"+street); this.street=street; } public String getStreet( ) { System.out.println("----getStreet---->"+this.street); return this.street; } public AddressBean( ) { System.out.println("----AddressBean created----"); } } d:\pskr>javac d . AddressBean.java <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <% org.students.AddressBean ab=new org.students.AddressBean(); ab.setState("StOne"); ab.setCity("CityOne"); ab.setStreet("StrOne"); pageContext.setAttribute("svab",ab); %> 1 <c:out value="${pageScope.svab}"/> <br> <c:out value="${pageScope.svab.state}"/> <br> <c:out value="${pageScope.svab.city}"/> <br> <c:out value="${pageScope.svab.street}"/> <br> 2 http://localhost:7001/jstl/bean.jsp ----AddressBean created-------setState---->StOne ----setCity---->CityOne

----setStreet---->StrOne ----getState---->StOne ----getCity---->CityOne ----getStreet---->StrOne org.students.AddressBean@a96863 StOne CityOne StrOne

ab

pageContext AddressBean 1 When the expression 1 is evaluated the AddressBean object will be picked up from the pageContext & toString( ) method will be executed. The out tag sends the value returned by toSting to the browser. 2 When the expression 2 is evaluated the AddressBean object will be picked up from pageContext & getState( ) method will be executed. ab StrOne

request AddressBean sb StudentBean <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <% org.students.AddressBean ab=new org.students.AddressBean(); ab.setState("StOne"); ab.setCity("CityOne"); ab.setStreet("StrOne"); org.students.StudentBean sb=new org.students.StudentBean(); sb.setAge(25); sb.setUserName("Sudheer Reddy"); sb.setAddress(ab); request.setAttribute("svsb",sb); %> <c:out value="${requestScope.svsb}"/> <br> <c:out value="${requestScope.svsb.age}"/> <br> <c:out value="${requestScope.svsb.userName}"/> <br> <c:out value="${requestScope.svsb.address.state}"/> <br> <c:out value="${requestScope.svsb.address.city}"/> <br> <c:out value="${requestScope.svsb.address.street}"/> <br>

http://localhost:8000/jstl/beans.jsp ----AddressBean created-------setState---->StOne ----setCity---->CityOne ----setStreet---->StrOne ----StudentBean created-------setAge---->25 ----setUserName---->Sudheer Reddy ----setAddress---->org.students.AddressBean@12cb585 ----getAge---->25 ----getUserName---->Sudheer Reddy ----getAddress---->org.students.AddressBean@12cb585 ----getState---->StOne ----getAddress---->org.students.AddressBean@12cb585 ----getCity---->CityOne ----getAddress---->org.students.AddressBean@12cb585 ----getStreet---->StrOne org.students.StudentBean@1e2a069 25 Sudheer Reddy StOne CityOne StrOne <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <c:forEach var="i" begin="0" end="8" step="2"> ----<br> <c:out value="${i}"/> <br> </c:forEach> http://localhost:7001/jstl/inum.jsp ---0 ---2 ---4 ---6 ---8 The body of the above forEach tag will be evaluated for 5 times. Every time the value of the variable I will be incremented by 2. <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <c:forEach var="i" items="one,two,three"> <c:out value="${i}"/> <br>

</c:forEach> http://localhost:7001/jstl/item.jsp one two three forEach tag uses a comma (,) as a delimiter. We can not use other delimiters with forEach tag. If the delimiter is not a comma (,) them we must used forTokens tag as shown below. <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <c:forTokens var="i" delims=":" items="one:two:three"> <c:out value="${i}"/> <br> </c:forTokens> http://localhost:7001/jstl/items.jsp one two three String objects pageContext Object Array <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <% Object oarr[ ]=new Object[5]; oarr[0]="Str One"; oarr[1]="Str Two"; oarr[2]="Str Thr"; oarr[3]="Str Four"; oarr[4]="Str Five"; pageContext.setAttribute("svarr",oarr); %> <c:forEach var="i" items="${pageScope.svarr}"> --- <c:out value="${i}"/> ---<br> </c:forEach> http://localhost:7001/jstl/oarr.jsp --- Str One ----- Str Two ----- Str Thr ----- Str Four ----- Str Five -- <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <%

Object oarr[ ]=new Object[2]; org.students.AddressBean ab=new org.students.AddressBean( ); ab.setState("StOne"); ab.setCity("CityOne"); ab.setStreet("StrOne"); oarr[0]=ab; ab=new org.students.AddressBean( ); ab.setState("StTwo"); ab.setCity("CityTwo"); ab.setStreet("StrThr"); oarr[1]=ab; pageContext.setAttribute("svarr",oarr); %> <c:forEach var="i" items="${pageScope.svarr}"> --- <c:out value="${i.state}"/> ---<br> --- <c:out value="${i.city}"/> ---<br> --- <c:out value="${i.street}"/> ---<br> ------------------- <br> </c:forEach> http://localhost:7001/jstl/ibeans.jsp --- StOne ----- CityOne ----- StrOne ----------------------- StTwo ----- CityTwo ----- StrThr --------------------The above forEach tag can be used to access the AddressBean object stored inside a Vector, ArrayList <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <% java.util.Vector v=new java.util.Vector( ); org.students.AddressBean ab; ab=new org.students.AddressBean( ); ab.setState("StOne"); ab.setCity("CityOne"); ab.setStreet("StrOne"); v.add(ab); ab=new org.students.AddressBean( ); ab.setState("StTwo"); ab.setCity("CityTwo"); ab.setStreet("StrThr"); v.add(ab); pageContext.setAttribute("svarr",v); %>

<c:forEach var="i" items="${pageScope.svarr}"> --- <c:out value="${i.state}"/> ---<br> --- <c:out value="${i.city}"/> ---<br> --- <c:out value="${i.street}"/> ---<br> ------------------- <br> </c:forEach> http://localhost:7001/jstl/vibeans.jsp --- StOne ----- CityOne ----- StrOne ----------------------- StTwo ----- CityTwo ----- StrThr -------------------- <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <% java.util.Hashtable ht=new java.util.Hashtable( ); org.students.AddressBean ab; ab=new org.students.AddressBean( ); ab.setState("StOne"); ab.setCity("CityOne"); ab.setStreet("StrOne"); ht.put("xxx",ab); ab=new org.students.AddressBean( ); ab.setState("StTwo"); ab.setCity("CityTwo"); ab.setStreet("StrThr"); ht.put("yyy",ab); pageContext.setAttribute("svarr",ht); %> <c:forEach var="i" items="${pageScope.svarr}"> --- <c:out value="${i.value.state}"/> ---<br> --- <c:out value="${i.value.city}"/> ---<br> --- <c:out value="${i.value.street}"/> ---<br> ------------------- <br> </c:forEach> http://localhost:7001/jstl/hibeans.jsp --- StOne ----- CityOne ----- StrOne ----------------------- StTwo ----- CityTwo ----- StrThr ---

------------------In the above AddressBean object are stored as the keys of the Hashtable. To access the properties of the AddressBean stored as the keys of a Hashtable, the code forEach (shown above) will be used. <html> <head> <title>ctax.html</title> </head> <body> <form action="ctax.jsp"> Applicant Name: <input type="text" name="applName"> <br> Age: <input type="text" name="age"> <br> Total Income: <input type="text" name="income"> <br> <input type="submit" value="Calculate Tax"> <br> </form> </body> </html> <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> Dear <c:out value="${param.applName}"/> ,<br> Your Tax due is ----> <c:if test="${param.age<=60}"> <c:out value="${param.income*0.30}"/> </c:if> <c:if test="${param.age>60}"> <c:out value="${param.income*0.25}"/> </c:if> http://localhost:7001/jstl/ctax.html Applicant Name: Age:
42 200000 sunil

Total Income:
Calculate Tax

Clicked

Dear sunil , Your Tax due is ----> 60000.0 http://localhost:7001/jstl/ctax.html Applicant Name: Age:
65 200000 usha

Total Income:
Calculate Tax

Clicked

Dear usha, Your Tax due is ----> 50000.0 <html> <head> <title>cdet.html</title> </head> <body> <form action="cdet.jsp"> Course: <input type="text" name="course"> <br> <input type="submit" value="Get details"> <br> </form> </body> </html> <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <c:choose> <c:when test="${param.course<='c'}"> details of C course <br> -------- <br> -------- <br> </c:when> <c:when test="${param.course<='cpp'}"> details of Cpp course <br> -------- <br> -------- <br> </c:when> <c:otherwise> We are not offering <c:out value="${param.course}"/> course </c:otherwise> </c:choose> http://localhost:8000/jstl/cdet.html Course:
Get details c

Clicked details of C course --------------http://localhost:8000/jstl/cdet.html


java

Course:
Get details

Clicked We are not offering java course

<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="crt" %> <crt:forEach var="i" items="one,two,three"> <crt:out value="${i}"/> <br> </crt:forEach> http://localhost:7001/jstl/crt.jsp

${i} ${i} ${i} c_rt, sql_rt, . etc tag libraries that support JSP Expressions. These are not supported EL expressions. So it displays EL expressions as it is. It will be treated as it is String. <html> <head> <title>crt.html</title> </head> <body> <form action="crt.jsp"> Name: <input type="text" name="name"> <br> <input type="submit" value="Send"> <br> </form> </body> </html> <%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="crt" %> Your entered name is <crt:out value='<%=request.getParameter("name")%>'/> http://localhost:7001/jstl/crt.html Name:
Send Sudheer Re

Clicked Your entered name is Sudheer Reddy

SQL> select * from student; no rows selected <%@ taglib uri="http://java.sun.com/jstl/sql" prefix="sql" %> <sql:setDataSource var="ds" driver="oracle.jdbc.driver.OracleDriver" url="jdbc:oracle:thin:@localhost:1521:xe" user="scott" password="tiger"/> <sql:update dataSource="${ds}"> insert into student values(1,'sunil','kesav','nrp') </sql:update> Data stored in student table http://localhost:7001/jstl/isdata.jsp Data stored in student table SQL> select * from student; SNO SNAME FNAME ADDR ---------- -------------------- -------------------- ---------1 sunil kesav nrp <html> <head>

<title>idata</title> </head> <body> <form action="idata.jsp"> Student no: <input type="text" name="sno"> <br> Student name: <input type="text" name="sname"> <br> Father name: <input type="text" name="fname"> <br> Address: <input type="text" name="address"> <br> <input type="submit" value="store"> <br> </form> </body> </html> <%@ taglib uri="http://java.sun.com/jstl/sql" prefix="sql" %> <sql:setDataSource var="ds" driver="oracle.jdbc.driver.OracleDriver" url="jdbc:oracle:thin:@localhost:1521:xe" user="scott" password="tiger"/> <sql:update dataSource="${ds}"> insert into student values(?,?,?,?) <sql:param value="${param.sno}"/> <sql:param value="${param.sname}"/> <sql:param value="${param.fname}"/> <sql:param value="${param.address}"/> </sql:update> Data stored in student table http://localhost:7001/jstl/idata.html Student no: Father name: Address:
store atp 2 latha krishna

Student name:

Clicked Data stored in student table SQL> select * from student; SNO SNAME FNAME ADDR ---------- -------------------- -------------------- ---------1 sunil kesav nrp 2 latha krishna atp <%@ taglib uri="http://java.sun.com/jstl/sql" prefix="sql" %> <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <sql:setDataSource var="ds" driver="oracle.jdbc.driver.OracleDriver"

url="jdbc:oracle:thin:@localhost:1521:xe" user="scott" password="tiger"/> <sql:query var="result" dataSource="${ds}"> select * from student </sql:query> <c:forEach var="row" items="${result.rows}"> <c:out value="${row.sno}"/> <br> <c:out value="${row.sname}"/> <br> <c:out value="${row.fname}"/> <br> <c:out value="${row.addr}"/> <br> --------- <br> </c:forEach> http://localhost:7001/jstl/esdata.jsp 1 sunil kesav nrp --------2 latha krishna atp -------- SQL> select * from newstype; no rows selected SQL> delete from student; 2 rows deleted SQL> select * from student; no rows selected Multiple sql statements can be executed in a single transaction by using the transaction tag. <%@ taglib uri="http://java.sun.com/jstl/sql" prefix="sql" %> <sql:setDataSource var="ds" driver="oracle.jdbc.driver.OracleDriver" url="jdbc:oracle:thin:@localhost:1521:xe" user="scott" password="tiger"/> <sql:transaction dataSource="${ds}"> <sql:update> insert into student values(100,'pinki','siva','hyd') </sql:update> <sql:update> insert into newstype values('Tragedy','Chess') </sql:update> </sql:transaction> Data stored in student & newstype tables http://localhost:7001/jstl/itab.jsp

Data stored in student & newstype tables SQL> select * from student; SNO SNAME FNAME ADDR ---------- -------------------- -------------------- ---------100 pinki siva hyd SQL> select * from newstype; MOVIES SPORTS ---------------------- -------------------Tragedy Chess public class App { public static void main(String args[ ]) { for(int i=1;i<1000000;i++) { System.out.println("This is the output of App "+i); i++; } } } D:\Pskr>javac App.java The JVM uses the memory area called Heap Space for storing the java objects. The size of the Heap Space used by the JVM can be controlled using the options Xms and Xms Initial heap size maximum heap size D:\Pskr>java Xms3m Xmx6m App This is the output of App 1 This is the output of App 2 .. This is the output of App 748570 This is the output of App 748570 If the above command is used the JVM will allocate 3mb memory space initially for the heap. If that is not enough the JVM keeps on internally the memory space till the maximum space 6mb is ranged.

You might also like