1. Trang chủ
  2. » Giáo án - Bài giảng

Servlet Programming

26 57 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Nội dung

14/07/2009 1 Servlet Programming 1 By VõVăn Hải Http://www.vovanhai.wordpress.com Developing Web Applications An Overview 2 Client – Server Model Advantages of Web Application • Easier access to information • Lower maintenance and deployment costs • Platform independency • Wider visibility 3 14/07/2009 2 Architecture of Web Applications 4 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 Component n-tier Architecture Component A Component B Component C Database Interfaces Application object broken into components that can communicate with each other, through interfaces 6 14/07/2009 3 Layered Architecture Component A Component B Component C Database M I D D L E W A R E JDBC-ODBC Bridge, perhaps 7 Communication/ Protocols Http Protocol Request Message structures Response Message structures 8 HTTP Protocol  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 9 14/07/2009 4 Server Side Technologies  Common Gateway Interface (CGI).  Server-side JavaScript (SSJS).  Personal Home Page (PHP).  Java Servlet  Active Server Page (ASP)  Java Server Page (JSP). 10 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 Active Server Pages (ASP)  Uses server side scripting architecture that is used to develop database driven Web applications  Runs under Internet Information Services (IIS)  Saved with a .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.  Provides an array of objects and components that provide benefits such as speed, security, modularity, and extensibility <%@ LANGUAGE = ”JavaScript” %> <html> <body> <% Response.Write(“ Welcome ”)%> </body> </html> Declares page language as JavaScript Displays Welcome message 12 14/07/2009 5 PHP Hypertext Preprocessor  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, such as, Windows, Mac, and Unix 13 Servlets  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, handling cookies, tracking user sessions, and setting HTTP headers 14 Example of Servlets import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Example extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println(“<html><body>”); out.println(“ Example of Servlets”); out.println(“</body></html>”); } } import Java class HTML code in servlets 15 14/07/2009 6 Web.xml <servlet> <description></description> <display-name>Display Servlet Name</display-name> <servlet-name>Servlet Name</servlet-name> <servlet-class>ServletClass</servlet-class> </servlet> <servlet-mapping> <servlet-name>Servlet Name</servlet-name> <url-pattern>/url_pattern</url-pattern> </servlet-mapping> </servlet> 16 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 .jsp extension <html> <head> <title>Hello World</title> </head> <body> Today’s date is <%= new java.util.Date() %> </body> </html> 17 Web Development Process  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, create template and standard HTML pages  Promotion – Implies the stage at which re-engineering and re- designing of the Web site is done  Site maintenance and updating – Implies the stage at which bug fixing and improvement of site is done 14/07/2009 7 GenericServlet Class 19 HTTPServlet Class 20 Web Application Directory Structure 21 14/07/2009 8 Servlet Requests and Response 22 ServletRequest Interface  TheServletRequest Interface  Provides access tospecific information about the request  Contains both actual request (as protocol, URL, and type) and raw request (as headers and input stream), and client specific request parameters (entered data on web form)  TheServletRequest Interface methods  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() 23 HttpServletRequest Interface  HttpServletRequest Interface  Extends ServletRequest Interface  Add a few more methods for handling HTTP-specific request data  HttpServletRequest Interface methods  public Cookie[] getCookies()  public String getHeader(String name)  public String getMethod()  public String getPathInfo()  public String getAuthType() 24 14/07/2009 9 Reading Request Headers From Request  getHeader()  getHeaders()  getHeaderNames() 25 ServletResponse Interface  TheServletResponse 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  TheServletResponse Interface methods  public String getContentType()  public PrintWriter getWriter() throws IOException  public ServletOutputStream getOutputStream() throws IOException  public void setContentType(String str) 26 HttpServletResponse interface  HttpServletResponseInterface  Extends ServletResponse Interface  Define HttpServlet objects to pass as an argument to the service() method to the client  HttpServletResponseInterface methods ◦ addCookie() ◦ addHeader() ◦ containsHeader() ◦ sendError() 27 14/07/2009 10 Sending Text & Binary data  getOutputStream()  getWriter()  print(boolean b)  println(char c) 28 Response Header 29 Sending Header  addHeader(): add a response header with a given name and value  addDateHeader()  addIntHeader()  containsHeader() 30 [...]... 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 35 36 12 14/07/2009 RequestDispatcher (1)  forward(): used to forward request from one servlet to another servlet 37 RequestDispatcher (2)  include():... important if Servlet- 2 performs some system update (such as credit-card processing) 39 13 14/07/2009 Error Handling in Servlets(1) 40 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]) 41 Logging Error 42 14 14/07/2009 Error Handling in Servlets Servlet. .. 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... 31 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 32 HTTP Request Processing Life Cycle 33 11 14/07/2009 Servlets and Servlet Context 34 Initialising servlets  Need for initialising servlet. .. servlet to another servlet 37 RequestDispatcher (2)  include(): used to include the contents of another servlet, JSP page or a HTML file to a servlet 38 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(),... … 57 57 19 14/07/2009 Filter config example 58 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   59 Configuring FilterChain 60 20 14/07/2009 Sample Filter 61 Securing Web Application 62 Security Concepts  Need of SecuringWeb... value=session.getAttribute("name"); 52 Filter 53 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 mod ify data  Modify response headers and data  Authenticating the user, comprising files, encrypting data and converting images... 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... same authentication mechanism  It can not use both form-based and basic authentication for different page  75 25 14/07/2009 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 . Name< /servlet- name> < ;servlet- class>ServletClass< /servlet- class> < /servlet& gt; < ;servlet- mapping> < ;servlet- name> ;Servlet Name< /servlet- name> <url-pattern>/url_pattern</url-pattern> < /servlet- mapping> < /servlet& gt; 16 Java. servlets 15 14/07/2009 6 Web.xml < ;servlet& gt; <description></description> <display-name>Display Servlet Name</display-name> < ;servlet- name> ;Servlet Name< /servlet- name> < ;servlet- class>ServletClass< /servlet- class> < /servlet& gt; < ;servlet- mapping> < ;servlet- name> ;Servlet. 14 Example of Servlets import java.io.*; import javax .servlet. *; import javax .servlet. http.*; public class Example extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse

Ngày đăng: 13/05/2014, 11:01

w