springMVC轉發與重定向


  SpringMvc請求方式分為轉發、重定向兩種,是用forward和redirect關鍵字在controller層進行處理。

  下面代碼實現了這兩種不同的請求方式:

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class HelloController {
    
    /**
     * 轉發形式
     * @param name
     * @param model
     * @return
     */
    @RequestMapping("/helloForward")
    public String helloForward(@RequestParam(value="name", required=false, defaultValue="World2017") String name, Model model) {
        model.addAttribute("name", name);
        return "hello";
    }
    
    
    
    @RequestMapping("/hello")
    public String hello() {        
        return "hello";       
    }
    
    /**
     * 使用RedirectAttributes類
     * @param name
     * @param redirectAttributes
     * @return
     */
    @RequestMapping("/helloRedirect")
    public String helloRedirect(@RequestParam(value="name", required=false ) String name, RedirectAttributes redirectAttributes) {
       
        redirectAttributes.addFlashAttribute("name", name);
        
        return "redirect:/hello";
    }
    
    
    @RequestMapping("/hello2")
    public String hello2(Model model,HttpServletRequest request) {
        
        HttpSession session = request.getSession();
        model.addAttribute("name",session.getAttribute("name"));
        return "hello";      
    }
    
    /**
     * 常規做法,重定向之前把參數放進Session中,在重定向之后的controller中把參數從Session中取出並放進ModelAndView
     * @param name
     * @param request
     * @return
     */
    @RequestMapping("/helloRedirect2")
    public String helloRedirect2(@RequestParam(value="name", required=false ) String name, HttpServletRequest request) {
       
        request.getSession().setAttribute("name", name);
        
        return "redirect:/hello2";
    }
    
    
}

  在使用redirect進行重定向時請求的URL鏈接發生了改變,並且在controller中如果像reward一樣 model.addAttribute("name", name)放置的參數,重定向之后是無法獲取到的,所以重定向需要另外的方式進行參數的傳遞,上面的程序介紹了兩種重定向傳參的方式:

  ①、重定向之前把參數放進Session中,在重定向之后的controller中把參數從Session中取出並放進ModelAndView

  ②、使用RedirectAttributes類,這種實現方式比較簡單。

 

 

  再總結一下servlet中轉發request.getRequestDispatcher().forward()和重定向response.sendRedirect()的區別:

  ①、轉發是一次請求,一次響應,而重定向是兩次請求,兩次響應

  ②、轉發:servlet和jsp共享一個request,重定向:兩次請求request獨立,所以前面request里面setAttribute()的任何東西,在后面的request里面都獲取不到

  ③、轉發:地址欄不會改變,重定向:地址欄發生變化。

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM