Servlet知識總結(7)——HttpServletRequest
阿新 • • 發佈:2020-08-07
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>
需注意轉發只要寫檔名即可