1. 程式人生 > 其它 >javaweb22/4/3

javaweb22/4/3

HttpServletRequest

如果要獲取客戶端請求過來的引數,找HttpServletRequest

HttpServletRequest代表客戶端的請求,使用者通過Http協議訪問伺服器,
Http請求中的所有資訊會被封裝到HttpServletRequest,通過HttpServletRequest的方法,獲得客戶端的所有資訊

獲取前端傳遞的引數,請求轉發

1.登入頁面

<body>
<h2>登入</h2>
<div>
<%--    ${pageContext.request.contextPath}/login  是通過<servlet-mapping>在web.xml中找到/login,之後通過<servlet>找到LoginServlet--%>
    <form action="${pageContext.request.contextPath}/login" method="post">
    使用者名稱:<input type="text" name="username"><br>
    密碼:<input type="password" name="password"><br>
    愛好:
        <input type="checkbox" name="hobbys" value="唱歌">唱歌
        <input type="checkbox" name="hobbys" value="跳舞">跳舞
        <input type="checkbox" name="hobbys" value="玩遊戲">玩遊戲
        <input type="submit">

    </form>

</div>
</body>

2.編寫Servlet

@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[] hobbys = req.getParameterValues("hobbys");

        //  會把/識別成當前應用,無需再寫/s/seccess
        req.getRequestDispatcher("/success.jsp").forward(req,resp);

        System.out.println(username+":"+password);
        System.out.println(Arrays.toString(hobbys));


    }

3.在web.xml中註冊Servlet

<servlet>
    <servlet-name>Log</servlet-name>
    <servlet-class>com.wenping.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>Log</servlet-name>
    <url-pattern>/login</url-pattern>
</servlet-mapping>

4.編寫LoginServlet轉發的頁面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h2>登陸成功</h2>
<h3>SECCESS</h3>
</body>
</html>

解決遇到的問題:

1.轉發成功,但是success頁面無內容

解決:req.getRequestDispatcher("/success.jsp")後忘記加.forward(req,resp);
2.success頁面顯示404
解決:getResquestDisptcher()的引數寫成/s/seccess,應是/seccess,IDEA會把/識別成當前應用,無需再寫/s/seccess
3.控制檯內容中文亂碼
解決:編輯Tomcat配置,在虛擬機器選項中填寫 -Dfile.encoding=UTF-