蔡 剑
This presentation is the property of its rightful owner.
Sponsored Links
1 / 42

Java Web应用开发:J2EE和Tomcat PowerPoint PPT Presentation


  • 40 Views
  • Uploaded on
  • Presentation posted in: General

蔡 剑 , 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.

Download Presentation

Java Web应用开发:J2EE和Tomcat

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Java web j2ee tomcat

蔡 剑, Ph.D.

Java Web应用开发:J2EE和Tomcat


Java web j2ee tomcat

本讲内容

  • Web层技术 (I)

    • J2EE Web 层基本结构

    • Servlet 和 JSP 概念

    • Servlet 技术


J2ee framework

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 layer structure

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

Servlet Advantages

  • Convenient: HTTP, and Java Based

  • Efficient: Web Container manages the threads

  • Standard and Cheap: Open source web servers available


Jsp advantages

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 application file structure

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

HTML Form Control

Browser

Table

request

Web Container

Get/Post

Action

Form

response

EJB Container

Table

Input

Database


A simple servlet

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

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

}


Example servlet result

Example Servlet Result


Servlet deployment

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>


Class and configuration file locations

Class and Configuration File Locations


Servlet lifecycle

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 process and thread

Servlet Process and Thread


Servlet apis

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 apis1

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


How to remember apis

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

Four Major Features

  • Process requests

  • Generate responses

  • Handling sessions

  • Work with other resources


Request line process

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

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

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

}


Headerservlet java result

HeaderServlet.java Result


Requestcounterservlet java result

RequestCounterServlet.java Result


Request form

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


Html form to get input

HTML Form to Get Input


An example for processing requests1

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

}


Formparameter java result

Formparameter.java Result


Send response from servlet

Send Response from Servlet


Responsewatcherservlet

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;


Display response

Display Response


Session mechanisms

Session Mechanisms

三种途径实现会话期间.

  • cookie机制.

    JSESSIONID=74D2DD5CA15A6090D33AF973B9C1D0D9)

  • URL 重写.

    http://localhost:8080/icsample/bookcookie;jsessionid=XXXXXX.

  • 隐藏表单输入.

    <INPUT type="hidden" name="session" value="12345">


Handle cookie

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

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


Cookieservlet java result

CookieServlet.java Result


Handle http session

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


Sessionrecorderservlet java result

SessionRecorderServlet.java Result


Session mangement

Session Mangement


Manage httpsession lifecycle

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


Collaboration with other servlets

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

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,

...

}


Request include

Request Include


  • Login