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>
  • 相关阅读:
    解决 下载 CM-12.0 源代码出现 Fatal: duplicate project .....问题
    解决Centos 7 dhcp服务器-no subnet declaration for start (no IPV4 addresses.)
    pgAdmin III 是 postgresql 的管理工具
    Ubuntu PostgreSQL安装和配置
    redis三种连接方式
    Delphi中Interface接口的使用方法
    解决lazarus 多线程报错问题
    Ubuntu安装UFW防火墙
    lazarus安装
    Ubuntu 虚拟机增强包下载
  • 原文地址:https://www.cnblogs.com/XSdao/p/11212790.html
Copyright © 2011-2022 走看看