Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Web应用开发:J2EE和Tomcat

Similar presentations


Presentation on theme: "Java Web应用开发:J2EE和Tomcat"— Presentation transcript:

1 Java Web应用开发:J2EE和Tomcat
蔡 剑, Ph.D.

2 本讲内容 Web层技术 (I) J2EE Web 层基本结构 Servlet 和 JSP 概念 Servlet 技术

3 J2EE Framework RDMS JSTL (X)HTML XML Applet JAF JMS JDBC JTA JNDI
Client Application JAF JMS JDBC JTA JNDI JSTL Servlets JSPs Web Container Session Beans Entity EJB Container J2EE Server RDMS Mail Server Java CORBA Directory Service Message Queue JavaMail RMI IIOP HTTP Message Application Client Container JAX RPC SAAJ JAXR JACC Mgmt JMX

4 Web Layer Structure Web Browser HTTP Connector Servlet JSP JSTL Static
Resources Application Deployment Descriptor Request Response Server Container

5 Servlet Advantages Convenient: HTTP, and Java Based
Efficient: Web Container manages the threads Standard and Cheap: Open source web servers available

6 JSP Advantages JSP is derived from Servlet
Simple and easy to use: Page-like format Portability: drag and drop Powerful: third-party functions added

7 Web Application File Structure
/webapps Web Server Installation Directory /bin /conf /common /urapp /WEB-INF /impages web.xml /classes /lib Command files to run and stop the server Server configuration files (including server.xml) server.xml Server configuration file Includes other components used by web server Jar files used by all applications Automatically loaded web applications and war files The directory of application you added Standard directory in a web application Web application deployment descriptor Servlet and other class files Other jar files used by this application Directory added by user /work /logs /endorsed Log and output files /temp Directory used by the JVM for temporary files (java.io.tmpdir) Jar files provided by other vendors Class files used by all applicaitons Temporary working directories for web applications

8 HTML Form Control Browser Table request Get/Post Web Container Action
response EJB Container Table Input Database

9 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"); ……

10 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(); }

11 Example Servlet Result

12 Servlet Deployment <?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC '-//Sun …' ' <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> <url-pattern>/simple</url-pattern> </servlet-mapping> </web-app>

13 Class and Configuration File Locations

14 Servlet Lifecycle Create Initialize Available for Service Destroy
Unavailable Servicing requests Unload Initialized succeed failed Requests from client exception Failure Back to normal

15 Servlet Process and Thread

16 Servlet APIs servlet基本类: 网络请求和响应: javax.servlet.Servlet
javax.servlet.SingleThreadModel javax.servlet.GenericServlet 网络请求和响应: javax.servlet.ServletRequest javax.servlet.ServletResponse javax.servlet.ServletInputStream javax.servlet.ServletOutStream javax.servlet.HttpServletRequest javax.servlet.HttpServletResponse

17 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

18 How to Remember APIs? Web Browser HTTP Connector Servlet JSP JSTL
Static Resources Application Deployment Descriptor Request Response Server Container

19 Four Major Features Process requests Generate responses
Handling sessions Work with other resources

20 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: Referer: Connection: Keep-Alive

21 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().

22 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();

23 HeaderServlet.java Result

24 RequestCounterServlet.java Result

25 Request Form

26 HTML Form to Get Input

27 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();

28 Formparameter.java Result

29 Send Response from Servlet

30 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"); case 4: out.println(" You should consier to become Certified Developer for the Java 2 Platform");

31 Display Response

32 Session Mechanisms 三种途径实现会话期间. cookie机制.
JSESSIONID=74D2DD5CA15A6090D33AF973B9C1D0D9) URL 重写. 隐藏表单输入. <INPUT type="hidden" name="session" value="12345">

33 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 );

34 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

35 CookieServlet.java Result

36 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>");

37 SessionRecorderServlet.java Result

38 Session Mangement

39 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();

40 Collaboration with Other Servlets
Web Browser HTTP Connector Servlet1 Application A Request Response Server Container HttpServletRequest Servlet2 Servlet3 Application B Servlet5 HttpServletResponse Servlet4 Include Forward Chaining

41 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, ...

42 Request Include


Download ppt "Java Web应用开发:J2EE和Tomcat"

Similar presentations


Ads by Google