Servlet basic concept

Servlet

overview

The whole process of Server Applet, that is, the server-side program written in java, which runs in the server and is mainly responsible for the communication between the client and the servlet and calling the servlet method

effect:

1. Receive user request data

2. Call other java programs to process request data

3. Respond to the client according to the processing result

Creation and use of Servlet

process:

1. Create a servlet class for processing front-end requests to inherit the HttpServlet class under the javax.servlet.http package

The specification of this class is created under the servlet directory of the project. The class name is composed of a custom name + Servlet. For example, the servlet class that processes login requests can be named LoginServlet

2. Rewrite the init, service, destroy methods in the parent class

//1.继承HttpServlet类
public class LoginServlet extends HttpServlet {
//2.重写service(),init(),destroy()方法
    public LoginServlet(){
        System.out.println("LoginServlet的无参构造");
    }
    //创建servlet对象,会将配置信息作为参数传入
    @Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println("LoginServlet的init()方法");
        //通过getInitParameter方法获取web.xml中的配置信息
        System.out.println("init:"+config.getInitParameter("n"));
    }
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("LoginServlet的service()方法");
        System.out.println(req);
        System.out.println(resp);
    }
    @Override
    public void destroy() {
        System.out.println("LoginServlet的destroy()方法");
    }
}

3. Configure in the Web.xml file

The Web.xml file is the configuration file of the web application and is used to configure the web resources. The file is located in the WEB-INF directory and the server will read the content in the web.xml file when it starts.

Configuration requires two steps:

① Register the servlet in the project

<servlet>
    <servlet-name>自定义的对象名</servlet-name>
    <servlet-class>servlet的全类名</servlet-class>
</servlet>
<!--
< servlet>元素用于注册Servlet,它包含有两个主要的子元素:
< servlet-name>和< servlet-class>,分别用于设置Servlet的注册名称和Servlet的完整类名。
-->

② Configure the address for the servlet

<servlet-mapping>
        <servlet-name>对应注册的对象名</servlet-name>
        <url-pattern>/Login</url-pattern><!--对应的url地址-->
</servlet-mapping>
<!--
< servlet-mapping>元素用于映射一个已注册的Servlet的一个对外访问路径,它包含有两个子元素:
< servlet-name>和< url-pattern>,分别用于指定Servlet的注册名称和Servlet的对外访问路径。
-->

Since the client accesses the resources in the web server through the URL address, if the Servlet program wants to be accessed by the outside world, the servlet program must be mapped to a URL address. This work uses the <servlet> element and the <servlet> element in the web.xml file. -mapping> element complete

Four methods in Servlet

no-argument constructor

The no-parameter construction method in the servlet class is used to initialize the members of the class. When the client sends a request for the first time or when the server starts, tomact will create a servlet object. At this time, the no-parameter construction method will be called. By default, it is in The servlet object is created after the first request is sent , if it is configured in the <servlet> element of the Web.xml file

<load-on-startup>-1</load-on-startup>

Greater than or equal to 0 means that the servlet object is created when the server starts (full load), and less than 0 means that the object is created when the request is sent

init

This method is called after the parameterless constructor to initialize the servlet and will only be called once

Same as the parameterless constructor, there are two situations to call

This method will pass in a ServletConfig parameter, which is an interface provided by tomcat to implement the class and used to encapsulate the information of the servlet object

Can be configured in the <servlet> element of Web.xml

<init-param>    
    <param-name>n</param-name>    
    <param-value>jim</param-value>
</init-param>

At this time, use the ServletConfig object to call the getInitParameter(String name) method to obtain the value of the configuration information

service

This method provides services for the front end and is called every time a request is made

The two parameters of this method are HttpServletRequest and HttpServletResponse, which are also two interfaces in java, and the implementation class is provided by tomcat

destroy

This method is called when the server is closed. It is mainly used to perform the final operations of the servlet program, such as storing data, printing logs, etc., and will only be called once.

The calling order of the above three methods is no parameter construction -->init-->service-->destroy, the construction method is called at the front, and the calling order of the latter three methods is specified in the top-level Servlet interface. All implementation classes of this interface need to follow this rule

Interaction between front-end and back-end programs

 

Servlet life cycle

Instantiation: no parameter construction method --> initialization: init --> service: service --> destruction: destroy

Recompilation of the web project

If you change the class name of the servlet or change the configuration file in the back-end java code, causing the project to fail to run normally, you need to recompile the java file and redeploy it to tomcat

The compiled java files are placed in the artifacts directory under the out directory. If recompilation is required, the build artifacts menu item in the build option in the toolbar is required. Select Clean to clear the compiled java files in the directory, and then restart Select Rebuild to recompile

