SpringMVC深入一
创建一个SpringMVC项目的基本步骤是:
1.导入相应的spring包,需要导入的包有:
spring-aop-4.3.3.RELEASE.jar
spring-beans-4.3.3.RELEASE.jar
spring-context-4.3.3.RELEASE.jar
spring-core-4.3.3.RELEASE.jar
spring-expression-4.3.3.RELEASE.jar
spring-web-4.3.3.RELEASE.jar
spring-webmvc-4.3.3.RELEASE.jar
commons-logging-1.2.jar
2.在web.xml中配置servlet
<!-- 配置DispatchServlet -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置一个初始化参数,其作用是配置SpringMVC配置文件的名称和位置 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param> -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
init-param
配置SpringMVC配置文件的名称和位置,所以上面的配置文件是位于src目录的springmvc.xml
文件。
实际上也可以不通过contextConfigLocation
来配置SpringMVC配置文件。默认的配置文件路径为/WEB-INF/<servlet-name>-servlet.xml
。所以对于上述的springDispatcherServlet
,其默认的配置文件为springDispatcherServlet-servlet.xml
,位于/WEB-INF/
下。
3.创建控制器,添加注解。
@Controller
public class HelloWorld {
/**
* 1. 使用@RequestMapping来映射请求
* 2. 返回值会通过视图解析器解析为实际的物理视图。对于InternalResourceViewResolver
* 视图解析器,会做如下的解析: prefix+returnVal+suffix,得到实际的物理视图,然后做转发
*
* /WEB-INF/views/success.jsp
* @return
*/
@RequestMapping("/helloworld")
public String hello() {
System.out.println("hello world");
return "success";
}
}
@RequestMapping
来映射请求,上面的hello
方法会处理http://localhost:8080/springmvc-1/helloworld
这样的请求。
返回值success
,会通过视图解析器解析为实际的物理视图。在本例子中是位于/WEB-INF/views/success.jsp
的文件。
如何解析是在springDispatcherServlet-servlet.xml
配置的。
4.SpringMVC的配置文件springDispatcherServlet-servlet.xml
,需要加入context
、beans
、mvc
命名空间。如下,说明见注释:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 配置自动扫描的包 -->
<context:component-scan base-package="com.springmvc"></context:component-scan>
<!-- 配置视图解析器:如何把handler方法返回值解析为实际的物理视图 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
@RequestMapping
@RequestMapping
注解为控制器指定可以处理哪些URL请求。
@RequestMapping
注解修饰方法还可以修饰类。
@RequestMapping("/springmvc")
public class SpringMVCTest {}
@RequestMapping
的value
,method
,params
及headers
分别表示请求URL、请求方法、请求参数、请求头的映射。联合使用多个条件可以放请求映射更加精确化。
如下,表示使用post方法
@RequestMapping(value="/testMethod", method=RequestMethod.POST)
如下,表示的是params
中必须包含username和age,其age不等于10,headers
中Accept-Language
要等于zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4
@RequestMapping(value="/testParamsAndHeaders", params={"username", "age!=10"}, headers={"Accept-Language=zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4"})
@RequestMapping
支持Ant
风格的通配符
?
匹配文件名中的一个字符*
匹配文件名中的任意字符**
匹配多层路径
@PathVariable
@PathVariable
可以映射URL中的占位符到目标方法的参数中
- 带占位符的URL是Spring3.0新增的功能,该功能在SpringMVC向
REST
目标挺近发展过程中有里程碑意义。
例如如下的链接:
<a href="springmvc/testPathVariable/1">TestPathVariable</a>
映射如下:
@RequestMapping("/testPathVariable/{id}")
public String testPathVariable(@PathVariable("id") Integer id) {
System.out.println("testPathVariable " + id);
return SUCCESS;
}
@PathVariable("id")
这里默认省略掉了value
Rest
Rest风格的URL,以CRUD为例:
请求路径 请求方法 作用
-/order/1 HTTP GET 得到id为1的order
-/order/1 HTTP DELETE 删除id为1的order
-/order/1 HTTP PUT 更新id为1的order
-/order HTTP POST 新增order
如何发送PUT
和DELETE
请求呢?
需要配置一个Filter,org.springframework.web.filter.HiddenHttpMethodFilter
。
在web.xml
中添加过滤器:
<!--
配置org.springframework.web.filter.HiddenHttpMethodFilter
把post请求转为delete或put请求
-->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
SpringMVC 对于DELETE/PUT请求,是通过post体中的”_method
“(可自定义)参数值来识别。所以需要使用一个名为_method
的隐藏域。
使用PUT
的Form表单:
<form action="springmvc/testRest/1" method="post">
<input type="hidden" name="_method" value="PUT"/>
<input type="submit" value="TestRest PUT"/>
</form>
Controller中定义方法如下:
@RequestMapping(value="/testRest/{id}", method=RequestMethod.PUT)
public String testRestPut(@PathVariable("id") Integer id) {
System.out.println("testRest PUT: " + id);
return SUCCESS;
}
DELETE
的定义和PUT
相似。
在使用过程中可能会出现如下的错误提示Status 405 - JSPs only permit GET POST or HEAD HiddenHttpMethodFilter
请参考如下的方式解决:
- Spring MVC 学习笔记(二):@RequestMapping用法详解
- SpringMVC: HTTP Status 405 - JSPs only permit GET POST or HEAD问题的解决办法
@RequestParam
@RequestParam
可以用来映射请求参数。
例如有如下的链接:
<a href="springmvc/testRequestParam?username=hello&age=11">testRequestParam</a>
如何获取到username和age的值呢?这时就要用到@RequestParam
@RequestMapping("/testRequestParam")
public String testRequestParam(@RequestParam(value="username") String username,
@RequestParam(value="age") int age){
System.out.println("testRequestParam: username " + username);
System.out.println("testRequestParam: age " + age);
return SUCCESS;
}
但是当链接中没有age字段时,会出错。这时就要用到required
(可能还需要将参数类型由int改为Integer),还可以使用defaultValue
来指定默认值。@RequestParam(value="age", required=false, defaultValue="0")
- value:即请求参数的参数名
- required:参数是否必须,默认为true
- defaultValue:请求参数的默认值
@RequestHeader
@RequestHeader
映射请求信息,用法与@RequestParam
相似。
如下获取请求头header的Accept-Language
对应的值:
@RequestMapping("/testRequestHeader")
public String testRequestHeader(@RequestHeader(value="Accept-Language") String header){
System.out.println("testRequestHeader, " + header);
return SUCCESS;
}
@CookieValue
@CookieValue
可以处理方法入参绑定某个Cookie值。
@RequestMapping("/testCookieValue")
public String testCookieValue(@CookieValue("JSESSIONID") String sessionId) {
System.out.println("testCookieValue:"+ sessionId);
return SUCCESS;
}
使用POJO对象绑定请求对象
SpringMVC会按请求参数名和POJO属性名进行自动匹配,自动为该对象填充属性值。支持级联属性
。
例如有如下的连个实体:
- Address类属性如下
- province
- city
- User实体属性如下
- username
- password
- age
- address 类型为Address类
有如下的form:
<form action="springmvc/testPojo" method="post">
username:<input type="text" name="username"/>
<br>
password:<input type="password" name="password"/>
<br>
email:<input type="text" name="email"/>
<br>
age:<input type="text" name="age"/>
<br>
province:<input type="text" name="address.province"/>
<br>
city:<input type="text" name="address.city"/>
<br>
<input type="submit"/>
</form>
注意city对应的name为address.city
使用POJO对象绑定请求对象,如下:
@RequestMapping("/testPojo")
public String testPojo(User user){
System.out.println("testPojo: "+user);
return SUCCESS;
}
使用Servlet API作为入参
MVC的Handler方法可以接受的ServletAPI类型的参数如下:
- HttpServletRequest
- HttpServletResponse
- HttpSession
- java.security.Principal
- Local
- InputStream
- OutputStream
- Reader
- Writer
例子如下:
@RequestMapping("/testServlet")
public String testServlet(HttpServletRequest request, HttpServletResponse response) {
System.out.println("testServlet");
System.out.println(request);
return SUCCESS;
}