# Redirect

## redirect重定向流程

參考資料:(<http://www.51gjie.com/javaweb/955.html>)

客戶發送一個請求到服務器，服務器匹配servlet，這都和請求轉發一樣，servlet處理完之後調用了sendRedirect()這個方法，這個方法是response的方法，所以，當這個servlet處理完之後，看到response. senRedirect()方法，立即向客戶端返回這個響應，響應行告訴客戶端你必須要再發送一個請求，去訪問test.jsp，緊接著客戶端受到這個請求後，立刻發出一個新的請求，去請求test.jsp,這裡兩個請求互不干擾，相互獨立，在前面request裡面setAttribute()的任何東西，在後面的request裡面都獲得不了。可見，在sendRedirect()裡面是兩個請求，兩個響應。

### response.sendRedirect重定向跳轉

```
@RequestMapping(value="/testredirect",method = { RequestMethod.POST, RequestMethod.GET })  
public ModelAndView testredirect(HttpServletResponse response){  
    response.sendRedirect("/index");
    return null; 
}
```

### ViewResolver直接跳轉

```
@RequestMapping(value="/testredirect",method = { RequestMethod.POST, RequestMethod.GET })  
public  String testredirect(HttpServletResponse response){  
    return "redirect:/index";  
} 
```

#### 帶參數

```
@RequestMapping("/testredirect")
public String testredirect(Model model, RedirectAttributes attr) {
    //跳轉地址帶上test參數
    attr.addFlashAttribute("test", "51gjie");
    //u2參數不會跟隨在URL後面
    attr.addFlashAttribute("u2", "51gjie");
	  return "redirect:/user/users";
}
```

### ModelAndView重定向

```
@RequestMapping(value="/restredirect",method = {RequestMethod.POST, RequestMethod.GET})  
public ModelAndView restredirect(String userName){  
    ModelAndView model = new ModelAndView("redirect:/main/index");    
    return model;  
}
```

#### 帶參數

```
@RequestMapping(value="/toredirect",method = {RequestMethod.POST, RequestMethod.GET})  
public ModelAndView toredirect(String userName){  
    ModelAndView model = new ModelAndView("/main/index");   
    //把userName參數帶入到控制器的RedirectAttributes
    model.addObject("userName", userName);  
    return model;  
}
```

### 總結

1\. redirect重定向可以跳轉到任意服務器，可以用在系統間的跳轉。

2\. Spring MVC中redirect重定向，參數傳遞可以直接拼接url也可以使用RedirectAttributes來處理，由於是不同的請求，重定向傳遞的參數會在地址欄顯示，所以傳遞時要對中文編碼進行處理。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://brianwu.gitbook.io/brian/java/spring/redirect.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
