Servlet 入门—请求转发和重定向

入门案例以登录为例子,介绍了servlet 的概念以及请求响应模型。实际的工程中,登录后通常都会跳转到新的页面。挑战就是我们今天要学习的新的知识点。

1. 从 index.jsp 复制一个新的页面,作为登录成功后跳转的新页面

页面内容:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>首页</title>
  </head>
  <body>
        欢迎您, <%= request.getAttribute("username") %>
  </body>
</html>

2. 修改后台 servlet

3. 启动 tomcat 验证

输入用户名密码,点击登录后:

重定向

1. 修改 success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>首页</title>
  </head>
  <body>
        欢迎您, <%= session.getAttribute("username") %>
  </body>
</html>

2. 修改后台 servlet

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // req 对象获取客户端发送过来的请求参数
        // 解决请求参数乱码
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println("Your Input: " + username + "/" + password);
        // 解决响应参数乱码
        resp.setContentType("text/html;charset=utf8");
       // resp.getWriter().write("登录成功!");

        // 重定向
        // 1. 携带登录成功的用户名到页面
        req.getSession().setAttribute("username", username);
        // 2. 通过重定向的方式,跳转到 success.jsp 页面
        resp.sendRedirect("success.jsp");
    }

3. 启动 tomcat ,验证

区别

重定向,是让浏览器发第二次请求,所以无法继续通过 request 传递参数,需要借助 session !


经验分享 程序员 微信小程序 职场和发展