Servlet Getting Started - What is the servlet

A, Servlet
Background: In the past did not know what servlet, the interview is the vague answer is java program. Just to get what they do not have time to read the tutorial to learn other people's blog, clearly doing a servlet, the first summary record notes, so as not to ever forget it, you also need again.

1. What is the servlet
        the Java Servlet is running the program on a Web server or application server. Usually we have a program to achieve the java servlet interface, called Servlet.

Servlet sun is provided by a technology used to develop dynamic web resources.
  Sun has provided thereon in a servlet API interfaces, users wishing to send a dynamic web resource (i.e. the development of a Java program output data to the browser),
complete the following two steps:
  1. preparation of a Java class that implements the servlet interface.
  2, to develop good Java classes deployed to a web server.
  
2.servlet benefits

  • You may collect user input from a web form; showing records from a database or other sources; also can dynamically create web pages.

  • Read client (browser) of the transmitted data explicit. Form HTTP client program that includes HTML form on a web page, or may be derived from or customized applet. Read client (browser) sends implicit HTTP request data. This includes cookies, media types and browsers can understand compression format, and so on.

  • Processing the data and generate a result. This process may need to access the database, the implementation of RMI or CORBA calls, call the Web service, or directly calculated corresponding response.

  • Transmitting the explicit data (i.e., document) to the client (browser). The format of the document can be varied, including text files (HTML or XML), binary files (GIF
    image), Excel and so on.

  • Sending an implicit HTTP response to the client (browser). This includes tells the browser or other client is returned the document type (eg HTML), set cookies
    and cache parameters, and other similar tasks.

3. Create the servlet codes
          Servlet and can be created using javax.servlet javax.servlet.http packages
in three ways:
1, to achieve Servlet interface

/*
 * 1.实例化(使用构造方法创建对象)
 * 2.初始化  执行init方法
 * 3.服务     执行service方法
 * 4.销毁    执行destroy方法
 */
public class ServletDemo1 implements Servlet {

    //public ServletDemo1(){}

     //生命周期方法:当Servlet第一次被创建对象时执行该方法,该方法在整个生命周期中只执行一次
    public void init(ServletConfig arg0) throws ServletException {
                System.out.println("=======init=========");
        }

    //生命周期方法:对客户端响应的方法,该方法会被执行多次,每次请求该servlet都会执行该方法
    public void service(ServletRequest arg0, ServletResponse arg1)
            throws ServletException, IOException {
        System.out.println("hehe");

    }

    //生命周期方法:当Servlet被销毁时执行该方法
    public void destroy() {
        System.out.println("******destroy**********");
    }
   //当停止tomcat时也就销毁的servlet。
    public ServletConfig getServletConfig() {
        return null;
    }

    public String getServletInfo() {
        return null;
    }
}

2, class inheritance GenericServlet

public class ServletDemo2 extends GenericServlet {

    @Override
    public void service(ServletRequest arg0, ServletResponse arg1)
            throws ServletException, IOException {
        System.out.println("heihei");

    }
}

3, inherited HttpServlet method (commonly used)

