Servlet Programming
By Võ Văn Hải http://vovanhai.wordpress.com

Application Model Servlet Requests and Response  Servlets and Servlet Context  Session Tracking  Filter  Securing Web Application
 


Client – Server Model
Developing Web Applications An Overview

Advantages of Web Application
• Easier access to information • Lower maintenance and deployment costs • Platform independency

• Wider visibility




Architecture of Web Applications

Traditional n-Tier Architecture

Application Logic= Presentation logic + Business Logic (No physical demarcation between the two) Infrastructure services provide additional functionalities required by application, such as messaging services and transactional services.
5 6

Component n-tier Architecture
Interfaces Component A Component B Component C Database

Layered Architecture

Component A Component B

Application object broken into components that can communicate with each other, through interfaces

Component C



JDBC-ODBC Bridge, perhaps
7 8


 Personal Home Page (PHP).01/10/2010 Communication/ Protocols HTTP Protocol   Http Protocol   Request Message structures Hypertext Transfer Protocol (HTTP) is an application level protocol Enables Web servers and browsers to send and receive data HTTP Request – Client sends a request to the Web server using HTTP request methods:  GET – Enables to access static resources  POST – Enables to access dynamic resources  HEAD – Enables to view the headers of HTTP response HTTP Response – Web server sends response to the client after processing the request Response Message structures 9 10 Server Side Technologies Common Gateway Interface (CGI).  Server-side JavaScript (SSJS).  Java Servlet  Active Server Page (ASP)  Java Server Page (JSP).  Common Gateway Interface (CGI)   Written using Perl programming language Enables the Web server to send information to other files and Web browsers Enables to obtain information and use it on the server machine Helps to process the inputs to the form on the Web page   Disadvantages •Reduced efficiency •Reloading Perl interpreter 11 12 3 .

