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

springMVC学习笔记六(注解方式实现控制器)

2014-08-06 14:00 711 查看
=========================注解方式实现控制器===========================

<context:component-scan/>扫描指定包中类上的注解,常用的注解有:

@controller: 声明处理器类

@requestMapping("/menu"):处理器功能方法的映射

@requestParam: 请求参数到处理器处理方法参数上的绑定

@modleAttribute:请求参数到命令对象的绑定

@sessionAttribute: session级别存储的属性

@initBinder:用于将请求参数转换到命令对象属性的对应类型

spring3.0引入restful架构风格支持

@cookieValue:cookies数据到处理器处理方法的方法参数上的绑定

@requestHander:请求头到处理器处理方法的方法参数上的绑定

@requestBody:请求body体的绑定

@responseBody:处理器处理方法的返回值作为响应体

@responseStatus:定义处理器功能处理方法/异常处理器返回的状态码和原因

@exceptionHandler:注解声明异常处理器

@pathVarible:请求 URI 中的模板变量部分到处理器功能处理方法的方法参数上的绑定

Spring3.1 使用新的 HandlerMapping 和 HandlerAdapter 来支持@Contoller 和@RequestMapping注解处理器

@service: 声明service组件

@repository: 声明dao组件

@component: 泛指组件,当不好归类时

@resource:用于注入,按名称装配(@Resource(name="beanName"))

@autowired:用于注入,按类型装配

@transactional(rollbackFor={Exception.class}):事务管理

@responseBody

@scope("prototype"):设定bean的作用域

示程序如下:

@Controller

// 或是@RequestMapping

public class AnnotationHelloWorldController {

@RequestMapping(value = "/annoHello")

public ModelAndView helloWorld() {

// 收集参数,验证参数

// 绑定参数到命令对象

// 将命令传入业务对象进行处理

// 选择下一个界面

ModelAndView mv = new ModelAndView();

mv.addObject("message", "hello world!!!!!");

mv.setViewName("hello");

return mv;

}

}

spring配置文件添加如下:

<!-- 注解 HandlerMapping -->

<bean

class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />

<!-- 注解 HandlerAdapter -->

<bean

class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" />

<!-- 注解方式实现控制器 -->

<bean class="cn.yue.mvc.controller.AnnotationHelloWorldController" />

页面视图/jsp/hello.jsp

<%@ page language="java" pageEncoding="UTF-8"

contentType="text/html; charset=UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<title>Hello World</title>

</head>

<body>${message}

</body>

</html>

-------------------处理器的定义

方式一:

@controller

方式二:

@requestMapping

---------------------窄化请求映射

控制器AnnotationHelloWorldController修改如下:

@Controller

@RequestMapping(value = "/user3")

public class AnnotationHelloWorldController {

@RequestMapping(value = "/annoHello")

public ModelAndView helloWorld() {

// 收集参数,验证参数

// 绑定参数到命令对象

// 将命令传入业务对象进行处理

// 选择下一个界面

ModelAndView mv = new ModelAndView();

mv.addObject("message", "hello world!!!!!");

mv.setViewName("hello");

return mv;

}

}

测试:
http://localhost:8089/user3/annoHello
------------------------请求映射

//

Remote Address:::1:8089

Request URL:http://localhost:8089/user3/annoHello 请求url

Request Method:GET 请求方法

Status Code:200 OK

Request Headersview source //请求头信息

Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

Accept-Encoding:gzip,deflate,sdch

Accept-Language:zh-CN,zh;q=0.8

Cache-Control:max-age=0

Connection:keep-alive

Cookie:JSESSIONID=6D207F75EF61B67C5DBC7D0C15809208

Host:localhost:8089

User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36

-----------------------url路径映射

a 普通url映射

//多个url可以映射同一个路径

@RequestMapping(value={"/user1","/user2"});

b url模板模式映射

@RequestMapping(value="/users/{userId}"):{×××}占位符, 请求的 URL 可以是 “/users/123456”或

“/users/abcd”, 通过@PathVariable 可以提取 URI 模板模式中的{×××}中的×××变量。

