Java Web (5) – servlet details (Part 2)

1、 HttpServletRequest class

1. What is the role of HttpServletRequest?

Every time a request enters the Tomcat server, the Tomcat server parses and encapsulates the requested HTTP protocol information into the request object. Then it is passed to the service methods (doget and dopost) for us to use. You can obtain the information of all requests through the HttpServletRequest object

2. Common methods of HttpServletRequest class

The details are as follows:

First, build the environment and configure the web XML, and then in the class

package com.md.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author MD
 * @create 2020-07-25 8:18
 */
public class RequestAPIServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException {

        System.out.println(req.getRequestURI());// /04_Servlet/requestAPIServlet

        System.out.println(req.getRequestURL());
        //http://localhost:8080/04_Servlet/requestAPIServlet

        System.out.println(req.getRemoteHost());//127.0.0.1

        System.out.println(req.getHeader("User-Agent"));//Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/83.0.4103.116 Safari/537.36

        System.out.println(req.getmethod());//GET
    }

    @Override
    protected void doPost(HttpServletRequest req,IOException {
        super.doPost(req,resp);
    }
}

Corresponding web xml

 <servlet>
        <servlet-name>RequestAPIServlet</servlet-name>
        <servlet-class>com.md.servlet.RequestAPIServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>RequestAPIServlet</servlet-name>
        <url-pattern>/requestAPIServlet</url-pattern>
    </servlet-mapping>

3. Get request parameters

First, create an HTML file under the web, as follows

<!DOCTYPE html>
<html lang="en">
<head>
    <Meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="http://localhost:8080/parameterServlet" method="post">
        用户名:<input type="text" name="username"><br>
        密码:<input type="password" name="password"><br>
        爱好:<input type="check@R_932_2419@" name="hobby" value="cpp">C++
        <input type="check@R_932_2419@" name="hobby" value="java">Java
        <input type="check@R_932_2419@" name="hobby" value="python">Python
        <input type="submit">
    </form>
</body>
</html>

Then there is the corresponding java code and the configured web XML (similar to above)

/**
 * @author MD
 * @create 2020-07-25 8:31
 */
public class ParameterServlet extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req,IOException {

        System.out.println("------------doGet--------------");
        // 获取请求的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
//        String hobby = req.getParameter("hobby");
        // 当有多个值的时候
        String [] hobby = req.getParameterValues("hobby");

        System.out.println("用户名:"+username);
        System.out.println("密码:"+password);
        System.out.println("爱好:"+ Arrays.asList(hobby));


    }
}

4. Chinese garbled code

When using the post request, if the user name is entered in Chinese, Chinese garbled code will appear, so this setting is required

public class ParameterServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req,IOException {
        // 在post的时候注意设置字符集,要不中文乱码
        // 只有在获取请求参数调用之前使用才有效
        req.setCharacterEncoding("UTF-8");

        System.out.println("------------doPost--------------");

        // 获取请求的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
//        String hobby = req.getParameter("hobby");
        // 当有多个值的时候
        String [] hobby = req.getParameterValues("hobby");

        System.out.println("用户名:"+username);
        System.out.println("密码:"+password);
        System.out.println("爱好:"+ Arrays.asList(hobby));

    }
}

5. Request forwarding

What is request forwarding?

Request forwarding refers to the operation that the server jumps from one resource to another after receiving the request, which is called request forwarding

Characteristics of request forwarding:

An example is as follows: access servlet1 and forward it to servlet2

public class Servlet1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req,IOException {
       // http://localhost:8080/04_Servlet/servlet1?username=abc

        // 1. 获取请求的参数
        String username = req.getParameter("username");
        System.out.println("在Servlet1中获取到的请求参数:"+username);
        // 在Servlet1中获取到的请求参数:abc


        // 2. 把获取到的数据传递,也可以自定义参数传递
//        req.setAttribute("username",username);
        req.setAttribute("key","我来自Servlet1");


        // 3. 转发
        // 地址必须以 /开头 ,这个地址也是在web.xml中配置对应的你要去的
        RequestDispatcher requestDispatcher = req.getRequestDispatcher("/servlet2");
        requestDispatcher.forward(req,resp);
        
        // 或者可以直接这样
        req.getRequestDispatcher("/servlet2").forward(req,resp);

    }
}

Corresponding web XML is not displayed. They are similar

/**
 * @author MD
 * @create 2020-07-25 8:57
 */
