Servlet知识总结(7)——HttpServletRequest

7.HttpServletRequest

HttpServletRequest代表客户端的请求,用户通过HTTP协议访问服务器,HTTP请求中的所有信息会被封装到HttpServletResquest,通过HttpServletResquest的方法可以获得客户端的所有信息

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>用户登录</title>
</head>
<body>
<h2>请登录</h2>
<div>
    <form action="${pageContext.request.contextPath}/login" method="post">
        用户名:<input type="text" name="username"><br>
        密码:<input type="password" name="password"><br>
        爱好:<br>
        <input type="checkbox" name="hobbys" value="唱">唱<br>
        <input type="checkbox" name="hobbys" value="跳">跳<br>
        <input type="checkbox" name="hobbys" value="rap">rap<br>
        <input type="checkbox" name="hobbys" value="篮球">篮球<br>
        <input type="submit">
    </form>
</div>
</body>
</html>
public class RequestDemo extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String[] hobbys = req.getParameterValues("hobbys");
        System.out.println("+++++++++++++++++++++++");
        System.out.println(username);
        System.out.println(password);
        System.out.println(Arrays.toString(hobbys));
        System.out.println("+++++++++++++++++++++++");

        req.getRequestDispatcher("/success.jsp").forward(req,resp);
    }
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h2><font color="green">登录成功</font></h2>
</body>
</html>

需注意转发只要写文件名即可

上一篇:Spring Boot【快速入门】


下一篇:获取请求用户的IP地址