zoukankan      html  css  js  c++  java
  • 转发和重定向

    转发

    转发的特点

    重定向

    重定向的特点

    • 地址栏:显示新的地址
    • 请求次数:2次
    • 根目录:http://localhost:8080/ 没有项目的名字
    • 请求域中的数据会丢失,因为是2次请求

    小结:重定向和转发的区别

    区别 转发forward 重定向sendRedirect
    根目录 包含项目访问地址 没有项目访问地址
    地址栏 不会发生变化 会发生变化
    哪里跳转 服务器端进行的跳转 浏览器端进行的跳转
    请求域中数据 不会丢失 会丢失
    
    //href中的/user/test会跳转到localhost:8888/user/test
    //href中的user/test会跳转到localhost:8888/项目名/user/test
    <a href="user/test">你好</a>
    
    @Controller
    @RequestMapping("/user")
    public class HelloController {
    
        @RequestMapping("/test")
        public void upload1(HttpServletRequest request,HttpServletResponse response) throws IOException {
            //会跳转http://localhost:8888/mvc1/user/success
            //response.sendRedirect("success");
    
            //会跳转到http://localhost:8888/success
            //response.sendRedirect("/success");
    
            //地址栏从index.jsp到http://localhost:8888/mvc1/user/test
            //另外一个例子是web课程中的,这里写/demo2 也会直接调用/项目/demo2的函数
            //request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request, response);
            
            //HTTP Status 404 – 未找到
            //消息/mvc1/user/WEB-INF/pages/success.jsp未找到
            //request.getRequestDispatcher("WEB-INF/pages/success.jsp").forward(request, response);
    
            //重定向是给客户端,需要加虚拟目录
            //转发给服务器端,不需要加虚拟目录
        }
    }
    
    
    @Controller
    @RequestMapping("/user")
    public class HelloController {
        @RequestMapping("/test")
        public void upload1(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
            System.out.println(request.getContextPath()); //打印/mvc1  项目名称
        }
    
    }
    
    @WebServlet("/responseDemo3")
    public class ResponseDemo3 extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
            //转发   这里加不加/都会正确
            request.getRequestDispatcher("/responseDemo2").forward(request,response);
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doPost(request,response);
        }
    }
    












    种一棵树最好的时间是十年前,其次是现在。
  • 相关阅读:
    scrapy框架之comand line tool
    CSS选择器与XPath语言
    Selenium之Web页面滚动条滚操作
    Selenium+Chrome+PhantomJS 爬取淘宝
    爬取今日头条中的图片
    django 和 mongdb 写一个简陋的网址,以及用django内置的分页功能
    charts 画饼图
    charts 画折线图
    oracle的char和varchar类型
    ORA-02049: 超时: 分布式事务处理等待锁的解决方法
  • 原文地址:https://www.cnblogs.com/islch/p/12789468.html
Copyright © 2011-2022 走看看