Bài giảng Java 2 - Trần Duy Thanh - Servlet Programming

Application Model

Servlet Requests and Response

Servlets and Servlet Context

Session Tracking

Filter

Securing Web Application

 

 

pptx84 trang | Chuyên mục: Java | Chia sẻ: dkS00TYs | Ngày: 08/06/2015 | Lượt xem: 2395 | Lượt tải: 3download
Tóm tắt nội dung Bài giảng Java 2 - Trần Duy Thanh - Servlet Programming, để xem tài liệu hoàn chỉnh bạn click vào nút "TẢI VỀ" ở trên
ype ... Define objects passed as an argument to service() method The ServletResponse Interface methods public String getContentType() public PrintWriter getWriter() throws IOException public ServletOutputStream getOutputStream() throws IOException public void setContentType(String str) 27 HttpServletResponse interface HttpServletResponse Interface Extends ServletResponse Interface Define HttpServlet objects to pass as an argument to the service() method to the client	 HttpServletResponse Interface methods addCookie() addHeader() containsHeader() sendError() 28 Sending Text & Binary data getOutputStream() getWriter() print(boolean b) println(char c) 29 Response Header 30 Sending Header addHeader(): add a response header with a given name and value addDateHeader() addIntHeader() containsHeader() 31 Redirecting Requests sendRedirect encodeRedirectURL 32 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 Servlets and Servlet Context 35 Initialising servlets Need for initialising servlet context To pass parameters form client to servlets To setup communication Initialising servlets Container locate the servlet class Container load the servlet Create an instance of the servlet Invoke init() method to initialise the servlet. 36 37 RequestDispatcher (1) forward(): used to forward request from one servlet to another servlet. 38 RequestDispatcher (2) include(): used to include the contents of another servlet, JSP page or a HTML file to a servlet. 39 RequestDispatcher vs. sendRedirect 1) If you use a RequestDispatcher, the target servlet/JSP receives the same request/response objects as the original servlet/JSP. Therefore, you can pass data between them using request.setAttribute(). With a sendRedirect(), it is a new request from the client, and the only way to pass data is through the session or with web parameters (url?name=value).2) A sendRedirect() also updates the browser history. Suppose you have JSP-1 which has a form that targets Servlet-2, which then redirects to JSP-3. With a redirect, the user's address bar will read "http://[host]/JSP-3". If the user clicks the Reload/Refresh button, only JSP-3 will be re-executed, not Servlet-2.If you use a RequestDispatcher to forward from Servlet-2 to JSP-3, the user's address bar will read "http://[host]/Servlet-2". A reload/refresh will execute both Servlet-2 and JSP-3. This can be important if Servlet-2 performs some system update (such as credit-card processing). 40 Error Handling in Servlets(1) 41 Error Handling in Servlets Reporting Errors public void sendError (int sc) throws IOException public void HttpServletResponse.setStatus (int sc) Logging Errors: public void log (String msg[, Throwable t]) 42 Logging Error 43 Error Handling in Servlets Servlet file RequestDispatcher dispatch = 	request.getRequestDispatcher ("/Billing"); if(dispatch == null){ response.sendError (404); }else { dispatch.forward (request, response); } web.xml 404 /FileNotFound.html 44 Session Tracking 45 Session Tracking Protocol Is a set of rules, which governs the syntax, 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 46 URL rewriting 47 Hidden Form Fields 48 Cookies Is a small piece of information sent by the web server to the client to keep track of users. 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. 49 Cookies example //add cookie to response Cookie cok=new Cookie("username", "vovanhai"); cok.setComment("ghi chu thu choi"); response.addCookie(cok); //get & print all cookie PrintWriter out=response.getWriter(); Cookie[]x= request.getCookies(); for(Cookie c:x) 	out.println(c.getName()	+":"+c.getValue()+""); 50 Session tracking using HttpSession Identifying 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, 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. Session Timeout: 51 Storing information in a session HttpSession session=request.getSession(true); if(session.isNew()){ session.setAttribute("name“,"value"); } 52 Retrieving information in session HttpSession session=request.getSession(true); Object value=session.getAttribute("name"); 53 Filter 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. The Filter can Authorize request Request headers and modify data Modify response headers and data Authenticating the user, comprising files, encrypting data and converting images 55 Working of Filters 56 Filter Example 57 Filters Chain There can be more than one filter between the user and the endpoint - Invoke a series of filters A request or a response is passed through one filter to the next in the filter chain. So each request and response has to be serviced by each filter forming a filter chain If the Calling filter is last filter, will invoke web resource 58 Configuring Filters 59 In Web Deployment Descriptor (web.xml) …. 	 icon file name Name of Filters 	 displayed name 	 describe filter implemented Filter Class 	 	parameter name 	 value 	 FilterName /context …. 59 Filter config example 60 FilterMapping elements : name of the filter : pattern useed to resolve URLs to which filter applies. : name of servlet whose request and response will be serviced by the filter 61 Configuring FilterChain 62 Modifying Character Encoding sample 63 Securing Web Application 64 Security Concepts 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 Pillars of Security/Security Mechanism Security Mechanism Firewall Digital Signatures Password Authentication / Authorization Pillars of Security HTTP basic authentication HTTP digest authentication HTTPS (Secured HTTP) client authentication Form-based authentication 66 HTTP Basic Authentication 67 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. The server enforces security through the Web browser. The Web browser displays a dialog box to accept the authentication information from the user, when the user tries to access a protected resource. Credentials are passed as plaintext and could be known easily Encoded using base-64 characters “username:password” 68 HTTP Digest Authentication 69 Use hash functions to secure web applications Hash function convert data into a small / complex no. Input Hash Value Fox DFC3478 Fox is running 583DNT89 69 HTTPS Client Authentication 70 HTTPS Client Authentication (cont) Authentication of users by establishing a Secure Sockets Layer (SSL) connection between sender and recipient 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 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\tomcat-users.xml 72 73 HTTP Basic Authentication demo 74 HTTP Digest Authentication demo Form-based Authentication 75 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, but they are redirected to a login page when they try to access the secured pages of the Web site. Use base-64 encoding, can expose user name and password unless all connections are over SSL Does not specify the security realm 76 web.xml 77 web.xml (cont.) 78 INTEGRAL requires data must be guaranteed not to change in transit. CONFIDENTIAL requires data must be guaranteed not to have bean read by an unauthorized thrid party in transit. A CONFIDENTIAL guarantee implies INTEGRAL. or INTEGRAL Configure SSL in Tomcat 79 Enable this XML fragment in Tomcat server.xml Run keytool to generate key-stroke: %JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSA Default password is changeit Form-based Authentication with Tomcat User 80 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. 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 Limitation Much harder to code and maintain Every resource must use the code 82 83 84 Any questions? That’s about all for today! Thank you all for your attention and patient! 

File đính kèm:

  • pptx5. JavaServlet.pptx
Tài liệu liên quan