zoukankan      html  css  js  c++  java
  • SpringMVC返回void的三大方法

    知识共享许可协议 版权声明:署名,允许他人基于本文进行创作,且必须基于与原先许可协议相同的许可协议分发本文 (Creative Commons

    在是springMVC的void的返回值中,有三大方法可以运行,个人觉得比较好运用。

    第一种:请求转发的页面

     @RequestMapping("/testVoid")
        public void testVoid(HttpServletRequest request, HttpServletResponse response){
            //请求转发的页面
            try {
                request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("执行了...");
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    这是常见的一种方式,当目标页面在/WEB-INF文件夹下面,就可以通过请求转发的页面 。

    第二种:重定向

     @RequestMapping("/testVoid2")
        public void testVoid2(HttpServletRequest request ,HttpServletResponse response){
            //重定向
            try {
                response.sendRedirect(request.getContextPath()+"/index.jsp");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    有时候在请求页面的时候,采用重定向是非常有必要的,重定向需要,处理掉原来的界面,重定向时需要拼接路径。

    第三种:直接响应

    @RequestMapping("/testVoid3")
        public void testVoid3(HttpServletRequest request ,HttpServletResponse response){
            //解决乱码
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");
            try {
                //响应
                response.getWriter().write("hello");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    这个效果就是在浏览器中输入指定的路径,就会把值传入到页面中。

    实际情况开发就根据自己需求来用相应的方法。

                                    </div>
                <link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-e44c3c0e64.css" rel="stylesheet">
                    </div>
  • 相关阅读:
    toj 2975 Encription
    poj 1797 Heavy Transportation
    toj 2971 Rotating Numbers
    zoj 2281 Way to Freedom
    toj 2483 Nasty Hacks
    toj 2972 MOVING DHAKA
    toj 2696 Collecting Beepers
    toj 2970 Hackle Number
    toj 2485 Card Tric
    js页面定位,相关几个属性
  • 原文地址:https://www.cnblogs.com/XSdao/p/11212790.html
Copyright © 2011-2022 走看看