Overview of Servlet components JavaWeb

This article will introduce Servlet component with her workflow, lifecycle, Request / Response core object.

First with his white words say that his understanding of the Servlet, Servlet is present in the components of the Web server that can handle user requests sent to the server in their browser and then processes the request to return the results of data required by the user, from a database query the data to be displayed on the page, but this type of dynamic data display pages called jsp page, Servlet used in conjunction with jsp page to meet all the needs of the user.

The figure is the flow of client and server interaction:
Here Insert Picture Description
Here Insert Picture Description
three ways to create ways of Servlet

  1. Create a class that implements the Servlet interface
  2. Create a class, inherited HttpServlet class
  3. Using the IDE directly create servlet, servlet and register

servlet two types of registration

  1. In the project version 3.0+ you can use @WebServlet ( "/ ×××") registered notes
  2. You can configure <servlet> in web.xml version 3.0 registered in the project
    Here Insert Picture Description
    Here Insert Picture Description

servlet life cycle

  • Examples of the initialization operation Servlet- - Service - Returns Results - Destruction - recovery
    Here Insert Picture Description
  1. Examples of the servlet (Example servlet single mode)
    where a: the first request Servlet, for example operation
    case 2: server startup, operation instantiated

Servlet configuration file is added to the web.xml <load-on-startup>be provided servlet instance of priority, the higher priority the smaller the value, of the form:

<servlet>
	<servlet-name>LifeServlet</servlet-name>
    <servlet-class>cn.hp.servlet.LifeServlet</servlet-class>
    <init-param>
    	<param-name>password</param-name>
    	<param-value>123</param-value>
    </init-param>
    <load-on-startup>10</load-on-startup>
</servlet>
  1. servlet initialization
    initializing operation immediately instantiated, executed only once, automatically calls the init () method

  2. servlet processing request
    automatic callback service method, two objects pass HttpServletRequest and HttpServletRespose, service () method takes a user request, in response to the processing result of
    the way a: override service ()
    Second way: override doGet () / doPost () method

  3. servlet destroy
    automatic callback destroy () method, Servlet automatically release resources currently occupied by the current application is terminated, is removed from the server, the server stops triggered destroy ()

The core interface Servlet

1. HTTPServletRequest

Request object encapsulates all the data request packet is generally used to obtain the data coming from the client. Life cycle of a request, if the request is forwarded also identified as a request because the request is forwarded with the response object passed to another servlet to handle.

Data acquisition request Method:

  • String value = request.getParameter(String key);
  • String[] value = request.getParameterValues(String key);
  • Map<String,String[]> map = request.getParameterMap();

Common methods:

method effect
Cookie[] getCookies() All Cookie requested object and returns an array of cookie
HttpSession getSession() Returns the current session associated with the session request
String getContextPath() Back Request URI portion indicates the requested context
String getMethod() Returns the requested HTTP method, get or post method
String getQueryString() Returns the query string in the request URL path
String getRemoteAddr() Return the IP address of the client sends a request

Forwards the request:

  1. Gets forward the request object
    RequestDispatcher rd = getRequestDispathcher(String path);
  2. Call forwarding method
    rd.forward(HttpServletRequest,HttpServletResponse);

Or directlyrequest.getRequestDispatcher("path").forward(request, response);

2. HttpServletResponse

response object for a content package in response to the results of the data packet can be encapsulated cookie object, set of response codes, adding the response header, in response thereof; pure for servlet development without jsp pages, then, response may output and splicing pages, jsp bottom is can redirect, hereinafter will be described the difference between processes and forwards the request redirection; splicing the servlet page.

Common methods:

method effect
void addCookie(Cookie cookie) Adds the specified cookie to the response
void setStatus(int statu) For setting the status code in response to
void setHeader(String name, String value) Setting a response header with a given name and value
void addHeader(String name, String value) Add a response header with a given name and value
void sendRedirect(String location) Redirect URL specified location sends the temporary redirect response to the client
printWriter getWriter() Get the character data output stream
ServletOutputStream getOutputStream() Obtaining an output stream of data bytes

Redirect the request:
in general use response.sendRedirect("新的Servlet地址");, is not the same redirection and forwarding, the request is forwarded to the servlet response both to the other object to the processing, the client does not change the url; redirected by definition, given a re-direction to allow client access, the circumstances of any parameters passed with the request in the set does not exist, the client accesses the server several times, url will change; with the following chart to illustrate:
Here Insert Picture Description
Here Insert Picture Description

3. HttpSession

Scope session is a session object, it can be understood as the user from opening a browser to access a server start, close the browser to end a session may include multiple requests, the session can set the parameters within the scope of the session for a user use, scope larger than the request object; in practice, can record data user login session, for example, a user is not logged wanted to visit the main page, in a servlet can determine session information, so the user is redirected to the login page.

Common methods:

method effect
public Object getAttribute(String name) Returns the object with the specified name in the session the session, did not return null
public void setAttribute(String name, Object value) This method uses the specified name to bind an object to the session session
public boolean isNew() The session is to determine whether the new

The following is a successful login to the main page to log in again failed small case:

//该方法属于登录servlet类
protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	request.setCharacterEncoding("utf-8");
	HttpSession session = request.getSession();
	Map<String, String[]> map = request.getParameterMap();

	String userName = map.get("userName")[0];
	String password = map.get("password")[0];

	if (dao.login(userName, password) < 0) {
		//登录失败
		request.getRequestDispatcher("/page/login.jsp").forward(request, response);
	} else {
		//登录成功
		session.setAttribute("userName", userName);
		response.sendRedirect("/DynamicWebProject_AnimalManager_v3/animals?type=list");
	}	
}
//该方法属于主页面的servlet类
protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	request.setCharacterEncoding("utf-8");
	HttpSession session = request.getSession();
	if (session.getAttribute("userName") == null) {
		response.sendRedirect("/DynamicWebProject_AnimalManager_v3/page/login.jsp");
	} else {
		//业务代码
	}
}

4. ServletContext

The current object is a web project environment object (context object), a context corresponding to a project web object may be understood to be a global object, starting from the server scope, project deployment begins, the project server shuts down or is removed, the object can store global variables, for example the number of visits a site.

Get ServletContext
ServletContext context = this.getServletContext() //this表示某个servlet实例;
ServletContext context = config.getServletContext();

Features

  1. Obtaining global initialization parameters web application
    String username = context.getInitParameter("username");
<context-param>
	<param-name>username</param-name>
    <param-value>zhangsan</param-value>
</context-param>
  1. Storing global data
    the getAttribute ()
    the setAttribute ()

  2. Gets the absolute path of any web application resources (deployment environment for the current project)
    String realPath = context.getRealPath("/");

5. ServletConfig

This object describes the current configuration information related to itself Servlet,

Obtain
ServletConfig config = this.getServletConfig();
String value = config.getInitParameter(String key);

Function
get re-initialized data in the current Servlet in web.xml:

<servlet>
	<init-param>
		<param-name>name</param-name>
		<param-value>zhangsan</param-value>
	</init-param>   
</servlet>

Get / Post request processing mode and garbled

  • Garbled data request:
    page coding: <meta charset="utf-8">
    GET request: String username = new String(username.getBytes("iso-8859-1"),"utf-8");
    POST request:request.setCharacterEncoding("utf-8");

  • Results garbled response:
    HTML page data: response.setContentType(type);
    plain text data:response.setCharacterEncoding(charset);

Published 12 original articles · won praise 3 · Views 241

Guess you like

Origin blog.csdn.net/qq_38599840/article/details/104419520