HttpServletRequest
HttpServletRequest
代表客户端的请求
用户通过Http协议访问服务器,HTTP请求中的所有信息会被封装到 HttpServletRequest
,通过这个HttpServletRequest
的方法,获得客户端的所有信息
获取前端参数,并进行请求转发
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
public class Login extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("UTF-8");
req.setCharacterEncoding("UTF-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
String[] hobbies = req.getParameterValues("hobbies");
System.out.println(username);
System.out.println(password);
System.out.println(Arrays.toString(hobbies));
//通过请求转发,同级跳转直接跳 /页面
//注意!重定向需要写项目名,转发不用
//req.getContextPath()
req.getRequestDispatcher("/success.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
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>login</servlet-name>
<servlet-class>com.mahe666.servlet.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
webapp/index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录页面</title>
</head>
<body>
<div style="text-align: center">
<%--${pageContext.request.contextPath}代表的是项目名--%>
<form action="${pageContext.request.contextPath}/login" method="get">
username:<input type="text" name="username"><br>
password:<input type="password" name="password"><br>
hobbies:
<input type="checkbox" name="hobbies" value="美女">美女
<input type="checkbox" name="hobbies" value="代码">代码
<input type="checkbox" name="hobbies" value="唱歌">唱歌
<input type="checkbox" name="hobbies" value="电影">电影
<br>
<input type="submit">
</form>
</div>
</body>
</html>
webapp/success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录成功</title>
</head>
<body>
<h2>登陆成功</h2>
</body>
</html>
重定向和转发的区别
相关博客:https://blog.csdn.net/weixin_38447888/article/details/106315971