SpringMVC 转发、重定向

 

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

@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,可以使用视图解析器
  • 使用关键字forward,但只能写全路径

 

重定向:

  • 使用关键字redirect,只能写全路径

 

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

 

 

示例

在web文件夹下新建1.jsp

return "redirect:/1.jsp";

/表示web文件夹根目录。

 

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

参考:https://www.cnblogs.com/chy18883701161/p/12249175.html

 

 


  

 

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

  • 传入HttpServletRequest | HttpServletResponse类型的参数。

 

posted @ 2020-02-01 14:57  chy_18883701161  阅读(765)  评论(0编辑  收藏  举报