javaWeb学习笔记之关于重定向和请求转发的区别

  • 相同点

    都会实现页面跳转

  • 不同点

    请求转发的时候,URL路径不会发生改变

    重定向,URL路径会发生改变

简单代码实现重定向:

修改index.jsp实现一个简单的表单

<%--这里提交的路径,需要寻找到项目的路径--%>
<%--${pageContext.request.contextPath}代表当前的项目--%> 
<form action="${pageContext.request.contextPath}/login" method="get"> 
    用户名:<input type="text" name="username"> <br>
    密码:<input type="password" name="password"> <br> 
    <input type="submit">
</form>
public class RedirectServlet 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");
        //进行重定向
        resp.sendRedirect("/r/success.jsp");
    }
}

新的jsp页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %> 
<html> 
    <head>
        <title>Title</title> 
    </head> 
    <body> 
        <h1>Success</h1> 
    </body> 
</html>
posted @ 2020-08-05 10:39  Kepler(*^_^*)  阅读(90)  评论(0编辑  收藏  举报