JavaWeb 两个疑问解答-转发和重定向显示的问题+前端转后端乱码问题-2023-04-06

一、转发和重定向显示的问题

      如果想在index.jsp中输入表单内容,提交后的 username 和 password 信息通过转发在另一个页面显示。

      只能用requestDispatcher, 不能用sendredirect

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>登录界面</title>
  </head>
  <body>

  <form action="${pageContext.request.contextPath}/login" method="post">
    <span>用户名:</span> <input type="text" name="username" > <br>
    <span>密码:</span> <input type="text" name="password" > <br>
    爱好:<br>
    <input type="checkbox" name="hobbys" value="足球">足球
    <input type="checkbox" name="hobbys" value="basketball">篮球
    <input type="checkbox" name="hobbys" value="排球">排球
    <br>
    <input type="submit">
  </form>

  </body>
</html>
package com.feijian.servlet;

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 RequestServlet 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");
        System.out.println(username+" : "+password);
        String[] hobbys = req.getParameterValues("hobbys");
        System.out.println(Arrays.toString(hobbys));
        for (String hobby : hobbys) {
            resp.getWriter().println(hobby);
        }

//        resp.sendRedirect("/r/success.jsp");
//        req.setAttribute("msg",username);
//        req.setAttribute("msg1",password);

        req.setAttribute("msg",username);
        req.setAttribute("msg1",password);
        req.getRequestDispatcher("/success.jsp").forward(req,resp);



    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
<?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">
    
    <servlet>
        <servlet-name>request</servlet-name>
        <servlet-class>com.feijian.servlet.RequestServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>request</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>
</web-app>

为什么不能用SendRedirect 是因为重定向会跳转到第二个页面,系统认为是第二个request, 显然第一个request的信息不会传给第二个response,相当于两个独立的request 和 response

在从前端多个爱好选项内容,写入后端在控制台上显示乱码问题。主要是在Tomcat上要做虚拟机的代码说明,如下:

posted @ 2023-04-06 20:16  Rui2022  阅读(71)  评论(0编辑  收藏  举报