public class Servlet2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req,IOException {
        // 1. 获取请求的参数
        String username = req.getParameter("username");
        System.out.println("在Servlet2中获取到的请求参数:"+username);//在Servlet2中获取到的请求参数:abc

        // 2. 查看从Servlet1中传递的参数
        Object key = req.getAttribute("key");
        System.out.println("Servlet1中传来的参数:"+key);//Servlet1中传来的参数:我来自Servlet1

        // 3. 处理自己的业务
        System.out.println("正在处理Servlet2的业务");//正在处理Servlet2的业务

    }
}

6. Base label

Therefore, in HTML file, if relative path is used during jump, specify relative path

<!DOCTYPE html>
<html lang="en">
<head>
    <Meta charset="UTF-8">
    <title>Title</title>
    <!--
        base标签设置页面相对路径工作时参照的地址
        href 属性就是参数的地址值
    -->
    <!--<base href="http://localhost:8080/04_Servlet/a/b/c.html">-->
    <!--
        也可以这样,但最后的斜杠不能省略
    -->
    <base href="http://localhost:8080/04_Servlet/a/b/">

</head>
<body>
    这是a目录下的b目录下的c.html页面
    <a href="../../index.html">跳到首页</a>
<!--通过定义了base,这个就相当于那个地址的上上层
    http://localhost:8080/04_Servlet/index.html
-->
</body>
</html>

The absolute path shall be used as much as possible in the development. If it is not possible, the base + relative path shall be used

7. Different meanings of / slash in Web

In the web / is an absolute path

2、 Httpservletresponse class

1. Role of httpservletresponse class

The httpservletresponse class is the same as the HttpServletRequest class.

Every time a request comes in, the Tomcat server will create a response object and pass it to the servlet program for use. HttpServletRequest represents the requested information, and httpservletresponse represents the information of all responses,

If we need to set the information returned to the client, we can set it through the httpservletresponse object

2. Two output streams

3. How to return data to the client

First, create a servlet and configure the corresponding web xml

Pay attention to Chinese garbled code

package com.md.servlet;
/**
 * @author MD
 * @create 2020-07-25 9:57
 */
public class ResponseIOServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req,IOException {

//        System.out.println(resp.getCharacterEncoding());//ISO-8859-1
//
//        // 设置服务器字符集为
//        resp.setCharacterEncoding("UTF-8");
//        // 此时若浏览器没有使用UTF-8中文还是乱码,这个时候需要
//        // 通过设置响应头,使得浏览器也使用UTF-8字符集
//        resp.setHeader("Content-Type","text/html; charset=UTF-8");


        // 或者直接可以这样写,自动设置服务器字符集和浏览器响应头
        // 方法一定要流获取之前先调用,通常放在最上面就行
        resp.setContentType("text/html; charset=UTF-8");


        // 需求:往客户端回传字符串数据

        PrintWriter writer = resp.getWriter();
        writer.write("response");
        writer.write("越过山丘,");
    }
}

4. Request redirection

Request redirection means that the client sends a request to the server, and then the server tells the client. I'll give you some addresses. You visit the new address. Request redirection (because the previous address may have been discarded)

Characteristics of request redirection:

An example is as follows: access RESPONSE1 and redirect to response2

/**
 * @author MD
 * @create 2020-07-25 10:15
 */
public class Response1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req,IOException {

        System.out.println("Response 1 ");

//        // 设置响应状态码,表示重定向
//        resp.setStatus(302);
//
//        // 设置响应头,说明新的地址,和web.xml里的要对应
//        resp.setHeader("Location","http://localhost:8080/04_Servlet/response2");


        // 推荐使用
        resp.sendRedirect("http://localhost:8080/04_Servlet/response2");
    }
}

//-----------------------------------

public class Response2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req,IOException {
        System.out.println("Response  2 ");

        resp.getWriter().write("Response2 result !");

    }
}

Corresponding web xml

<servlet>
        <servlet-name>Response1</servlet-name>
        <servlet-class>com.md.servlet.Response1</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>Response1</servlet-name>
        <url-pattern>/response1</url-pattern>
    </servlet-mapping>

    <!---->
    <servlet>
        <servlet-name>Response2</servlet-name>
        <servlet-class>com.md.servlet.Response2</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>Response2</servlet-name>
        <url-pattern>/response2</url-pattern>
    </servlet-mapping>
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>