springmvc笔记-2-注解

1.@Controller
2.@RequestMapping
3.@RequestParam
4.@PathVariable
5.@RequestHeader
6.@CookieValue
7.@SessionAttributes
8.@ModelAttribute
9.@RequestBody
10.@ResponseBody
暂时没有弄得:
了解springmvc的各个组件
自定义HttpMessageConverter传递和接受json,xml用的不多也没有看(p63)

@Controller:将类标识为Controller控制器
需要

    
    <context:component-scan base-package="com.**">context:component-scan>
    
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">bean>
    
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">bean>

处理request body部分注解:@RequestParam,@RequestBody
处理request uri部分注解:@PathVariable
处理request header部分注解:@RequestHeader,@CookieValue
处理attribute类型的注解:@SessionAttributes,@ModelAttribute


@RequestMapping(org.springframework.web.bind.annotation.RequestMapping)
指示springmvc用哪一个类或方法来处理请求动作,该注解可用于类或方法。

如果放在类上面,进过测试如果在springmvc的配置文件中配置xml类型的Controller时,注解方式和xml配置方式会有冲突

代码案例:
下面进入hello方法对应的url是:localhost:8080/项目名称/aa/hello

@Controller
@RequestMapping(value="aa")
public class HelloController {
    @RequestMapping(value="/hello")
    public ModelAndView hello() {
        // 配置准备返回的ModeAndView对象,该对象通常包含了返回视图名,模型的名称,以及模型的对象
        ModelAndView mv = new ModelAndView();
        // 添加模型数据,可以是任意类型的对象
        mv.addObject("message", "Hello World!");
        // 设置视图名,配合springmvcNote1-servlet.xml中的视图解析器,合成指向/WEB-INF/jsp/test.jsp页面
        mv.setViewName("test");
        return mv;
    }
}



springmvc笔记-2-注解_第1张图片

value:对应url的映射
method:对应url的请求方式
consumes:指定处理请求的提交内容类型
produces:指定返回的内容类型
params:该属性指定request中必须包含某些参数值是,才让该方法处理
headers:该属性指定request中必须包含某些指定的header值,才能让该方法处理


部分配置案例:

@RequestMapping(value="/hello",method={RequestMethod.GET,RequestMethod.POST},consumes="application/json",produces="application/json",params="name=caoxuekun")

测试案例
要想进入hello方法,必须满足url为:http://localhost:8080/springmvcNote1/aa/hello?name=caoxuekun
也可以是post方式访问,但必须带有参数name的值为caoxuekun

@Controller
@RequestMapping(value="aa")
public class HelloController {
    @RequestMapping(value="/hello",method={RequestMethod.GET,RequestMethod.POST},params="name=caoxuekun")
    public ModelAndView hello() {
        return null;
    }
}

如果在处理方法上需要访问HttpServletRequest,HttpServletResponse,HttpSession对象,可以在处理方法的参数中添加
eg:

@RequestMapping(value="/hello")
    public ModelAndView hello(HttpServletRequest request,HttpSession session,HttpServletResponse response){
        return null;
    }



对于mvc框架,控制器(Controller)执行业务逻辑,用于产生模型数据Model,而视图View则用于渲染模型数据
springmvc提供了Model,ModelMap,ModelAndView,@ModelAttribute,@SessionAttributes输出模型数据


Model/ModelMap:
index.jsp页面代码

    
"test02"> type="text" name="name"/> type="text" name="password"/> type="submit" value="test02提交"/>

对应Controller方法代码

    /* * Model功能类似Map,键值对,和ModelMap一样 * 先访问:http://localhost:8080/springmvcNote1/modelandview/index * 在test02提交后,在访问 * http://localhost:8080/springmvcNote1/modelandview/test03 * 每次访问都会从新创建一个Model */
    @RequestMapping("/test02")
    public String test02(Model model,String name,String password){
        User user = new User();
        user.setName(name);
        user.setPassword(password);
        model.addAttribute("depositUser",user);
        System.out.println("将对象存入到model中,键名为:depositUser");
        System.out.println(model);
        return "test02";

    }
    @RequestMapping("/test03")
    public void test03(Model model){
        //从model中取出之前存入model中键位depositUser的对象,每次访问都会从新创建一个Model,所以无法出去
        User uu = (User) model.asMap().get("depositUser");
// User uu = (User) model.get("depositUser");
        System.out.println(uu.getName()+"=sdfssss==="+uu.getPassword());
    }

test02.jsp代码

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title heretitle>
head>
<body>
    ${depositUser.name }
body>
html>



ModelAndView:可以配置模型和视图名称
Controller对应的方法

//org.springframework.web.servlet.ModelAndView;
    @RequestMapping("/test04")
    public ModelAndView test04(String name,String password,ModelAndView mv){
// ModelAndView mv = new ModelAndView();
        User user = new User();
        user.setName(name);
        user.setPassword(password);
        mv.addObject(user);
        mv.setViewName("test04");
        return mv;
    }

test04.jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title heretitle>
head>
<body>
    ${user.name }
body>
html>



参数绑定
@RequestParam:传入的参数赋值个方法中对应的参数
springmvc笔记-2-注解_第2张图片