getWriter().init(config). } } public void init(ServletConfig config) throws ServletException { super.01/10/2010 Active Server Pages (ASP)  PHP Hypertext Preprocessor       Uses server side scripting architecture that is used to develop database driven Web applications Runs under Internet Information Services (IIS) Saved with a .Write(“ Welcome ”)%> </body> </html> Declares page language as JavaScript Displays Welcome message 13 Server side scripting language that provides tools for developing dynamic Web pages PHP is similar to JSP and ASP Enables to connect the Web forms to the database Requires a simple text editor to develop the code Provides security by executing the PHP code on the server Enables the use of PHP on operating systems. Mac. public class Example extends HttpServlet { public void doGet(HttpServletRequest request. and extensibility      <%@ LANGUAGE = ”JavaScript” %> <html> <body> <% Response.*. handling cookies. Provides an array of objects and components that provide benefits such as speed. String param = config. import javax.servlet.servlet.http. such as. Windows. and setting HTTP headers 15 HTML code in servlets 4 . HttpServletResponse response) throws ServletException. and Unix 14 Servlets      Example of Servlets import Java class import java.println(“ Example of Servlets”). import javax.*.getInitParameter(“param"). modularity.io. out. } 16 Enables the user to run Java code on the Web server Enables to develop Web pages and process inputs from the Web pages Enables to add dynamic content to Web pages A single servlet instance can process multiple requests Contains built-in functionality for reading HTML form data. IOException{ PrintWriter out = response.*. out. out.println(“</body></html>”).println(“<html><body>”). tracking user sessions. security.asp extension Provides programming tools with functionalities that enable the user to develop ASP applications faster Enables the user to develop Web applications using languages such as VB Script and JScript.

create template and standard HTML pages Promotion – Implies the stage at which re-engineering and redesigning of the Web site is done Site maintenance and updating – Implies the stage at which bug fixing and improvement of site is done 20 5 .util.xml <servlet> <description></description> <display-name>Display Servlet Name</display-name> <servlet-name>Servlet Name</servlet-name> <servlet-class>ServletClass</servlet-class> <init-param> <param-name>param</param-name> <param-value>Value of param</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>Servlet Name</servlet-name> <url-pattern>/url_pattern</url-pattern> </servlet-mapping> </servlet> 17 Java Server Pages (JSP)      JSP is a server-side technology based on servlets Contains static template data and JSP elements Enables to build cross-platform database driven Web applications The tag library in JSP simplifies the task of creating dynamic Web content Saved with a .01/10/2010 Web.Date() %> </body> </html> 18 Web Development Process  GenericServlet Class Includes six stages:       Planning – Implies the stage at which the user needs to gather requirements and define target audience Analysis – Implies the stage at which the user needs to evaluate the information and verify the correctness and consistency of information Design – Implies the stage at which the user needs to create sample layout and send the layout for approval Implementation – Implies the stage at which the user needs to establish the framework of site.jsp extension <html> <head> <title>Hello World</title> </head> <body> Today’s date is <%= new java.

Object value)  The ServletRequest Interface methods 23 24 6 . and client specific request parameters (entered data on web form) public String getParameter(String name) public Enumeration getParameterNames() public String[] getParameterValues() public Object getAttribute(String name) public int getContentLength() public ServletInputStream getInputStream() throws IOException public String getServerName() Public void setAttribute(String name. and type) and raw request (as headers and input stream). URL.01/10/2010 HTTPServlet Class Web Application Directory Structure 21 22 ServletRequest Interface  The ServletRequest Interface   Servlet Requests and Response         Provides access to specific information about the request Contains both actual request (as protocol.

01/10/2010 HttpServletRequest Interface  HttpServletRequest Interface   Reading Request Headers From Request  Extends ServletRequest Interface Add a few more methods for handling HTTP-specific request data getHeader()  getHeaders()  HttpServletRequest Interface methods      public public name) public public public Cookie[] getCookies() String getHeader(String  String getMethod() String getPathInfo() String getAuthType() getHeaderNames() 25 26 ServletResponse Interface  The ServletResponse Interface  HttpServletResponse interface  HttpServletResponse Interface    Create and manipulate a servlet’s output which is response to the client Retrieve an output stream to send data to the client... decide on the content type . Define objects passed as an argument to service() method   Extends ServletResponse Interface Define HttpServlet objects to pass as an argument to the service() method to the client  The ServletResponse Interface methods    HttpServletResponse Interface methods ◦ ◦ ◦ ◦ addCookie() addHeader() containsHeader() sendError()  public public public throws public String getContentType() PrintWriter getWriter() throws IOException ServletOutputStream getOutputStream() IOException void setContentType(String str) 27 28 7 .

01/10/2010 Sending Text & Binary data getOutputStream() Response Header   getWriter()   print(boolean b) println(char c) 29 30 Sending Header  Redirecting Requests  addHeader(): add a response header with a given name and value addDateHeader() addIntHeader() containsHeader() sendRedirect    encodeRedirectURL  31 32 8 .

01/10/2010 Generic Servlet Lyfe Cycle The life cycle is defined by: • init() – called only one by the server in the first request • service() – process the client’s request • destroy() – called after all requests have been processed or a server-specific number of seconds have passed 33 HTTP Request Processing Life Cycle 34 Initialising servlets  Need for initialising servlet context ◦ To pass parameters form client to servlets ◦ To setup communication Servlets and Servlet Context  Initialising servlets ◦ Container locate the servlet class ◦ Container load the servlet ◦ Create an instance of the servlet ◦ Invoke init() method to initialise the servlet. 35 36 9 .

setAttribute(). If the user clicks the Reload/Refresh button. which then redirects to JSP-3. 37 38 RequestDispatcher (2)  RequestDispatcher vs. you can pass data between them using request. and the only way to pass data is through the session or with web parameters (url?name=value). 1) If you use a RequestDispatcher.01/10/2010 RequestDispatcher (1)  forward(): used to forward request from one servlet to another servlet. If you use a RequestDispatcher to forward from Servlet-2 to JSP-3. Therefore. JSP page or a HTML file to a servlet. not Servlet-2. A reload/refresh will execute both Servlet-2 and JSP-3. it is a new request from the client. 39 40 10 . This can be important if Servlet-2 performs some system update (such as credit-card processing). the target servlet/JSP receives the same request/response objects as the original servlet/JSP. sendRedirect  include(): used to include the contents of another servlet. the user's address bar will read "http://[host]/JSP-3". the user's address bar will read "http://[host]/Servlet-2". With a redirect. Suppose you have JSP-1 which has a form that targets Servlet-2. 2) A sendRedirect() also updates the browser history. With a sendRedirect(). only JSP-3 will be re-executed.

html</location> </error-page> 43 44 11 .getRequestDispatcher ("/Billing"). response).forward (request.setStatus (int sc) 41 Logging Errors: public void log (String msg[. }else { dispatch. if(dispatch == null){ response. } web. Throwable t]) 42 Logging Error Error Handling in Servlets Servlet file RequestDispatcher dispatch = request.xml <error-page> <error-code>404</error-code> <location>/FileNotFound.sendError (404).01/10/2010 Error Handling in Servlets(1) Error Handling in Servlets Reporting Errors •public void sendError (int sc) throws IOException •public void HttpServletResponse.

semantics and synchronisation of communication • Stateless Protocol: not tracked • HTTP Protocol • Client – server Model • Request – response • Stateless Protocol The session tracking mechanism serves the purpose tracking the client identity and other state information required throughout the session 45 46 Session Tracking URL rewriting Hidden Form Fields 47 48 12 .01/10/2010 Session Tracking Protocol • Is a set of rules. which governs the syntax.

getCookies(). Cookie[]x= request. 49 50 Session tracking using HttpSession  Identifying Storing information in a session user in a multi-page request scenario and information about that user  Is used to created a session between the client and server  When users make a request.01/10/2010 Cookies  Is a small piece of information sent by the web server to the client to keep track of users.addCookie(cok).  Cookie has values in the form of key-value pairs  A web browser is expected to support 20 Cookies per host  Size of each cookie can be a maximum of 4 KB. } 51 52 13 . the server signs it a session object and a unique session ID  The session ID matches the user with the session object in subsequent requests  The session ID and the session object are passed along with the request to the server. cok. for(Cookie c:x) out.getSession(true). Cookies example //add cookie to response Cookie cok=new Cookie("username". //get & print all cookie PrintWriter out=response.println(c.setAttribute("name“.getWriter(). Session Timeout: HttpSession session=request."value").getName() +":"+c. "vovanhai").setComment("ghi chu thu choi"). if(session.getValue()+"<br/>"). response.isNew()){ session.

