springmvc重定向到另一个项目_关于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;

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

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

欢迎来到技术之家,

如需转载,烦请保留本文链接和出处:http://www.jszja.com/contents/14/1222.html

您的支持将是我们前进的动力!如对本篇文章有疑问或建议,请通过本站下方邮箱联系我们,让技术之家每天进步一点点!(●'◡'●)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值