@RequestMapping("/test05")
public void test05(
    @RequestParam("name") String name,
    @RequestParam(value="password",required=true,defaultValue="caoxuekun") String password){
        //required=true是默认值
        System.out.println(name+"*****"+password);
    }



@PathVariable:获取URL的动态参数

    @RequestMapping("/test06/{number}")
    public void test06(@PathVariable String number){
        System.out.println(number);
    }



@RequestHeader:将请求头信息映射到处理方法的参数上
springmvc笔记-2-注解_第3张图片

    @RequestMapping("test07")
    public void test07(@RequestHeader("User-Agent") String userAgent,
            @RequestHeader(value="Accept") String[] accepts){
        System.out.println(userAgent);
        for(String s:accepts){
            System.out.println(s);
        }
    }



@CookieValue:将cookie的数据映射到处理方法的参数上
springmvc笔记-2-注解_第4张图片

    @RequestMapping("test08")
    public void test08(@CookieValue(value="JSESSIONID",defaultValue="") String sessionId){
        //会自动将JSESSIONID赋给sessionId
        //defaultValue=""表示cookie中没有JSESSIONID值时,将sessionId的值设为""
        System.out.println(sessionId);
    }


@SessionAttributes:允许我们有选择的指定Model中那些信息需要转存到HttpSession中(该方法只能用在类注解上)
springmvc笔记-2-注解_第5张图片

@SessionAttributes("user")
public class ModelAndViewTest 

此时如果在方法中model.addAttribute(user);那么user会存入HttpSession中


@ModelAttribute:将参数请求绑定到处理方法的参数上

    @ModelAttribute
    @RequestMapping("/test01")
    public void test01(String name,String password){
        //@ModelAttribute会先于/test01调用将index.jsp页面中有传入的参数name,和password
        //赋值给test01(String name,String password)
        //也可以不要@ModelAttribute这个注解
        System.out.println(name+"==="+password);
    }



信息转换
HttpMessageConverter可以将请求信息转换为对象,并将对象(类型为T)绑定到请求方法的参数中,或将对象转换为响应信息。(暂时了解到这里)

下面的实体类的共用
json数据转java对象,对象转json,对应的类必须序列化: Book implements Serializable

package com.entity;

import java.io.Serializable;

public class Book implements Serializable{
    private Integer id;
    private String name;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}

@RequestBody:利用ajax传输json格式数据,并将数据封装到对应的类的属性中
需要json放方面的jar包
jackson-annotations-2.6.0-rc4.jar
jackson-core-2.6.0-rc4.jar
jackson-core-asl-1.9.7.jar
jackson-core-lgpl-1.9.7.jar
jackson-databind-2.6.0-rc4.jar

ajax代码:

 **contentType:"application/json;charset=utf-8":发送信息至服务器时的内容编码类型**
$.ajax({
                url:"test09",
                dataType : "json", // 预期服务器返回的数据类型。
                type : "post", // 请求方式 POST或GET
                //发送信息至服务器时的内容编码类型
               contentType:"application/json;charset=utf-8", 
               // 发送到服务器的数据。
               data:JSON.stringify({id : 1, name : "SpringmvcNode1"}),
               async:  true , // 默认设置下,所有请求均为异步请求。如果设置为false,则发送同步请求
               // 请求成功后的回调函数。
                success:function(data){
                    alert(data);
                }
            });

xml配置


    <mvc:annotation-driven /> 

会自动注册RequestMappingHandlerMapping与RequestMappingHandlerAdapter两个bean, 这是springmvc为@Controllers分发请求所必须的,并提供了数据绑定支持@NumberFormatannotation,@DateTimeFormat,@Valid,读写XML,和读写JSON

@RequestBody注解会将ajax传递过来的数据:{id : 1, name : “SpringmvcNode1”}
封装到Book对象的属性中
springmvc代码

    @RequestMapping(value="/test09",method={RequestMethod.POST,RequestMethod.GET})
    public void test09(@RequestBody Book code,HttpServletResponse response)throws Exception{
        System.out.println("test09进入"+code.getName());//
        //ObjectMapper是Jackson的主要类,功能是将java对象转换成json格式数据
        ObjectMapper om = new ObjectMapper();
        //设置编码类型和输出格式
        response.setContentType("text/html;charset=UTF-8");
        //输出json数据类型到ajax
        response.getWriter().println(om.writeValueAsString(code));
    }

**//输出json数据类型到ajax
response.getWriter().println(om.writeValueAsString(code));**

@ResponseBody用在方法上时,可以将对象返回为json格式

    @RequestMapping("/test10")
    @ResponseBody
    public Object test10(){
        System.out.println("+++++++++++");
        List books = new ArrayList<>();
        Book b1 = new Book();
        b1.setId(1);
        b1.setName("caoxuekun");
        Book b2 = new Book();
        b2.setId(2);
        b2.setName("曹雪坤");
        books.add(b1);
        books.add(b2);
        return books;
    }

对应的ajax

        $("#test10Ajax").click(function(){
            alert();
            $.ajax({
                url:"test10",
                dataType : "json", // 预期服务器返回的数据类型。
                type : "post", // 请求方式 POST或GET
               // 请求成功后的回调函数。
                success:function(data){
                    var date = JSON.stringify(data);
                    alert(date);
                }
            });
        });

map方面暂时没弄出来

你可能感兴趣的:(springmvc)