@RequestMapping(value="/users/{userId}/create") : 这 样 也 是 可 以 的 , 请 求 的 URL 可 以 是

“/users/123/create”。

@RequestMapping(value="/users/{userId}/topics/{topicId}"):这样也是可以的,请求的 URL 可以是

“/users/123/topics/123”。

c ant风格的url路径映射

@RequestMapping(value="/users/**"):可以匹配“/users/abc/abc”,但“/users/123”将会被【URI模板模式映射

中的“/users/{userId}”模式优先映射到】

@RequestMapping(value="/product?"):可匹配“/product1”或“/producta”,但不匹配“/product”或“/productaa”;

@RequestMapping(value="/product*"):可匹配“/productabc”或“/product”,但不匹配“/productabc/abc”;

@RequestMapping(value="/product/*"):可匹配“/product/abc”,但不匹配“/productabc”;

@RequestMapping(value="/products/**/{productId}"):可匹配“/products/abc/abc/123”或“/products/123”,

Ant风格和URI模板变量风格可混用;

d 正则表达式风格的URL路径映射

@RequestMapping(value="/products/{categoryCode:\\d+}-{pageNumber:\\d+}") : 可 以 匹 配

“/products/123-1”,但不能匹配“/products/abc-1”

e 组合使用或的关系

@RequestMapping(value={"/test1", "/user/create"})

-------------------请求方法映射限定

@Controller

@RequestMapping("/customers/**") //①处理器的通用映射前缀

public class RequestMethodController {

@RequestMapping(value="/create", method = RequestMethod.GET)//类级别的@RequestMapping窄化

public String showForm() {

System.out.println("===============GET");

return "customer/create";

}

@RequestMapping(value="/create", method = RequestMethod.POST)//类级别的@RequestMapping窄化

public String submit() {

System.out.println("================POST");

return "redirect:/success";

}

}

-----------------请求参数数据映射限定

请求数据中有指定参数名

@Controller

@RequestMapping("/parameter1") //①处理器的通用映射前缀

public class RequestParameterController1 {

//②进行类级别的@RequestMapping窄化

@RequestMapping(params="create", method=RequestMethod.GET)

public String showForm() {

System.out.println("===============showForm");

return "parameter/create";

}

//③进行类级别的@RequestMapping窄化

@RequestMapping(params="create", method=RequestMethod.POST)

public String submit() {

System.out.println("================submit");

return "redirect:/success";

}

}

请求数据中没有指定参数名

@RequestMapping(params="!create", method=RequestMethod.GET)

请求数据中指定参数名=值

@RequestMapping(params="submitFlag=create", method=RequestMethod.GET)

请求数据中指定参数名!=值

@RequestMapping(params="submitFlag!=create", method=RequestMethod.GET)

组合使用是“且”的关系

@RequestMapping(params={"test1", "test2=create"})

------------ 请求头映射限定????

-------------生产者和消费者限定

...............................media type

媒体类型格式:type/subtype(;parameter)?

type 主类型,任意的字符串,如 text,如果是*号代表所有;

subtype 子类型,任意的字符串,如 html,如果是*号代表所有;

parameter 可选,一些参数,如 Accept 请求头的 q 参数, Content-Type 的 charset 参数

常见媒体类型:

text/html : HTML 格式

text/plain :纯文本格式

text/xml :XML 格式

image/gif :gif 图片格式

image/jpeg :jpg 图片格式

image/png:png 图片格式

application/x-www-form-urlencoded : <form encType=””>中默认的 encType,form 表单数据被编码为 key/value 格式发

送到服务器(表单默认的提交数据的格式)。

multipart/form-data : 当你需要在表单中进行文件上传时,就需要使用该格式;

application/xhtml+xml :XHTML 格式

application/xml : XML 数据格式

application/atom+xml :Atom XML 聚合格式

application/json : JSON 数据格式

application/pdf :pdf 格式

application/msword : Word 文档格式

application/octet-stream : 二进制流数据(如常见的文件下载)

.........................content-type:请求/响应的内容区数据的媒体类型

请求头的内容类型

@RequestMapping(value = "/request/ContentType", method = RequestMethod.POST,

headers = "Content-Type=application/json")

