SpringMVC基本注解的介绍

来源:互联网 发布:公文的阅知范围体现在 编辑:程序博客网 时间:2024/04/30 12:34


@Controll    //声明需扫描的类,这个注解主要为了,你发起请求的时候,可以从这个类中去找应该访问那个方法@RequestMapping("/user")     //相当于@RequestMapping(value="/user") ,这个类先拦截比如: xxx/项目名字/user/xxx,项目名字后面是user的请求@SessionAttriutes("user")    /* 相当于@SessionAttriutes(value="user"),这个是如果你model里面 ,比如model.addAttribute("user",user);添加到了model对象里面, 然后你就可以通过HttpSession对象的getAttribute("user"),去取出来这个对象,也可以设置多个对象到HttpSession中,比如,
 @SessionAttributes(types={User.class,Student.class},value{"user","student"}) */public class TestControl{@ModelAttribute("loginCheck")      //这个注解只支持一个属性value,这个方法回在你执行Controller每个方法前被执行,因此在一个的Controller映射到多个url上时候,要谨慎使用public void userModel1(User user,Model model){/*接受的user对象放入model中,然后在你@RequestMapping("loginCheck")这个注解的方法哪里可以通过model对象获取到值,看下面演示 */model.addObject("user",user);    }@RequestMapping("loginCheck")public ModelAndView userModel2(Model model,HttpSession session){ /*因为在执行@RequestMapping("loginCheck")前已经先走了@ModelAttribute("loginCheck")  所以Model中就有了值了 ,并且因为类上面有了@SessionAttributes("user"),所以你往model中放入user键的时候,HttpSession中也就有了值了,也就可以通过session.getAttribute("user") 去获取值*/User user=(User)model.asMap().get("user"); //通过session去取值User user2=(User)session.getAttribute("user");ModelAndView m2=new ModelAndView();m2.setView(user);m2.setViewName("success.jsp");return m2;}@RequestMapping("pageing/{pageNumber}")public void userModel3(/* @pathVariable会获取你请求最路径的的那个值放入注解的这个pageNumber变量中,比如请求    xxxx/user/pageing/100, 然后就会把100这个值放入注解声明的这个变量里面,前提你发送的请求能到这里才可以(到user/pageing这个路径下才行),注解的参数名字一定和上面mapping中的参数名字一致才可以,一般分页会用这种方式*/@PathVariable int pageNumber){ System.out.println(pageNumber);}@RequestMapping("login4")public void userModel4(/* @RequestParam注解会把你请求带的id值放入到这个注解的变量当中,但不会影响你把id放入但user下*/@RequestParam int id,User user){ System.out.println(pageNumber);}/* 在写下一个方法前说明一下,在前台用get或者post请求提交数据的时候,数据编码格式由请求头的ContentType指定,分为下面几种情况1. application/x-www-form-urlencoded,这种情况的数据,@RequestParam,@ModelAttribute也可以处理,并且很方便,当然@RequestBody也能处理2.multipart/form-data, @RequestBody 不能处理这种格式的数据,这种数据一般是上传文件才会指定的类型3.application/json application/xml 等格式的数据,必须使用@RequestBody来处理,实际开发中可以使用@RequestBody注解可以很方便的处理JSON格式的数据*//* 比如,前台ajax请求,如果contentType:“application/json”, data:JSON.stringify({id:1,name:"小明"}),contentType是json数据类型,并且传过来的是json字符串 */@RequestMapping("ajaxRequestTest")public void setJson(    //方法的括号之间传的是方法的参数,中间用逗号隔开//@RequestBody会根据json数据,转化成对象的Object,也就是说会把json里面的数据放入user对象当中@RequestBody User user,HttpServletResponse response){//测试有没有把json数据放入对象System.out.println(user.getId());System.out.println(user.getName());response.setContentType("text/html;charset=utf-8");response.getWriter().print("{msg:\"测试成功,这个是返回给ajax的数据\"}");}}