package com.lixu.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletDemo1 extends HttpServlet{

	/**
	 * 标识 ID
	 */
	private static final long serialVersionUID = 1L;
    
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException{

	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException{
		
		doGet(request, response);
	}
	
}

the web.xml configuration:

<servlet>
     <servlet-name>ServletDemo1</servlet-name>
     <servlet-class>com.lixu.servlet.ServletDemo1</servlet-class> <!-- 实现的servlet所在包的地址 -->
  </servlet>

  <servlet-mapping>
     <servlet-name>ServletDemo1</servlet-name> 
     <url-pattern>/servlet/ServletDemo1</url-pattern>  <!-- 请求路径,servlet被外界访问,需要的映射访问地址 -->
     <init-param> <!-- 初始化参数,可不写 -->
         <param-name>myparam</param-name>
         <param-value>xiaoming</param-value>
     </init-param>
  </servlet-mapping>

A Servlet only have one object, all service requests
        HttpServlet in the original method of the Servlet have carried out the default action, no explicit initialization and destruction service (), in HttpServlet, the custom of a new service () method in which getMethod () method of the type judgment request to invoke doGet () or doPost () processing get, post the request, the user need only to extend the HttpServlet, then override doPost () or doGet () processing method request can be.

Two, servlet life cycle

  • Servlet is initialized by calling a method init ().
  • Servlet call service () method to process client requests.
  • Servlet by calling destroy () method is terminated (end).
  • Finally, Servlet is garbage collected by the JVM's garbage collector.

        Note: destory method is called after, servlet is destroyed, but did not immediately recovered, when requested again, and did not re-initialized.

Three, form data Servlet
Servlet form data processing, the data may use different methods depending on the automatic analysis:

  • getParameter (): You can call request.getParameter () method to get the value of the form parameter.
  • getParameterValues ​​(): If the parameter appears more than once, this method is called, and returns multiple values, e.g. checkbox.
  • getParameterNames (): If you want to get a complete list of all the parameters of the current request, then the method call.

Examples
get way:

jsp test page:

<form action="getForm" method="GET">
	                用户名: <input type="text" name="name" value="张三" />
	                网址:<input type="text" name="url" />
	             <input type="submit" value="get方式提交">
     </form>

Customizing a servlet processing request:

package com.lixu.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 处理get数据请求
 */
@WebServlet("/getForm")
public class myservlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		// 设置响应内容类型
        response.setContentType("text/html;charset=UTF-8");

        String title = "使用 GET 方法读取表单数据";
        
        /*
         * getParameter()获取 表单 参数的值。
         */
        String name = request.getParameter("name");
        String url = request.getParameter("url");
        
        //参考教程时,get请求需要编码,但是我加上下面的代码,运行时反而乱码(显示:???)(我也不清楚为什么)
        //name =new String(name.getBytes("ISO8859-1"), "UTF-8") ;
       
        //打印信息
        PrintWriter out = response.getWriter();
        String docType = "<!DOCTYPE html> \n";
        out.println(docType +
            "<html>\n" +
            "<head><title>" + title + "</title></head>\n" +
            "<body bgcolor=\"#f0f0f0\">\n" +
            "<h1 align=\"center\">" + title + "</h1>\n" +
            "<ul>\n" +
            "  <li><b>站点名</b>:"
            + name + "\n" +
            "  <li><b>网址</b>:"
            + url + "\n" +
            "</ul>\n" +
            "</body></html>");
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

xml arrangement

<?xml version="1.0" encoding="UTF-8"?>
<!-- 我这里代码放开,报格式错误,我就不校验了 -->
<!-- <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> -->
<web-app>  
  <servlet>
     <servlet-name>myservlet</servlet-name>
     <servlet-class>com.lixu.servlet.myservlet</servlet-class> <!-- 实现的servlet所在包的地址 -->
  </servlet>
  
  <servlet-mapping>
     <servlet-name>myservlet</servlet-name> 
     <url-pattern>/servlet/myservlet</url-pattern>  <!-- 请求路径,servlet被外界访问,需要的映射访问地址 -->
     <init-param> <!-- 初始化参数,可不写 -->
         <param-name>myparam</param-name>
         <param-value>xiaoming</param-value>
     </init-param>
  </servlet-mapping>
</web-app>

Effect:
Here Insert Picture Description
POST request:

package com.lixu.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 处理get数据请求
 */
@WebServlet("/postForm")
public class myservlet1 extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		// 设置响应内容类型
        response.setContentType("text/html;charset=UTF-8");

        String title = "使用 POST 方法读取表单数据";
        
        //getParameter();
        String name =new String(request.getParameter("name").getBytes("ISO8859-1"),"UTF-8");
        
        String url = request.getParameter("url");
        url = new String(url.getBytes("ISO8859-1"),"UTF-8");
     
        //打印信息
        PrintWriter out = response.getWriter();
        String docType = "<!DOCTYPE html> \n";
        out.println(docType +
            "<html>\n" +
            "<head><title>" + title + "</title></head>\n" +
            "<body bgcolor=\"#f0f0f0\">\n" +
            "<h1 align=\"center\">" + title + "</h1>\n" +
            "<ul>\n" +
            "  <li><b>站点名</b>:"
            + name + "\n" +
            "  <li><b>网址</b>:"
            + url + "\n" +
            "</ul>\n" +
            "</body></html>");
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

jsp, web.xml needs to be rewritten, configuration (almost a lazy posts)

Four, springMVC the servlet application
        in springMVC in, or we SSM project: generally do not need to define our own servlet, mostly used is DispatcherServlet (central distributor) SpringMVC provided.
DispatcherServlet is the ultimate inherited HttpServlet, which means it is a framework of common Servlet. Controller layer HttpServletRequest data acquisition request.
web.xml configuration:

<servlet>
  <servlet-name>dispatcher</servlet-name>  
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <!-- tomcat启动时自动创建servlet,数字越小优先级越高(>0) -->  
  <load-on-startup>1</load-on-startup> 
</servlet>

<servlet-mapping>
  <servlet-name>dispatcher</servlet-name>  
  <!--  "/" 拦截所有请求 -->
  <url-pattern>/</url-pattern>  
</servlet-mapping>

Reference: HTTPS: //www.runoob.com/servlet/servlet-form-data.html
          https://www.cnblogs.com/xdp-gacl/p/3760336.html

Published 16 original articles · won praise 3 · Views 534

Guess you like

Origin blog.csdn.net/outdata/article/details/102543784