@Controller注解
@Controller注解是在Spring的org.springframework.stereotype包下,org.springframework.stereotype.Controller注解类型用于指示Spring类的实例是一个控制器,使用@Controller注解的类不需要继承特定的父类或者实现特定的接口,相对之前的版本实现Controller接口变的更加简单。而Controller接口的实现类只能处理一个单一的请求动作,而@Controller注解注解的控制器可以同时支持处理多个请求动作,使程序开发变的更加灵活。
@Controller用户标记一个类,使用它标记的类就是一个Spring MVC Controller对象,即:一个控制器类。Spring使用扫描机制查找应用程序中所有基于注解的控制器类,分发处理器会扫描使用了该注解的方法,并检测该方法是否使用了@RequestMapping注解,而使用@RequestMapping注解的方法才是真正处理请求的处理器。为了保证Spring能找到控制器,我们需要完成两件事:
- 在Spring MVC的配置文件中的头部引入spring-context;
- 使用 context:component-scan/元素,该元素的功能是:启动包扫描功能,以便注册带有@Controller、@Service、@repository、@Component等注解的类成为Spring的Bean。配置文件如下所示:
<!-- spring可以自动去扫描base-pack下面的包或者子包下面的java文件,如果扫描到有Spring的相关注解的类,则把这些类注册为Spring的bean -->
<context:component-scan base-package="com.gxy.controller"/>
@RequestMapping注解
Spring MVC中用于参数绑定的注解有很多,都在org.springframework.web.bind.annotation包中,根据它们处理的request的不同内容可以分为四类(常用的类型)。
第一类:处理request body部分的注解有:@RequestParam和@RequestBody
第二类:处理requet uri部分的注解有:@PathVaribale
第三类:处理request header部分的注解有:@RequestHeader和@CookieValue
第四类:处理attribute类型的注解有:@SessionAttributes和@MoelAttribute
@RequestMapping注解类
1、RequestMapping注解类的属性
RequestMapping注解类的属性,分别有 value, method, consumes, produces, params, headers
- value属性 • 代表具体的请求路径,比如上面的 “/home”, “/index"都是value的值 value可以省略,就像例子中一样,直接用 @RequestMapping(”/home")
的格式,它等同于@RequestMapping(value = “/home”) - method属性 • 指定请求的method类型, GET、POST、PUT、DELETE等:
例:@RequestMapping(value = “/login”, method = RequestMethod.POST)那么只有发送POST请求才会触发这个方法
它的值既可以是字符串也可以是数组: 例:@RequestMapping(value = “/login”, method = {RequestMethod.POST, RequestMethod.GET}) - consumes属性 • 指定请求的提交内容类型(Content-Type),例如application/json, text/html
例:@RequestMapping(value = “/login”, consumes = “application/json”)
它的值既可以是字符串也可以是数组 例:@RequestMapping(value = “/login”, consumes =
{“application/json”, “text/html”}) - produces属性 • 指定返回的内容的类型(Content-Type),例如application/json, text/html
例:@RequestMapping(value = “/login”, produces = “application/json”)
它的值既可以是字符串也可以是数组 例:@RequestMapping(value = “/login”, produces =
{“application/json”, “text/html”}) - params属性 • 指定请求中必须包含某些参数值,才会触发这个处理方法 例:@RequestMapping(value =
“/login”, params = “id=1”)
参数中除了使用=等号外,还可以使用!=号,表示在参数的值不等于的情况下触发这个方法 例:@RequestMapping(value =
“/login”, params = {“id=1”,“age!=18”}) • 也可以不指定具体的值,直接使用
“paramName” 的格式,代表请求中必须包含参数名为 paramName 的参数
• 直接使用“!paramName”格式表示请求不能包含名为paramName的请求参数 - headers属性
请求头Header中必须包含某些指定的参数值,才能让该方法处理请求,可以利用这个特性拒绝非指定来源的客户端的访问,以加强站点的安全。
例:@RequestMapping(value = “/login”, headers = “content-type=text/")
例:@RequestMapping(value = “/login”, headers =
{"content-type=text/”,“Referer=http://www.buyinplay.com”})
@CookieValue注解
2.CookieValue注解
读取Cookies中的值,并且赋值给变量
有三个属性 value, required, defaultValue,分别表示Cookie的名字,是否必须有这个Cookie值,如果没有则使用默认值
不带任何参数,表示需要的参数名与标注的变量名相同
@RequestMapping("/user")
public String listone(@CookieValue String goodsName){//不带任何参数
return "user";
}
@RequestMapping("/user")
public String listtwo(@CookieValue("goodsName") String goodsName){//指定Cookie的名字
return "user";
}
@RequestMapping("/user")
public String listthree(@CookieValue(value="goodsName",defaultValue="new",required =false) String goodsName){//指定Cookie的名字,如果没有这个名字,赋值默认值new
return "user";
}
@RequestParam注解
3.RequestParam注解
@RequestParam是一个可选参数,例如:@RequestParam(“id”) 注解,所以它将和URL所带参数 id进行绑定 。
如果入参是基本数据类型(如 int、long、float 等),URL 请求参数中一定要有对应的参数,否则将抛出
org.springframework.web.util.NestedServletException 异常,提示无法将 null 转换为基本数据类型.
@RequestParam包含3个配置 @RequestParam(required = ,value="", defaultValue = “”)
required :参数是否必须,boolean类型,可选项,默认为true
value: 传递的参数名称,String类型,可选项,如果有值,对应到设置方法的参数
defaultValue:String类型,参数没有传递时为参数默认指定的值
@4.ResponseBody注解
4.ResponseBody注解
这个注解可以直接放在方法上,表示返回类型将会直接作为HTTP响应字节流输出(不被放置在Model,也不被拦截为视图页面名称)。可以用于ajax。
使用了@ResponseBody能够直接将controller返回的bean对象或map对象等自动进行json或xml格式的转换,无需再使用JSONObject或者
response.setContentType(“application/json”)+PrintWriter来将返回的bean、String、map对象转换成JSON格式,再输出到页面上
用于将Controller的方法返回的对象,通过适当的HttpMessageConverter(转换器)转换为指定格式后,写入到Response对象的body数据区
返回如json、xml等时使用
在springmvc配置文件中通过,给AnnotationMethodHandlerAdapter初始化7个转换器
ByteArranHttpMessageConverter 读写二进制数据
StringHttpMessageConverter 将请求信息转换为字符串
ResourceHttpMessageConverter 读写org.springframework.core.io.Resource对象
SourceHttpMessageConverter 读写javax.xml.transform.Source类型的数据
XmlAwareFormHttpMessageConverter 处理表单中的XML数据
Jaxb2RootElementHttpMessageConverter 通过JAXB2读写XML消息,将请求消息转换到标注XmlRootElement和XmlType的注解类中
MappingJacksonHttpMessageConverter 读写JSON数据
@5.SessionAttribute注解
5.SessionAttribute注解
session管理
如果希望在多个请求之间公用某个模型属性数据,则可以在控制器类标注一个@SessionAttributes,Spring MVC会将模型中对应的属性暂存到HttpSerssion中
除了SessionAttributes,还可以直接用原生态的request.getSession()来处理session数据
Spring 允许我们有选择地指定 ModelMap 中的哪些属性需要转存到 session 中,以便下一个请求属对应的 ModelMap 的属性列表中还能访问到这些属性。这一功能是通过类定义处标注 @SessionAttributes 注解来实现的。@SessionAttributes 只能声明在类上,而不能声明在方法上。
@SessionAttributes("currUser") // 将ModelMap 中属性名为currUser 的属性
@SessionAttributes({"attr1","attr2"})
@SessionAttributes(types = User.class)
@SessionAttributes(types = {User.class,Dept.class})
@SessionAttributes(types = {User.class,Dept.class},value={"attr1","attr2"})
@6、ModelAttribute注解
6、ModelAttribute注解
- 应用于方法参数,参数可以在页面直接获取,相当于request.setAttribute(,)
- 应用于方法,将任何一个拥有返回值的方法标注上 @ModelAttribute,使其返回值将会进入到模型对象的属性列表中.
- 应用于方法参数时@ModelAttribute(“xx”),须关联到Object的数据类型,基本数据类型 如:int,String不起作用
@ModelAttributes: 接收值
方式一(重定向后面跟请求参数的方式): redirect.addAttribute("参数名",参数值);
方式二(使用session传值的方式):redirect.addFlashAttribute("参数名",参数值);
public class RedirectController {
/**
* SpringMVC提供的重定向方法:结合了上面两种方式的传参方式
* RedirectAttributes : 传参,专门在重定向时传参
* @ModelAttributes: 接收值
* 方式一(重定向后面跟请求参数的方式): redirect.addAttribute("username","chen");
* 方式二(使用session传值的方式):redirect.addFlashAttribute("username","kobe");
*
* @param redirect
* @return
*/
@RequestMapping("/r5")
public String r5(RedirectAttributes redirect){
System.out.println("r5");
// 采用的是 重定向后面跟请求参数的方式
redirect.addAttribute("username","chen");
// 采用的是 session 的传值方式
redirect.addFlashAttribute("username","kobe");
return "redirect:/r6";
}
@RequestMapping("/r6")
public String r6(@ModelAttribute("username")String name){
System.out.println("r6");
System.out.println("username: "+name);
return "hello";
}
}
@7、PathVaribale注解
7、PathVaribale注解
3.1 使用说明
作用:
用于绑定 url 中的占位符。例如:请求 url 中 /delete/{id},这个{id}就是 url 占位符。
url 支持占位符是 spring3.0 之后加入的。是 springmvc 支持 rest 风格 URL 的一个重要标志
属性:
value:用于指定 url 中占位符名称。
required:是否必须提供占位符。
使用示例
jsp:
<!-- PathVariable 注解 -->
<a href="usePathVariable/100">pathVariable 注解</a>
控制器:
@RequestMapping("/usePathVariable/{id}")
public String usePathVariable(@PathVariable("id") Integer id) {
System.out.println(id);
return "success";
}
@ 8、RequestBody注解
8、RequestBody注解
作用:
用于获取请求体内容。直接使用得到是key=value&key=value…结构的数据。
get 请求方式不适用。
属性:
required:是否必须有请求体。默认值是:true。当取值为 true 时,get 请求方式会报错。如果取值为 false,get 请求得到是 null
使用示例
post 请求 jsp:
<!-- request body 注解 -->
<form action="springmvc/useRequestBody" method="post">
用户名称:<input type="text" name="username" ><br/>
用户密码:<input type="password" name="password" ><br/>
用户年龄:<input type="text" name="age" ><br/>
<input type="submit" value="保存">
</form>
get 请求 jsp:
<a href="springmvc/useRequestBody?body=test">requestBody 注解 get 请求</a>
控制器:
@RequestMapping("/useRequestBody")
public String useRequestBody(@RequestBody(required = false) String body) {
System.out.println(body);
return "success";
}