Finally, remove the project in the original tomcat, and then re-deploy the java project to the tomcat server

Http protocol

When the front end sends a request to the back end, it will follow the Http protocol

overview

● Hypertext Transfer Protocol, the protocol for transmitting hypertext from the server to the local browser is used to define the process of exchanging data between the client browser and the server.

● HTTP is a communication protocol based on TCP/IP to transfer data

● HTTP is a protocol belonging to the application layer

http request

After the client connects to the server, it requests a web resource from the server, which means that the client sends an http request to the server.

For example: clicking a hyperlink and submitting a form are all sending an http request to the backend

Requests include:

Request line: including the requested address, request method, request status, request resource name, http version

Request header: Contains information on the server side and some environmental information on the client side, passed in the form of key-value pairs

Request body: store the data of the post request, the parameters in the request body are passed in the form of key values, multiple links are connected with &, and the server parses after receiving it.

request method

GET method:

Hyperlink access, the default is GET method form submission, no method is specified, the default is GET method POST method: form submission, specify method="POST" The difference between the Get method and the post method The Get method mainly obtains information from the server; the post is mainly Submit information to the server Get method submits data through the URL, the data can be seen in the URL; POST method, the data is placed in the request body and submitted. The size of the data submitted by GET is generally limited to 1kb (different browsers will vary); while POST does not have this limitation.

doGet() and doPost() methods

There are two methods in the servlet to deal with the two request methods, namely the doGet() and doPost() methods, which are called in the service method.

In the process of building a Servlet, it is necessary to create a new Servlet class that inherits from the HttpServlet class. This step will cause the subclass to meet the specifications specified in the Servlet interface. Even if the init, service, and destroy methods are not rewritten, the client sends the server These methods will still be called according to the specification when sending the request. So to implement the response to the http request in the doGet() and doPost() methods, you can directly rewrite these two methods in the servlet

HttpServletRequest object: (receive the requested data)

The tomcat server will encapsulate all the data of the http request into the object of the implementation class of the HttpServletRequest interface, and use this object in the process of data processing to obtain the requested information

Get request header: getHeader(String name)

Get the transmitted data: String getParameter(String name) String getParameterValues(String name)

In versions after Tomcat8, the data requested by get can be automatically transcoded, but the data requested by post needs to be decoded before receiving.

req.setCharacterEncoding("utf-8")

//1.继承HttpServlet类
public class LoginServlet_back extends HttpServlet {
//2.重写service(),init(),destroy()方法
  /*  public LoginServlet_back(){
        System.out.println("LoginServlet的无参构造");
    }
    //创建servlet对象,会将配置信息作为参数传入
    @Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println("LoginServlet的init()方法");
        //通过getInitParameter方法获取web.xml中的配置信息
        System.out.println("init:"+config.getInitParameter("n"));
    }
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("LoginServlet的service()方法");
        System.out.println(req);
        System.out.println(resp);
    }
    @Override
    public void destroy() {
        System.out.println("LoginServlet的destroy()方法");
    }
*/
    /*
    get与post方法是在service中调用的方法,在前端发送请求后会在service方法中判断请求的方式然后再进行方法的调用
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(req.getMethod());
        System.out.println(req.getProtocol());
        System.out.println(req.getRequestURL());
        System.out.println(req.getHeader("User-Agent"));
        System.out.println(req.getParameter("name"));
        System.out.println(req.getParameter("age"));
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接收数据
        req.setCharacterEncoding("utf-8");
        System.out.println(req.getMethod());
        System.out.println(req.getProtocol());
        System.out.println(req.getRequestURL());
        System.out.println(req.getHeader("User-Agent"));
        System.out.println(req.getParameter("account"));
        System.out.println(req.getParameter("password"));
        System.out.println(req.getParameter("gender"));
        String []hobbys=req.getParameterValues("hobby");
        System.out.println(Arrays.toString(hobbys));
        //处理数据
        //响应
        resp.setContentType("text/html;charset=utf-8");//设置响应的字符集
        PrintWriter printWriter= resp.getWriter();
        printWriter.print("提交成功");
    }
}public class LoginServlet extends HttpServlet {
    /*
        get与post方法是在service中调用的方法,在前端发送请求后会在service方法中判断请求的方式然后再进行方法的调用
         */
   /* @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(req.getMethod());
        System.out.println(req.getProtocol());
        System.out.println(req.getRequestURL());
        System.out.println(req.getHeader("User-Agent"));
        System.out.println(req.getParameter("name"));
        System.out.println(req.getParameter("age"));
    }
*/
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");//设置响应的字符集
        PrintWriter printWriter= resp.getWriter();
        String token = req.getHeader("token");
        DecodedJWT dec = JWTUtil.getTokenInfo(token);
        int id = dec.getClaim("id").asInt();//获取token中的id
        String account = dec.getClaim("account").asString();//获取token中的账号信息
        System.out.println("id :" + id + "  account :" + account);
        CommandResult commandResult = new CommandResult(200,null,"验证token成功");
        printWriter.print(new ObjectMapper().writeValueAsString(commandResult));
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");//设置响应的字符集
        PrintWriter printWriter= resp.getWriter();
        CommandResult commandResult=null;
        //处理数据
        try {
            LoginDao loginDao=new LoginDao();
            Admin admin=loginDao.checkAccount(req.getParameter("account"),req.getParameter("password"));
            if (admin!=null){
                String token = JWTUtil.token(admin.getId(),admin.getAccount());
                admin.setToken(token);
                commandResult=new CommandResult(200,admin,"登录成功");
            }else{
                commandResult=new CommandResult(201,null,"账号或密码错误");
            }
        } catch (Exception e) {
            commandResult=new CommandResult(500,null,"服务器忙,请稍后再试");
        }
        printWriter.print(new ObjectMapper().writeValueAsString(commandResult));
    }
}

http response

An http response represents the data returned by the server to the client, which includes: response line, response header, and response body.

Response line: contains the http protocol version, and is used to describe the processing result of the server to the request. HTTP/1.1 (protocol version) 200 (status) OK (status code description) Status code: a fixed number used by the server and browser to determine the status 200: the request is successful 302: the request is redirected 400: semantic error, the current request cannot The server understands or the request parameter is wrong 404: The requested resource does not exist, usually the path is wrongly written or the server resource is deleted 500: Service internal error (abnormal code)

Response header: used to describe the basic information of the server and data description Server Apache-Coyote/1.1 Content-Type text/html;charset=UTF-8 Content-Length 0 Date Wed, 13 Sep 2017 02:26:07 GMT

Response body: represents the text returned by the server to the client browser

HttpServletResponse object: (data that encapsulates the response)

When the web server receives the http request from the client, it will create an HttpServletResponse object representing the response for each request. The data returned by the server to the client will be encapsulated in this object

Common methods of this object:

getWriter(), get a PrintWriter character output stream output data, used to respond data to the front end, set the data in the response body

PrintWriter print stream (response data to the front end):

print(String message), write(String message) Both methods can print strings to the front end

Response will use ISO8859-1 to decode the characters that need to be output to the browser by default. If the output characters do not exist in ISO8859-1, it will cause garbled characters.

The response.setContetnType("text/html;charset=utf-8"); method can set the character set encoding used by the response and the character set encoding used by the browser to open at the same time.

filter

Filter, also known as filter, is the most practical technology in Servlet technology. WEB developers use Filter technology to manage all web resources managed by web servers (web resources that can intercept reception and response): such as Servlet, so as to realize some special features. For example, it implements some advanced functions such as URL-level permission access control, filtering sensitive words, and compressing response information.

Function: Intercept server web resources (authority control, authority control by intercepting resources, whether it can be accessed)

Filter interface

An interface Filter class is provided in Servlet. The class that implements this interface is called Filter Filter. Through this class, the user can intercept the access request and response before accessing a certain target resource.

The specification specified in the Servlet interface requires the implementation of three methods

init(FilterConfig filterConfig): This method is a method to initialize the filter object, which is called only once after the container initializes the filter object. The parameter FilterConfig can obtain the initialization parameters of the filter.

doFilter(ServletRequest request, ServletResponse response, FilterChain chain): This method is the method for filter to perform filtering operations, and is the most important method. Filter implementation classes must implement this method. The request and response can be preprocessed in the method body. Among them, FilterChain can pass the processed request and response objects to the next resource on the filter chain.

destroy(): This method is called before the container destroys the filter object.

public class EncodingFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("编码过滤器");
        servletRequest.setCharacterEncoding("utf-8");
        filterChain.doFilter(servletRequest,servletResponse);
    }
    
}

configure filter

After the filter filter is developed, the filter needs to be configured in the web.xml file

   
 <!--注册项目中的过滤器-->
    <filter>
        <filter-name>encode</filter-name><!--过滤器的名称-->
        <filter-class>com.yzl.webback.filter.EncodingFilter</filter-class><!--由反射机制创建对象-->
    </filter>
    <!--配置进入过滤器的地址-->
    <filter-mapping>
        <filter-name>encode</filter-name><!--与注册过滤器的名称对应-->
        <url-pattern>/*</url-pattern><!--设置哪些请求servlet的资源-->
    </filter-mapping>

Guess you like

Origin blog.csdn.net/yzl1293346757/article/details/127769463