420 likes | 535 Views
蔡 剑 , Ph.D. Java Web应用开发:J2EE和Tomcat. 本讲内容. Web 层技术 ( I) J2EE Web 层基本结构 Servlet 和 JSP 概念 Servlet 技术. RDMS. JDBC. Web Container. JSPs. ( X)HTML XML. Servlets. HTTP. JSTL. JavaMail. Mail Server. J2EE Application Server. JAX RPC. Mgmt. Java Application. RMI. JAXR.
E N D
蔡 剑, Ph.D. Java Web应用开发:J2EE和Tomcat
本讲内容 • Web层技术 (I) • J2EE Web 层基本结构 • Servlet 和 JSP 概念 • Servlet 技术
RDMS JDBC Web Container JSPs (X)HTML XML Servlets HTTP JSTL JavaMail Mail Server J2EE Application Server JAX RPC Mgmt Java Application RMI JAXR JACC JNDI JDBC JMS JAF JTA Applet SAAJ JMX CORBA Server IIOP EJB Container Application Client Container Message Beans Session Beans Entity Beans Client Application Directory Service JNDI JAX RPC Mgmt JMS JAX RPC Mgmt Message Queue JAXR JACC JNDI JDBC JMS JAF JTA JAXR JMS SAAJ JMX SAAJ JMX J2EE Framework
Web Application Servlet HTTP Request Web Browser HTTP Connector JSP JSTL HTTP Response Deployment Descriptor Static Resources Web Server Container Web Layer Structure
Servlet Advantages • Convenient: HTTP, and Java Based • Efficient: Web Container manages the threads • Standard and Cheap: Open source web servers available
JSP Advantages • JSP is derived from Servlet • Simple and easy to use: Page-like format • Portability: drag and drop • Powerful: third-party functions added
Web Server Installation Directory /bin Command files to run and stop the server /common Includes other components used by web server Class files used by all applicaitons /classes /endorsed Jar files provided by other vendors Jar files used by all applications /lib /conf Server configuration files (including server.xml) server.xml Server configuration file /logs Log and output files /temp Directory used by the JVM for temporary files (java.io.tmpdir) /webapps Automatically loaded web applications and war files /urapp The directory of application you added Standard directory in a web application /WEB-INF web.xml Web application deployment descriptor /classes Servlet and other class files /lib Other jar files used by this application Directory added by user /impages /work Temporary working directories for web applications Web Application File Structure
HTML Form Control Browser Table request Web Container Get/Post Action Form response EJB Container Table Input Database
A Simple Servlet import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class SimpleServlet extends HttpServlet { public void init() throws ServletException { } public void doGet ( HttpServletRequest req, HttpServletResponse resp ) throws ServletException,IOException { PrintWriter out = resp.getWriter(); resp.setContentType("text/html"); ……
A Simple Servlet (cont’d) out.println(" <HTML> "); out.println(" <HEAD>"); out.println(" <TITLE> Simple Servlet </TITLE> "); out.println(" </HEAD> "); out.println(" <BODY BGCOLOR=white> "); out.println(" <CENTER> "); out.println(" <FONT COLOR=BLACK SIZE='5'> "); out.println(" <STRONG> I know servlet!</STRONG> "); out.println(" </FONT> "); out.println(" </CENTER> "); out.println(" </BODY> "); out.println(" </HTML> " ); out.flush(); }
Servlet Deployment <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC '-//Sun …' 'http://java.sun.com/j2ee/dtds/web-app_2.3.dtd'> <web-app> <display-name>IcSamples</display-name> <description>……</description> <servlet> <servlet-name>SimpleServlet</servlet-name> <display-name>SimpleServlet</display-name> <description>chap 4.2 example</description> <servlet-class>jwadbook.servlets.SimpleServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>SimpleServlet</servlet-name> <url-pattern>/simple</url-pattern> </servlet-mapping> </web-app>
Create Initialize Initialize failed Initialized succeed Failure Available for Service Unavailable for Service Unload Back to normal Destroy Servicing requests Unavailable exception Requests from client Servlet Lifecycle
Servlet APIs servlet基本类: javax.servlet.Servlet javax.servlet.http.HttpServlet javax.servlet.SingleThreadModel javax.servlet.GenericServlet 网络请求和响应: javax.servlet.ServletRequest javax.servlet.ServletResponse javax.servlet.ServletInputStream javax.servlet.ServletOutStream javax.servlet.HttpServletRequest javax.servlet.HttpServletResponse
Servlet APIs 和网络容器联系: javax.servlet.ServletConfig 和网络程序联系: javax.servlet.ServletContext 和其他网络资源的共同作用: javax.servlet.http.RequestDispatcher 错误异常类: javax.servlet.ServletException javax.servlet.UnavailableException 其他附属类: javax.servlet.http.HttpUtils javax.servlet.http.Cookie
Web Application Servlet HTTP Request Web Browser HTTP Connector JSP JSTL HTTP Response Deployment Descriptor Static Resources Web Server Container How to Remember APIs?
Four Major Features • Process requests • Generate responses • Handling sessions • Work with other resources
Request Line Process GET/icwork/?search=product HTTP/1.1 Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */* Accept-Language: en-us Accept-Encoding: gzip, deflate User-Agent: Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0; DigExt) Host: www.icconcept.com:8080 Referer: http://www.yoursite.com/header.html Connection: Keep-Alive
Major Methods for Processing Requests • ServletRequest,HttpServletRequest defines HTTP Header processing methods. • For reading request line: • getMethod(), getRequestURI(), getProtocol(); • 2) For reading header and its value:getHeaderNames(), getHeaders(), getHeader(), getDataHeader(), getIntHeader(); • 3) For reading particular header and its related valuses: • getCookies(), getAuthType(), getRemoteUser(), getRemoteAddr(), getRemoteHost(), getContentType(), getContentLenth(), getServerPort().
An Example for Processing Requests public void doPost (…){… out.println("<B>Method: </B>" + req.getMethod() + "<BR>"); out.println("<B>URI: </B>" + req.getRequestURI() + "<BR>"); out.println("<B>Protocol: </B>" + req.getProtocol() + "<BR>"); … Enumeration headerNames = req.getHeaderNames(); while(headerNames.hasMoreElements()) { String headerName = (String)headerNames.nextElement(); out.println("<TR><TD>" + headerName + "</TD>"); out.println(" <TD>" + req.getHeader(headerName)+"</TD>"); } out.println("</TABLE>"); out.println("</BODY></HTML>"); out.flush(); }
Request Form http://localhost:8080/icwork/control/createproject?proj_ID=null&proj_name=Project1&group=Web+Software+Group&lead=Zhang+San&desc=This+project+developes+an+advanced+web-based+task+monitoring+application+for+Icconcept+Inc.&actiontype=CREATE_PROJECT&submit.x=63&submit.y=8
An Example for Processing Requests Enumeration params = req.getParameterNames(); PrintWriter out = resp.getWriter(); while( params.hasMoreElements() ) { String nextparam = (String)params.nextElement(); String[] paramarray = req.getParameterValues(nextparam); out.println("<TR> <TD> " + nextparam + " </TD> <TD> <FONT> " + value + " </FONT></TD></TR>" ); } out.println ( "</TABLE> "); out.println("</CENTER>"); out.println(" <HR> "); out.println(" </BODY> "); out.println(" </HTML> " ); out.flush(); }
ResponseWatcherServlet int sel = Integer.valueOf(req.getParameter("selevel")).intValue() ; int eel = Integer.valueOf(req.getParameter("eelevel")).intValue() ; out.println(" <H3> "); switch (sel+eel) { case 6: out.println(" You should consier to become Certified Enterprise Architect for J2EE Technology"); break; case 5: out.println(" You should consier to become Certified Web Component Developer for the J2EE Platform"); break; case 4: out.println(" You should consier to become Certified Developer for the Java 2 Platform"); break;
Session Mechanisms 三种途径实现会话期间. • cookie机制. JSESSIONID=74D2DD5CA15A6090D33AF973B9C1D0D9) • URL 重写. http://localhost:8080/icsample/bookcookie;jsessionid=XXXXXX. • 隐藏表单输入. <INPUT type="hidden" name="session" value="12345">
Handle Cookie Cookie[] cookielist = req.getCookies(); Cookie category = new Cookie("Your_Favorite_Category" , "1_Computer_Book_2_Management_Book_3_Cooking_Book_4_Classical_Music" ); Cookie lastorder = new Cookie("Your_Last_Order" , "Java_Web_Application_Design_J2EE__Rich_Dad_Poor_Dad" ); category.setComment("Store your favorite book list"); category.setMaxAge(ageinsecond); //set the life time of the cookie category.setPath("/icsamples"); category.setVersion(1); //category.setSecure(true); resp.addCookie( category ); resp.addCookie( lastorder );
Request with Cookie Information GET /icsamples/bookcookie HTTP/1.1 Accept: */* Accept-Language: en-us Accept-Encoding: gzip, deflate User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; DigExt) Host: localhost:8070 Connection: Keep-Alive Cookie: Your_Last_Order=Java_Web_Application_Design_J2EE__Rich_Dad_Poor_Dad; Your_Favorite_Category=1_Computer_Book_2_Management_Book_3_Cooking_Book_4_Classical_Music
Handle HTTP Session HttpSession cusession = req.getSession(true); //set attributes cusession.setAttribute("Last_Access_Time", time); cusession.setAttribute("Protocol", req.getProtocol()); cusession.setMaxInactiveInterval(3600*24); if(cusession.getAttribute("Access_Recorder")!=null) { …… out.println("Session Creation Time: " + String.valueOf(cusession.getCreationTime())+ "<BR>"); out.println("Session Last Access Time: " + String.valueOf( cusession.getLastAccessedTime())+ "<BR>");
Manage HttpSession Lifecycle Session is handled by Web container and Servlet Three situations to stop a session: • Close Web Browser • MaxInactiveInterval reached cusession.setMaxInactiveInterval(3600*24); • Call invalidate method HttpSession cusession= req.getSession(); cusession.invalidate();
HttpServletRequest Servlet1 Servlet2 Chaining HTTP Request Forward Web Browser HTTP Connector Web Application A Servlet3 HTTP Response HttpServletResponse Servlet4 Include Web Application B Servlet5 Web Server Container Collaboration with Other Servlets
Request Forward and Include public class Servlet1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { RequestDispatcher dispatcher = getServletContext().getContext("/webapp2"). getRequestDispatcher("/servlet4"); if (dispatcher != null) dispatcher.forward(request, response); …… // dispatcher.include(request, response); } public void doPost(HttpServletRequest request, ... }