Java web-Servlet request and response

Foreword: I
        ’m going crazy in online classes at home╰(‵□′)╯, there are no textbooks in class, it’s too uncomfortable, I can only record the content of learning during this period in the blog, it’s too difficult...


1. Overview of servlet:
  • A small JAVA program running on the WEB server, that is, a Java class.
  • A dynamic resource used to be accessed by users.
  • Generally, the java classes that implement the Servlet interface are collectively referred to as Servlet.
  • The prepared Servlet needs to be configured in the web.xml file for external access.
Second, the role of servlet:
  • Used to process the HTTP request from the client and return a response
  • It can handle the request doGet()and doPost()other methods.
Three, servlet system structure:
  • Servlet is provided by Servlet container
  • Servlet container refers to a server that provides Servlet functions (here, Tomcat)
  • The Servlet container dynamically loads the Servlet onto the server.
    Insert picture description here
  • Servlet requests are first received by the HTTP server, and the HTTP server is only responsible for parsing static HTML pages.
  • The servlet request is forwarded to the servlet container, and the servlet container will call the corresponding servlet according to the mapping relationship in the web.xml file.
  • The Servlet returns the processed result to the Servlet container, and transmits the response to the client through the HTTP server.
Four, three ways to create a servlet:
  • Directly implement the Servlet interface
  • Inherit the GenericServlet class
  • Inherit the HttpServlet class (commonly used)

The relationship is as follows:
Insert picture description here

Five, three methods of servlet life cycle:
  • init(): For the first visit to this Servlet, the Servlet object will be created and the initialization method will be executed. Only execute it once.
init(ServletConfig config):
其中的config就是ServletConfig接口对象。  
  • service(): Respond to client requests. Every time you visit the Servlet, it will be executed
service(ServletRequest request, 
ServletResponse response) 
  • destroy(): After the server is shut down normally, this method will be executed, only once.
public void destroy() 
Six, configure the web.xml file:

The prepared Servlet needs to be configured in the web.xml file for external access. The Servlet container will call the corresponding Servlet according to the mapping relationship in the web.xml file

Example:

<web-app>
<servlet>
    <servlet-name> FirstServlet </servlet-name>  //为了方便使用Servlet,取的别名
    <servlet-class> pdsu.edu.cn.hm.HelloWorld </servlet-class>  //完整的包名+类名
</servlet>

<!-- 配置如何访问这个servlet -->
<servlet-mapping>
    <servlet-name> FirstServlet </servlet-name>  //和上面那个起的别名必须相同!
    <url-pattern> /HelloServlet </url-pattern>  //访问Servlet的URL
</servlet-mapping>
</web-app>

According to the web.xml configured above, the access path of the project is:
Insert picture description here

Seven, inherit the class to create a servlet:

Define the HelloWorld class to inherit the HttpServlet class:

1. Implementation doGetor doPostmethod (or both).

2. The method parameters of these two methods are:

  • HttpServletRequest: Used to obtain the data of the Form, the header information of the HTTP request, and so on.
  • HttpServletResponse: Used to set the HTTP status code, HTTP response header information, and obtain the output stream object used to send data to the client.

3. In most cases, doPostit is called in a method doGet, or vice versa.

8. Servlet request and response:

1. The difference between Get and Post submission :
Insert picture description here

2. When to use the GET/POST method :

  1. Use the GET method when requesting a static page or graphic file, because only the file name needs to be sent;
  2. When sending big data, use the POST method;
  3. When uploading files, use the POST method;
  4. Use the POST method when sending user names, passwords or other confidential information.

3. Response status header :

setHeader() 设置响应头,String类型的值
addHeader() 加响应头
setIntHeader()设置响应头,int类型的值
setDateHeader()设置响应头,date类型的值
containsHeader()是否包含指定的响应头
addCookie()向set-cookie报头插入一个cookie

4. Set the method to deal with garbled characters :

setContentType() 设置响应的类型和编码方式,比如response.setContentType("text/html;charset=utf-8");
setCharacterEncoding() 设置响应字符编码,比如response.setCharacterEncoding("utf-8"); 

5. Response message body :

The getWriter() method is used to get a text output stream

PrintWriter out = response.getWriter();
调用print()println()write()方法

The getOutputStream() method is used to get a binary output stream

ServletOutputStream out = response.getOutputStream();
OutputStream比使用PrinterWriter发送文本效率更高,可以动态地创建任何形式的数字内容

Example:

public void doGet( HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
    
    
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		....
	}
	public void doPost( HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
    
    
		doGet(request, response);
	}