//客户端发送json数据请求

//请求的地址

String url = "http://localhost:9080/springmvc-chapter6/request/ContentType";

//创建Http Request(内部使用HttpURLConnection)

ClientHttpRequest request =

new SimpleClientHttpRequestFactory().

createRequest(new URI(url), HttpMethod.POST);

//设置请求头的内容类型头和内容编码(GBK)

request.getHeaders().set("Content-Type", "application/json;charset=gbk");

//以GBK编码写出请求内容体

String jsonData = "{\"username\":\"zhang\", \"password\":\"123\"}";

request.getBody().write(jsonData.getBytes("gbk"));

//发送请求并得到响应

ClientHttpResponse response = request.execute();

System.out.println(response.getStatusCode());

响应头的内容类型

@RequestMapping("/response/ContentType")

public void response1(HttpServletResponse response) throws IOException {

//表示响应的内容区数据的媒体类型为html格式,且编码为utf-8(客户端应该以utf-8解码)

response.setContentType("text/html;charset=utf-8");

//写出响应体内容

response.getWriter().write("<font style='color:red'>hello</font>"); }

.....................accept:指定什么类型的响应是可以接受的

json数据

服务端控制器

@RequestMapping(value = "/response/ContentType", headers = "Accept=application/json")

客户端接收服务端数据

需要把请求头Accept改为“Accept=application/json”

xml数据

服务端控制器

@RequestMapping(value = "/response/ContentType", headers = "Accept=application/xml")

客户端接收服务端数据

需要把请求头Accept改为“Accept=application/xml”

生产者和消费者的限定

<!-- HandlerMapping -->

<bean

class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>

<!-- HandlerAdapter -->

<bean

class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>

当功能处理方法是消费者时

@RequestMapping(value = "/consumes", consumes = {"application/json"}):

当功能处理方法是生产者时

@RequestMapping(value = "/produces", produces = "application/json")

窄化时是覆盖而不是继承

类级别 @RequestMapping(value="/narrow", produces="text/html")

方法级别@RequestMapping(produces="application/xml")

此时方法级别将覆盖类级别

组合使用是“或”的关系

@RequestMapping(produces={"text/html", "application/json"})

数据绑定

功能处理方法支持的数据类型

ServletRequest/HttpServletRequest 和 ServletResponse/HttpServletResponse

InputStream/OutputStream 和 Reader/Writer

WebRequest/NativeWebRequest

HttpSession

命令/表单对象

Model、Map、ModelMap

Errors/BindingResult

Locale /Principal

@requestParam绑定单个请求参数

注:右击项目,选择“属性”,打开“属性对话框”,选择“Java Compiler”然后再打开的选项卡将“Add

variable attributes to generated class files”取消勾选,意思是不将局部变量信息添加到类文件中

功能:

将请求参数区数据映射到功能处理方法的参数上

示例代码如下:

@RequestParam(value="username", required=true, defaultValue="zhang") String username)

参数:

value:参数名

required:请求中是否一定要有相应的参数,默认为false

defaultValue:请求中没有同名参数时的默认值

@requestHeader绑定请求头数据

功能:

将请求头信息区数据映射到功能处理方法的参数上

示例代码如下:

@RequestHeader("User-Agent") String userAent,

@RequestHeader(value="Accept") String[] accepts)

@modelAttribute绑定请求参数到命令对象

功能:

a 绑定请求参数到命令对象

//可以在视图页面使用${user.username}来获取绑定的命令对象的属性。

public String test1(@ModelAttribute("user") UserModel user)

b 暴露表单引用对象为模型数据

@ModelAttribute("cityList")

public List<String> cityList() {

return Arrays.asList("北京", "山东");

}

c 暴露@requestMapping方法返回值为模型数据

public @ModelAttribute("user2") UserModel test3(@ModelAttribute("user2") UserModel user)

匿名绑定命令参数

public @ModelAttribute List<UserModel> test()

@sessionAttributes绑定到命令对象session

@value绑定spEL表达式

public String test(@Value("#{systemProperties['java.vm.version']}") String jvmVersion)

参考:http://jinnianshilongnian.iteye.com/blog/1752171
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: