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(重定向)。html

  

 

(1)若是是轉發、重定向到本controller的其它業務方法:web

  • 能夠寫全路徑
return "forward:/userController/handler2";

 

  • 也能夠只寫子路徑,但不要子路徑開頭的斜槓

     無論handler2()是標註爲@RequestMapping("/handler2"),仍是標註爲@RequestMapping("handler2"),都只能這樣:spring

return "forward:handler2";

 

 

(2)若是是轉發、重定向到其它controller的業務方法,只能寫全路徑。mvc

 

 


 

 

轉發、重定向到視圖

springmvc原本就會把返回的字符串做爲視圖名解析,而後轉發到對應的視圖。app

 

轉發有2種方式:jsp

  • 不使用關鍵字forward,能夠使用視圖解析器
  • 使用關鍵字forward,但只能寫全路徑

 

重定向:spa

  • 使用關鍵字redirect,只能寫全路徑

 

由於使用關鍵字forward、redirect時,SpringMVC不會使用視圖解析器來解析視圖名,也就不能使用視圖名拼接,只能寫全路徑。code

 

 

示例

在web文件夾下新建1.jsphtm

return "redirect:/1.jsp";

/表示web文件夾根目錄。blog

 

能夠轉發、重定向到html這種靜態頁面,也能夠轉發、重定向到WEB-INF下的頁面,但須要配置資源,

參考:http://www.javashuo.com/article/p-qgcprrlt-o.html

 

 


  

 

固然,也能夠使用servlet的方式來實現:

  • 傳入HttpServletRequest | HttpServletResponse類型的參數。
相關文章
相關標籤/搜索