spring mvc怎么重定向

2025-04-07 17:45:52
推荐回答(2个)
回答1:

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;

@Controllerpublic 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里面都获取不到

③、转发:地址栏不会改变,重定向:地址栏发生变化。

回答2:

(1)转发:在返回值前面加"forward:",比如"forward:user.go?name=1"

(2)重定向:在返回值前面加"redirect:",比如"redirect:user.go"