Java 利用response重定向后无法显示页面内容

界面代码

login.jsp

登陆
<form action="<%=request.getContextPath()%>/login_do" method="post">
    用户名:<input type="text" name="username"/><br>
    密码:<input type="password" name="password"/><br>

    <input type="submit" value="登陆">
form>

loginservlet

public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username =request.getParameter("username");
        String password=request.getParameter("password");
        UserService userService=new UserService();
        User user=userService.login(username,password);
        if(user!=null){
            request.getSession().setAttribute("user",user);
            if(user.isAdmin()){
                response.sendRedirect(request.getContextPath()+"/admin/goods_list");
            }else {
                request.getRequestDispatcher("/").forward(request,response);
            }

        }else {
            request.setAttribute("msg","用户名或密码错误,请重新登陆");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

goods_list.jsp

public class GoodsListServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Goods> list=new GoodsServices().selectAllGoods();
        request.setAttribute("list",list);
        request.getRequestDispatcher("/admin/goods_list.jsp").forward(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   
    }
}

运行结果:

后发现无法跳转到goods_list界面。

解决办法:

最终通过http请求发现界面在进行response.sendRedirect()重定向时,会默认使用get请求方式,而原来是对post处理,所以需要把处理写在doGet()中

你可能感兴趣的:(Java,web)