6. HttpServletRequest object method :

Get request line:

getMethod():获取HTTP的请求方法,GET、POST等
getRequestURI():获取请求的URI,/项目名/servlet路径
getRequestURL():获取请求的URL,包含协议名、服务器名或IP、端口号和请求资源但不包括查询字符串参数,如http://127.0.0.1:8080/lovo/index.html
getQueryString():获取请求URL后面的查询字符串,如name=zhangsan
getProtocol():获取请求的协议名和版本号,如HTTP/1.1
getContextPath():获取项目名称
getServletPath():获取Servlet的映射路径,如Analyz

Get request header:

getHeader(name):返回指定的请求头的值 
getHeaders(name):返回一个Enumeration(枚举)包含请求头中的所有值 
getHeaderNames():特定请求中接收到的所有请求头的名称 
getIntHeader(name):获取特定请求头的值,并将其转化为int类型
getDateHeader(name):获取特定请求头的值,并将其转化为Date类型

7. Get form data :

  • getParameter(parameterName): Get the value of the form parameter. The parameter name is case sensitive and consistent with the parameter name that appears in the HTML form. The same method can be used for both GET and POST requests.
  • getParameterValues(parameterName): Get multiple parameter values ​​of the same parameter name, and return a string array object
  • getParameterNames(): Return a list of all form parameter names in the request in the form of Enumeration

Example:

String name=request.getParameter("username");
String sex=request.getParameter("sex");
String email=request.getParameter("email");

8. Request redirection :

  • When the Web server receives the client's request, due to certain restrictions, it cannot access the Web resource pointed to by the current request URL. A new resource path can be specified to allow the client to resend the request. This is request redirection.

Two ways to achieve redirection:

1. Use with status code 302+location:

response.setStatus(302);
response.setHeader(“location”,/项目名/页面名或servlet名”)

2. Directly specify URI redirect:

response.sendRedirect("/lovobook/bar.html");

9. Set the page to refresh automatically :

1. Timing jump: jump from one page to another page regularly, for example, the registration page jumps to the login page

response.setHeader("Refresh", "5;URL=http://www.baidu.com");

2. Regular refresh: page address remains unchanged, page data changes, such as online ticket purchase

response.setHeader("Refresh", "3");
response.getWriter().println(new java.util.Date());

10. Response status header :
Insert picture description here
Example:
output Excel sheet

public class RefreshServlet extends HttpServlet
{
    
      public void doGet(HttpServletRequest request,  HttpServletResponse  response) throws ServletException, IOException
    {
    
    
        response.setCharacterEncoding("GBK");
        //设置响应类型(Excel)
      response.setContentType("application/vnd.ms-excel");
      PrintWriter out = response.getWriter();
      out.println("姓名\t 年龄\t 性别");
      out.println(“张小三\t 20\t 男");
      out.println(“李小斯\t 21\t 女");
    }
}

The result will be an Excel file
Insert picture description here

Nine, ServletContext object:

Role: Shared data that can be accessed by all users can be stored in the ServletContext.
Features:

  1. Only destroyed when the web application is closed
  2. Different web applications, ServletContext exist independently
  3. Each web application has only one ServletContext object

Get the object :getServletContext()

  • Different Servlets in the same Web application call the getServletContext method to obtain the same ServletContext object instance, which
    can be locked to prevent the web application from accessing key parts.

Common methods of ServletContext :

Ways to access initial parameters:

getInitParameter(String name), getInitParameterNames()

Method to read web application properties:

getAttribute(String name), getAttributeNames( )

Methods of manipulating web application properties:

setAttribute(String, Object), removeAttribute(String)

Get the resource forwarder:

 RequestDispatcher getRequestDispatcher(String path)
Ten, RequestDispatcher object:

Function: Send the request sent by the client to other resources of the server.
The resource type can be static resources (such as HTML files) or dynamic resources (such as Servlet or JSP files).

Example:
To send the request to resource x

//必须使用相对于根”/”的路径
getServletContext().getRequestDispatcher("/x")
//可以为当前或根的相对路径
request.getRequestDispatcher("x")

Method of RequestDispatcher :

Forward the request from the current Servlet to other resources:

void forward(ServletRequest request,ServletResponse response) 

Include the content of the resource in the response object:

void include(ServletRequest request,ServletResponse response) 

Example: forward to index.html

getServletContext().getRequestDispatcher("/index.html").forward(request, response);

Ok, let's stop here this time, and record a separate cookie and session for the following session.

Guess you like

Origin blog.csdn.net/qq_43531669/article/details/105569412