encrypting data and converting images 55 Working of Filters 56 14 . 53 54 Filters  Components that add functionality to the request and response processing of a Web Application  Intercept the requests and response that flow between a client and a Servlet/JSP. Object value=session.getAttribute("name"). comprising files.getSession(true).01/10/2010 Retrieving information in session Filter HttpSession session=request.  The Filter can  Authorize request  Request headers and modify data  Modify response headers and data  Authenticating the user.

Invoke a series of filters  A request or a response is passed through one filter to the next in the filter chain.xml) <web-app> …. So each request and response has to be serviced by each filter forming a filter chain  If the Calling filter is last filter. </web-app> 59 59 60 15 . will invoke web resource 57 58 Filter config example Configuring Filters  In Web Deployment Descriptor (web. <filter> <icon>icon file name</icon> <filter-name>Name of Filters</filter-name> <display-name>displayed name</display-name> <description>describe filter</description> <filter-class>implemented Filter Class</filter-class> <init-param> <param-name>parameter name</param-name> <param-value>value </param-value> </init-param> </filter> <filter-mapping> <filter-name>FilterName</filter-name> <url-pattern>/context</url-pattern> </filter-mapping> ….01/10/2010 Filter Example Filters Chain  There can be more than one filter between the user and the endpoint .

01/10/2010 FilterMapping elements    Configuring FilterChain <filter-name>: name of the filter <url-pattern>: pattern useed to resolve URLs to which filter applies. <servlet-name>: name of servlet whose request and response will be serviced by the filter 61 62 Modifying Character Encoding sample Securing Web Application 63 64 16 .

 Credentials are passed as plaintext and could be known easily  Encoded using base-64 characters  “username:password” 68 67 17 .  The server enforces security through the Web browser.  The Web browser displays a dialog box to accept the authentication information from the user.01/10/2010 Security Concepts Pillars of Security/Security Mechanism  Security Mechanism    Firewall Digital Signatures Password Authentication / Authorization HTTP basic authentication HTTP digest authentication HTTPS (Secured HTTP) client authentication Form-based authentication  Pillars of Security    Need of Securing Web Application        Is accessed over a network such as Internet / Intranet Access to confidential information by unauthorized users Unauthorized use of resources Heavy traffic Malicious Code 65 66 HTTP Basic Authentication HTTP Basic Authentication (cont)  Common method to authenticate users by verifying the user name and password  Users are authenticated before allowing them to access the protected resources. when the user tries to access a protected resource.

xml Sender – SSL Client Recipient – SSL server  Extra authentication layer in between Http and TCP  This layer confirms the client authentication  Two kinds of Certificated are used   Server Certificates Client Certificates 71 72 18 .01/10/2010 HTTP Digest Authentication  Use hash functions to secure web applications  Hash function convert data into a small / complex no. Input Fox Fox is running Hash Value DFC3478 583DNT89 HTTPS Client Authentication 69 69 70 HTTPS Client Authentication (cont)  Authentication of users by establishing a Secure Sockets Layer (SSL) connection between sender and recipient   Authentication & web.xml  Configuring Users in Tomcat  Entering the username and password to create the Tomcat users using View Admin Console in Tomcat  Reference %TOMCAT_HOME%\conf\tomcatusers.

Use base-64 encoding. but they are redirected to a login page when they try to access the secured pages of the Web site. can expose user name and password unless all connections are over SSL Does not specify the security realm 75 76 19 .01/10/2010 HTTP Basic Authentication demo HTTP Digest Authentication demo 73 74 Form-based Authentication Form-based Authentication (cont) A customized login page is created for a Web application. Web site users can browse the unprotected pages of the Web site.

) or INTEGRAL oINTEGRAL requires data must be guaranteed not to change in transit. oCONFIDENTIAL requires data must be guaranteed not to have bean read by an unauthorized thrid party in transit.xml (cont. 77 oA CONFIDENTIAL guarantee implies INTEGRAL.01/10/2010 web.xml Form-based Authentication with Tomcat User Run keytool to generate key-stroke: %JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSA Default password is changeit 79 80 20 .xml web. 78 Configure SSL in Tomcat Enable this XML fragment in Tomcat server.

 Advantages:  Gives scope to the programmer to ignore the constraints of the programming environment  Updating the mechanism does not require total change in Security model  It is easily maintainable  Limitation  Access is provided to all or denied  Access is provided by the Server only if the password matches  All the pages use same authentication mechanism  It can not use both form-based and basic authentication for different page 81 Programmatic Security Authenticates users and grant access to the users Servlet either authenticates the user or verify that the user has authenticates earlier Advantages   Ensue total portability Allowed password matching strategies Much harder to code and maintain Every resource must use the code Limitation   82 Any questions? 83 84 21 .01/10/2010 Declarative Security  Provides security to resource with the help of the server configuration  Works as a different layer from the web component which it works.

01/10/2010 That’s about all for today! Thank you all for your attention and patient! 22 .