Servlets and JSP
Purpose of the Web-tier
• A J2EE application’s Web tier makes the application’s business logic available on the World Wide Web. The Web tier handles all of a J2EE application’s communication with Web clients, invoking business logic and transmitting data in response to incoming requests. • A server in the Web tier processes HTTP requests. In a J2EE application, the Web tier usually manages the interaction between Web clients and the application’s business logic. • The Web tier typically produces HTML or XML content, though the Web tier can generate and serve any content type. • While business logic is often implemented as enterprise beans, it may also be implemented entirely within the Web tier.
Functions of Web-tier
• • • • • • Web-enabled business logic Generates dynamic content Presents data and collects input\ Controls screen flow Maintains state Supports multiple and future client types • May implement business logic
Web-Tier Technologies in the J2EE Platform
• Web-tier technologies in the J2EE platform provide the benefits of server-side scripting, using compiled Java classes in a standardized, secure, and vendor-neutral environment. • A Web application is a collection of Web-tier components, content, and configuration information, which operates as a single functional unit. • The runtime support environment for a Web application is called a Web container. • The platform specification defines a contract between the Web container and each Web component, defining the component’s lifecycle, the behavior the component must implement, and the services that the server must provide to the component. • The platform specification also defines two types of Web component technologies: Java Servlets (“servlets”) and JavaServer PagesTM (JSPTM pages) technology.
• A servlet is a Java class that extends a J2EE server, producing dynamic content in response to requests from the server. The server passes service requests to the servlet through the standard interface javax.servlet, which every servlet must implement. • A JSP page is an HTML page with special markup that provides customizable behavior for generating dynamic content at runtime. A JSP page is usually translated into a servlet when it is deployed. JSP technology provides a document-centric, rather than programmatic, way to specify dynamic content generation.
The Web Container
• A J2EE Web application runs inside a J2EE server’s Web container. The container manages each component’s lifecycle, dispatches service requests to application components, and provides standard interfaces to context data such as session state and information about the current request. • The Web container provides a consistent interface to the components it hosts, so Web components are portable across application servers. And, because packaging and deployment of J2EE Web applications are standardized, a Web application can be deployed into any J2EE server without recompiling the code or rebuilding the application archive.
• A Java Servlet is a Java class that extends a J2EE-compatible Web server. Each servlet class produces dynamic content in response to service requests to one or more URLs. • Servlets are compiled Java classes, so they are generally faster than CGI programs or server-side scripts. In addition to producing content, servlets have several features that support application structure. A developer can create classes that respond to events in a servlet’s lifecycle by implementing listener interfaces. • A servlet can also be extended by one or more servlet filters, which are reusable classes that wrap calls to a servlet’s service method, transforming the request or the response. Servlet filters can be organized into filter chains that perform successive transformations on servlet requests or responses. • Distributed servlets are more scalable than non-distributed servlets. The Web • container can provide an application with load balancing and failover by migrating • user sessions among cluster nodes. • Distributed servlets are marked distributable in the Web application deployment descriptor.
Web-Tier Technology Guidelines
Servlets are most effectively used for implementing logic and generating binary content. Use Servlets to Implement Services
Use Servlets as Controllers
Use Servlets to Generate Binary Content Avoid Writing Servlets That Print Mostly Static Texts Use Request, Dispatcher Methods forward and include Correctly.
Servlet’s Life Cycle
Request Object: • Encapsulates all information from the client. • Provides access to request headers • InputStream or Reader containing data from the client. • CGI Like information • form data and query parameters • server specific parameters such as SSL information Response Object: • Encapsulates all communication back to the client • Provides access to response headers • OutputStream to write data to the client • setting cookies • Convenience method for sending redirects, error pages, etc.
A Simple Servlet
Compiling & Deploying Servlet
• Add servlet.jar file to the classpath.
– Apache Tomcat 4.0 Servlet.jar is available in tomcat’s common\lib directory. – Weblogic 7.0 beta weblogic.jar has the servlet APIs. bea\weblogic700b\server\lib – J2EE Reference implementation
• J2ee.jar (j2sdkee1.3.1\lib) has the servlet APIs.
java <servletclassname> Place the .class file
If it is Tomcat Apache
• Create an application directory for the application and create a directory called WEB-INF under that. Under WEB-INF create a directory called classes and place the servlet class in the classes folder. Create a web.xml and copy it in WEB-INF directory of your application. You can change the context path for your application in server.xml under the conf directory of the Tomcat Home. Start the Tomcat server and open the browser and give the URL.
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/webapp_2_3.dtd"> <web-app> <servlet> <servlet-name>Example</servlet-name> <servlet-class> ExampleServlet </servlet-class> </servlet> </web-app>
Context path in server.xml
<Context debug="0" docBase = "c:\hemaexamples" path="/MyServlets" privileged="true"/> From the browser open the resource: http://localhost:8080/MyServlets/servlet/Ex ample
Deploying servlets in Weblogic
• Create your application directory with WEBINF\classes under it. • Create the web.xml file as created for Apache and save it in WEB-INF directory • Under mydomains directory, edit the config.xml file to make an entry of your application. <Application Deployed="true" Name=“Example" Path="c:\" TwoPhase="false"> <WebAppComponent Name=“Example" Targets="myserver" URI=“hemaexamples"/> </Application> Open the browser and type the url: http://localhost:7001/Example/Example
HttpServlet (abstract class)
doGet(HttpServletRequest,HttpServletResponse) doPost(HttpServletRequest,HttpServletResponse) doHead(HttpServletRequest,HttpServletResponse) doPut(HttpServletRequest,HttpServletResponse) doOptions((HttpServletRequest,HttpServletResponse) doTrace((HttpServletRequest,HttpServletResponse) All the above methods throw the following exceptions: ServletException IOException
• • • • • • • • • • • • • • • • String getParameter(String) int getContentLength() HttpSession getSession(boolean) String getRemoteAddr() int getServerPort() String getProtocol() Enumeration getParameterNames() Map getParameterMap() String getParameterValues() String getRemoteHost() String getServerName() String getHeader(String) Enumeration getHeaderNames() String getQueryString() String getMethod() StringBuffer getRequestURL()
• • • • • • • addHeader(String ,String) String encodeURL(String) setContentType(String) setContentLength(int) PrintWriter getWriter() int getBufferSize() ServletOutputStream getOutputStream()
• To maintain the state of the client information, session tracking is used. The three common methods of session tracking are: • Hidden fields • URL rewriting • Cookies You can pass the values as hidden fields to a form and get the value back along with other fields which will help to identify the client. The encodeURL method of HttpServletResponse is used for URL rewriting which takes the URL as the string and includes the sessionid in it. This will not be utilised if the client’s browser supports cookies. addCookie() method takes a Cookie object as an argument. The identification values can be passed between the client and the server as cookies.
Session Tracking code
• To create a session
– HttpSession hs = request.getSession(true); The request object will return the HttpSession object if a session is already there. If a session is not there, it creates a new session and returns that object.
• To find out if the session is new:
boolean ns = hs.isNew();
• To add attributes to session
– hs.setAttribute(String name, Object value)
• To retrieve the value of an attribute
– hs.getAttribute(String name) returns an Object
• To get the creation time
– hs.getCreationTime() returns long
• To get the maximum inactive interval
– hs.getMaxInactiveInterval() returns a long
• To get the last accessed time
• This object is used to share information between servlets in an application. You can set some global attributes whose value can be shared. • You do this by getting the ServletContext object of each servlet and then set or get the global attributes.
• To get the ServletContext object
– ServletContext ss = getServletContext();
• To set an attribute
• To retrieve an attribute
Using Filters with Servlets
• The interfaces Filter, FilterChain and FilterConfig are new with Servlet 2.3 release. • Classes that implement these interfaces are used to either preprocess or postprocess servlets. • They can change the requests before a servlet is invoked or a response after a server generates it. • You can chain as many filters as you want together on either or both sides of the servlet you want to affect. • You can write filters with a specific functionality and reuse them with different servlets. • You will need to modify the web.xml to register the filters and to map where they are being used. • Filters can be used for authentication, logging and auditing, image conversion, data compression, encryption. Tokenizing , triggering resource access events, XSLT and MIME-type chains.
• The Filter interface has three methods:
– init(FilterConfig) – destroy() – doFilter(ServletRequest,ServletResponse,Filt erChain)
• Write a class that implements Filter interface and implement all the methods and give the logic in doFilter() method
Filter settings in web.xml
<web-app> <filter> <filter-name>PostFilter</filter-name> <filter-class> Greetings.PostFilter </filter-class> </filter> <filter-mapping> <servlet> <servlet-name>Hello</servlet-name> <servlet-class>Greetings.Hello1</servlet-class> </servlet> </filter-mapping> …. </web-app>
• With filtering, you have a single servlet working along with Java objects on the server. • With forwarding, your first servlet does some amount of processing on a request on to another servlet or resource. • You will use forwarding when you are using servlets as a controller and jsp as the view. • You cannot start generating the body of a servlet and forward it to another. • You can set or add headers, set status codes and attributes. • You forward the request using the RequestDispatcher object.
• request.setAttribute(name,value); • RequestDispatcher rds = request.getRequestDispatcher(“/servlet/Gr eetings.Hello5”); • rds.forward(request,response);
Including content from one resource in another
• You cannot use forward() to combine the body of response from two different servlets. To include the output of one resource in another, use include() of the RequestDispatcher. • Printwriter out = res.getWriter(); • req.setAttribute(name,value); • RequestDispatcher rds = req.getRequestDispatcher(“/servlet/Greetings/HelloInclu de”); • out.println(“<HTML>”); • out.println(“<BODY>”); • out.println(“<h1>”); • rds.include(request,response); • out.println(new Date()); • out.println(“</body> </html>”);