SpringMVC使用进阶-内置对象和跳转

内置对象和页面跳转是web开发中比较重要的组成部分,springmvc作为新生代的框架,对这方面的支持也还算不错,这次着重分享跳转方式和内置对象的使用

一   页面跳转

页面跳转分为客户端跳转和服务端跳转两种,在springmvc中使用跳转是比较简单的,只需在return后面写就可以了

(1)客户端跳转

return "redirect:user.do?method=reg5";  
return "redirect:http://www.baidu.com"; 

(2)服务端跳转
return "forward:index.jsp";
return "forward:user.do?method=reg5"; 


二  内置对象

springmvc中也可以像servlet那样使用内置对象,同时也有自己独立的写法,先来看看springmvc中运用传统方式使用内置对象

@RequestMapping(params="method=reg2")
public String reg2(String uname,HttpServletRequest req,ModelMap map){
		req.setAttribute("a", "aa");
		req.getSession().setAttribute("b", "bb");
		return "index";
}

这段代码和servlet比较类似,但是springmvc的写法就更简单,如下所示

ModelMap 和request内置对象的功能一致

@SessionAttributes      看名字就可以看出这个注解和session有关,主要用于ModelMap中指定的属性放到session,可以参照下面的事例代码

@Controller
@RequestMapping("/user.do")
@SessionAttributes({"u","a"})   //将ModelMap中属性名字为u、a的再放入session中。这样,request和session中都有了。
public class UserController  {
	@RequestMapping(params="method=reg4")
	public String reg4(ModelMap map) {  		System.out.println("HelloController.handleRequest()");
		map.addAttribute("u","uuuu");  //将u放入request作用域中,这样转发页面也可以取到这个数据。
		return "index";
	}
}

@ModelAttribute  这个注解可以和@SessionAttribute配合使用,可以将ModelMap中属性的值通过该注解自动赋给指定变量

如下所示

@RequestMapping(params="method=reg5")
public String reg5(@ModelAttribute("u")String uname,ModelMap map) { //[将属性u的值赋给形参uname]
		System.out.println("HelloController.handleRequest()");
		System.out.println(uname); 
		return "index";
}


最后总结一下ModelAndView模型视图类,见名知意,从名字上我们可以知道ModelAndView中的Model代表模型,View代表视图。即,这个类把要显示的数据存储到了Model属性中,要跳转的视图信息存储到了view属性。但是常规情况下一般是返回字符串。为了看得更明白我也把使用ModelAndView方式返回页面的代码贴出来。


@RequestMapping(params="method=login3")
public ModelAndView login3(){
		ModelAndView mv=new ModelAndView();
		mv.setViewName("index2");
		return mv;
}


是不是都很简单呢,下次打算分享的内容是springmvc文件上传。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值