SpringMVC 转发、重定向

时间:2020-02-01 16:24:22   收藏:0   阅读:50

 

转发、重定向到其它业务方法

@org.springframework.stereotype.Controller
@RequestMapping("/userController")
public class UserController{

    @RequestMapping("/handler1")
    public String handler1() throws IOException {
        //转发给handler2处理
        return "forward:handler2";
    }

    @RequestMapping("/handler2")
    public void handler2(HttpServletResponse response) throws IOException {
       //......
    }

}

返回String,在里面加上关键字:forward(转发),redirect(重定向)。

  

 

(1)如果是转发、重定向到本controller的其它业务方法:

return "forward:/userController/handler2";

 

     不管handler2()是标注为@RequestMapping("/handler2"),还是标注为@RequestMapping("handler2"),都只能这样:

return "forward:handler2";

 

 

(2)如果是转发、重定向到其它controller的业务方法,只能写全路径。

 

 


 

 

转发、重定向到视图

springmvc本来就会把返回的字符串作为视图名解析,然后转发到对应的视图。

 

转发有2种方式:

 

重定向:

 

因为使用关键字forward、redirect时,SpringMVC不会使用视图解析器来解析视图名,也就不能使用视图名拼接,只能写全路径。

 

 

示例

在web文件夹下新建1.jsp

return "redirect:/1.jsp";

/表示web文件夹根目录。

 

可以转发、重定向到html这种静态页面,也可以转发、重定向到WEB-INF下的页面,但需要配置资源,不然会出错,

参考:

 

 


 

 

 

当然,也可以使用servlet的方式来实现:

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!