servlet实操之重定向

一个web资源收到客户端请求,收到后通知客户端去访问另外一个web资源

常见场景

用户登录

servlet实现:

void sendRedirect(String location) throws IOException

//        resp.setHeader("Location","/Response_war/yanimage");
//        resp.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
          resp.sendRedirect("/Response_war/yanimage");

重定向和转发的区别:

不同点:
转发请求转发的时候url不会产生变化
重定向请求转发的时候url会产生变化
image
相同点:
都可以实现跳转

简单练习

项目首页jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>
<%--<提交的路径需要寻找到项目的路径>--%>
<%--<代表当前的项目pageContext.request.ContextPath>--%>
<form action="${pageContext.request.contextPath}/login" method="get">
    用户名: <input type="text" name="username">
    密码: <input type="password" name="password">
    <input type="submit">
</form>
</body>
</html>

后端接受请求:

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        System.out.println("进入请求");
        //处理请求
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println(username + ":" + password);
        //重定向一定要注意路径问题,否则就会404
        resp.sendRedirect("/Response_war/success.jsp");

    }
posted @   Takiyo  阅读(33)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性

阅读目录(Content)

此页目录为空

点击右上角即可分享
微信分享提示