您的位置:首页 > 编程语言 > Java开发

spring mvc注解

2015-12-25 17:27 267 查看

1.1. Spring mvc注解优化

<!-- AnnotationMethodHandlerAdapter 是方法映射的,不同方法有不同url请求,在类找方法。

2)DefaultAnnotationHandlerMapping

DefaultAnnotationHandlerMapping根据扫描的包下面找类,即通过url找类 -->

<bean

class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean>

<bean

class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean>

可以简化为

<mvc:annotation-driven/>

1.2. @Controller

用来注释一个类,表明这个类是一个控制器,用来处理请求。

1.3. @RequestMapping

1.3.1. @RequestMapping注释类

表示这个类下所有的请求都会在这个路径下

1.3.2. @RequestMapping注释方法

1. 基本用法

@RequestMapping(value="/departments")

//等价于@RequestMapping(“/departments")

//字符串中的斜杠也可以省略

public String simplePattern(){

System.out.println("simplePattern method was called");

return "someResult";

}

2. 指定RequestMethod.POST

@RequestMapping(value="/hello",method=RequestMethod.POST)

3. 指定http请求头

@RequestMapping(value = "/foos", headers = "key=val")

4. consumes,produces;

consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;

produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;

1.4. Requestparam

@RequestMapping("deleteUser")

public void deleteUser(@RequestParam int id){

}

请求可以为http://localhost:8080/spring-mvc/bars?id=100

1.5. @ModelAttribute

1.5.1. @ModelAttribute注释方法

被@ModelAttribute注释的方法会在此controller每个方法执行前被执行,因此对于一个controller映射多个URL的用法来说,要谨慎使用。

@ModelAttribute注释一个void方法

可以用来从数据库准备数据显示到页面上

@ModelAttribute注释一个具体类方法

可以用来直接绑定数据到页面上,绑定参数的名字为类名的小写

@ModelAttribute指定value值

可以指定传到页面上参数值

1.6. @SessionAttribute

将modelMap中的属性放入session中
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: