HttpServletRequest

HttpServletRequest

Request请求和Response响应相对应。

以下是模拟登录然后重定向到特定网页

jsp中:${pageContext.request.contextPath}可以获得网页页面的绝对路径。

  首先是:RequestDemo01类

public class RequestDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = this.getServletContext();
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        resp.sendRedirect("/ServletTestDemo_war/TestDemo.jsp");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println(username + "\n" + password);
    }

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

  然后是index.jsp初始网页

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>
<a href="http://localhost:8080/ServletTestDemo_war/demo01">
    <input type="button" name="button" value="点我登陆">
</a>
</body>
</html>

  然后是TestDemo.jsp测试网页

<%--
  Created by IntelliJ IDEA.
  User: 22729
  Date: 2021/7/30
  Time: 16:31
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>TestDemo</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/ResultDemo.jsp" method="get">
    <p>
        <span>账户:</span>
        <input type="text" name="username">
    </p>
    <p>
        <span>密码:</span>
        <input type="password" name="password">
    </p>
    <p>
        <input type="submit" name="submit">
    </p>
</form>

</body>
</html>

  最后是ResultDemo.jsp

<%--
  Created by IntelliJ IDEA.
  User: 22729
  Date: 2021/7/30
  Time: 16:51
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Result</title>
</head>
<body>
<h1>
    Succes
</h1>
</body>
</html>

  web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0"
         metadata-complete="true">

    <servlet>
        <servlet-name>requsetDemo01</servlet-name>
        <servlet-class>com.zhang.Servlet.RequestDemo01</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>requsetDemo01</servlet-name>
        <url-pattern>/demo01</url-pattern>
    </servlet-mapping>
</web-app>

 

HttpServletRequest

上一篇:js控制全屏显示


下一篇:JsPDF+html2canvas将网页转换成PDF并解决了图表文字不跨页的问题