一.基础入门
- 导入SpringMVC需要的jar包
<!--core-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<!--web-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
- 添加Web.xml配置文件中关于SpringMVC的配置
<!--配置DispatcherServlet-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
- 在resources添加springmvc-mvc.xml配置文件
<?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/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.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<context:component-scan base-package="controller,intergrate.controller"/>
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
- 在WEB-INF文件夹下创建名为jsp的文件夹,用来存放jsp视图。创建一个success.jsp”
5.编写Controller代码
@Controller
public class CommonController {
@RequestMapping("/hello")
public String hello() {
//System.out.println("helloworld!");
return "success";
}
}
二、配置解析
1.Dispatcherservlet
DispatcherServlet是前置控制器,配置在web.xml文件中的。拦截匹配的请求,Servlet拦截匹配规则要自已定义,把拦截下来的请求,依据相应的规则分发到目标Controller来处理,是配置spring MVC的第一步。
2.InternalResourceViewResolver
视图名称解析器
3.以上出现的注解
@Controller 负责注册一个bean 到spring 上下文中
@RequestMapping 注解为控制器指定可以处理哪些 URL 请求
三、SpringMVC常用注解
@Controller
负责注册一个bean 到spring 上下文中
@RequestMapping
注解为控制器指定可以处理哪些 URL 请求
@RequestBody
该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到要返回的对象上 ,再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上
@ResponseBody
该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区
@ModelAttribute
在方法【定义】上使用 @ModelAttribute 注解:Spring MVC 在调用目标处理方法前,会先逐个调用在方法级上标注了@ModelAttribute 的方法
在方法的【入参】前使用 @ModelAttribute 注解:可以从隐含对象中获取隐含的模型数据中获取对象,再将请求参数 –绑定到对象中,再传入入参将方法入参对象添加到模型中
@RequestParam
在处理方法入参处使用 @RequestParam 可以把请求参 数传递给请求方法
@PathVariable
绑定 URL 占位符到入参
@ExceptionHandler
注解到方法上,出现异常时会执行该方法
@ControllerAdvice
使一个Contoller成为全局的异常处理类,类中用@ExceptionHandler方法注解的方法可以处理所有Controller发生的异常
四、自动匹配参数
/**
* 1.自动匹配参数
*/
@RequestMapping("/personWithParam")
public String personWithParam(String name, int age) {
System.out.println(name + ":" + age);
return "success";
}
五、自动装箱
package model;
import java.io.Serializable;
/**
* Person
* Created by heqianqian on 2017/4/27.
*/
public class Person implements Serializable{
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
/**
* 2.自动装箱
*/
@RequestMapping("/personAutoPack")
public String personAutoPack(Person person) {
System.out.println(person.getName() + " " + person.getAge());
return "success";
}
六、使用InitBinder来处理Date类型的参数
/**
* 3.使用InitBinder来处理Date类型的参数
*/
@RequestMapping("/date")
public String date(Date date) {
System.out.println(date);
return "success";
}
@InitBinder
public void initBinder(ServletRequestDataBinder binder) {
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
}
七、向前台传递参数
/**
* 4.向前台传递参数
*/
@RequestMapping("/showParam")
public String showParam(Map<String, Object> map) {
Person p = new Person("heqianiqna", 12);
map.put("person", p);
return "person";
}
八、使用Ajax调用
//pass the parameters to front-end using ajax
@RequestMapping("/getPerson")
public void getPerson(String name,PrintWriter pw){
pw.write("hello,"+name);
}
@RequestMapping("/name")
public String sayHello(){
return "name";
}
$(function(){
$("#btn").click(function(){
$.post("mvc/getPerson",{name:$("#name").val()},function(data){
alert(data);
});
});
});
九、在Controller中使用redirect方式处理请求
/**
* 5.使用redirect进行重定向
*/
@RequestMapping("/redirect")
public String redirect() {
return "redirect:/hello";
}
@RequestMapping("/fileUpload")
public String fileuploadUI() {
return "upload_file";
}
十、文件上传
引入依赖
<!--fileupload-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
在SpringMVC配置文件中加入
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="102400000"/>
</bean>
方法代码
/**
* 6.文件上传
*/
@RequestMapping("/uploadFile")
public String uploadFile(HttpServletRequest request) throws IOException {
MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartHttpServletRequest.getFile("file");
String fileName = file.getOriginalFilename();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String filePath = request.getSession().getServletContext().getRealPath("/")
+ "upload" + simpleDateFormat.format(new java.util.Date()) + fileName.substring(fileName.lastIndexOf("."));
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8"));
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(file.getInputStream(), "UTF-8"));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
bufferedWriter.write(line);
}
bufferedWriter.flush();
bufferedWriter.close();
bufferedReader.close();
return "success";
}
前台form表单
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>上传文件</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/uploadFile" method="post" enctype="multipart/form-data">
<input type="file" name="file"/><br>
<input type="submit" value="submit"/>
</form>
</body>
</html>
十一、使用@RequestParam注解指定参数的name
/**
* 7.使用@RequestParam指定参数
*/
@RequestMapping(value = "/appointParam", method = RequestMethod.GET)
public String appointParam(@RequestParam("age") int age, @RequestParam("name") String name) {
System.out.println(age + " " + name);
return "success";
}
十二、RESTFul风格的SringMVC
RestfulController
@Controller
@RequestMapping(value = "/rest")
public class RestfulController {
@RequestMapping(value = "/form", method = RequestMethod.GET)
public String form() {
return "rest_form";
}
@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
public String get(@PathVariable("id") Integer id) {
System.out.println("get " + id);
return "success";
}
@RequestMapping(value = "/user/{id}", method = RequestMethod.POST)
public String post(@PathVariable("id") Integer id) {
System.out.println("post " + id);
return "success";
}
@RequestMapping(value = "/user/{id}", method = RequestMethod.PUT)
public String put(@PathVariable("id") Integer id) {
System.out.println("put " + id);
return "success";
}
@RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
public String delete(@PathVariable("id") Integer id) {
System.out.println("delete " + id);
return "success";
}
}
form表单发送put和delete请求
在web.xml中配置
<!--配置HiddenHttpMethodFilter 可以使用put,delete,post,get-->
<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>
在前台可以用以下代码产生请求
<form action="rest/user/1" method="post">
<input type="hidden" name="_method" value="PUT">
<input type="submit" value="put">
</form>
<form action="rest/user/1" method="post">
<input type="submit" value="post">
</form>
<form action="rest/user/1" method="get">
<input type="submit" value="get">
</form>
<form action="rest/user/1" method="post">
<input type="hidden" name="_method" value="DELETE">
<input type="submit" value="delete">
</form>
十三、返回json格式的字符串
引入依赖
<!--json-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
方法代码
@Controller
@RequestMapping("/json")
public class JsonController {
/**
* 返回json数据字符串
*/
@ResponseBody
@RequestMapping("/getUser")
public Person get() {
return new Person("heqianqian", 20);
}
}
十四、异常的处理
1.处理局部异常(Controller内)
@Controller
@RequestMapping("/except")
public class ExceptController {
//ps:返回的视图是/WEB/INF/jsp/except/xx.jsp
@ExceptionHandler
public ModelAndView exceptionHandler(Exception ex) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("except", ex);
System.out.println("exceptionHandler");
return modelAndView;
}
/**
* 局部异常处理
*/
@RequestMapping("/error")
public String error() {
int a = 2 / 0;
return "success";
}
}
2.处理全局异常(所有Controller)
@ControllerAdvice
public class ExceptControllerAdvice {
//ps:返回的视图是/WEBINF/jsp/xxx.jsp
@ExceptionHandler
public ModelAndView exceptionHandler(Exception ex) {
ModelAndView mv = new ModelAndView("error");
mv.addObject("except", ex);
System.out.println("in testControllerAdvice");
return mv;
}
}
3.另一种处理全局异常的方法
在SpringMVC配置文件中配置
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="java.lang.ArithmeticException">error</prop>
</props>
</property>
</bean>
十五、设置一个自定义拦截器
创建一个MyInterceptor类,并实现HandlerInterceptor接口
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
System.out.println("preHandle");
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle");
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
System.out.println("afterCompletion");
}
}
2.在SpringMVC的配置文件中配置
<mvc:interceptors>
<bean class="interceptor.MyInterceptor"/>
</mvc:interceptors>
拦截器拦截顺序
十六、表单的验证(使用Hibernate-validate)及国际化
引入依赖
<!--Hibernate-validate和国际化-->
<dependency>
<groupId>com.fasterxml</groupId>
<artifactId>classmate</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.1.4.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator-annotation-processor</artifactId>
<version>5.4.1.Final</version>
</dependency>
编写实体类User并加上验证注解
public class User {
private int id;
@NotEmpty
private String name;
@Past//表示时间必须是一个过去值
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date birth;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", birth=" + birth + "]";
}
}
ps:@Past表示时间必须是一个过去值
3.在jsp中使用SpringMVC的form表单
<form:form action="form/add" method="post" modelAttribute="user">
id:<form:input path="id"/><form:errors path="id"/><br>
name:<form:input path="name"/><form:errors path="name"/><br>
birth:<form:input path="birth"/><form:errors path="birth"/>
<input type="submit" value="submit">
</form:form>
ps:path对应name
4.Controller中代码
@Controller
@RequestMapping("/form")
public class FormController {
@RequestMapping(value = "/add",method = RequestMethod.GET)
public String add(Map<String,Object> map){
//因为jsp中使用了modelAttribute属性,所以必须在request域中有一个"user".
map.put("user",new User());
return "add_user";
}
@RequestMapping(value = "/add",method = RequestMethod.POST)
public String add(@Valid User user, BindingResult bindingResult){//@Valid 表示按照在实体上标记的注解验证参数
System.out.println(user.getName());
if (bindingResult.getErrorCount()>0){
return "add_user";
}
return "show";
}
}
ps:
1.因为jsp中使用了modelAttribute属性,所以必须在request域中有一个”user”.
2.@Valid 表示按照在实体上标记的注解验证参数
3.返回到原页面错误信息回回显,表单也会回显
5.错误信息自定义
在src目录下添加locale.properties
NotEmpty.user.name=name can't not be empty
Past.user.birth=birth should be a past value
DateTimeFormat.user.birth=the format of input is wrong
typeMismatch.user.birth=the format of input is wrong
typeMismatch.user.id=the format of input is wrong
在SpringMVC配置文件中配置
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="locale"/>
</bean>
6.国际化显示
在src下添加locale_zh_CN.properties
username=账号
password=密码
locale.properties中添加
username=user name
password=password
创建一个locale.jsp
<body>
<fmt:message key="username"></fmt:message>
<fmt:message key="password"></fmt:message>
</body>
在SpringMVC中配置
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="locale"/>
</bean>
<!--可以直接访问WEB-INF下的jsp页面-->
<mvc:view-controller path="/locale" view-name="locale"/>
让locale.jsp在WEB-INF下也能直接访问
最后,访问locale.jsp,切换浏览器语言,能看到账号和密码的语言也切换了
十七、整合SpringIOC和SpringMVC
1.创建实体类
public class User {
private int id;
@NotEmpty
private String name;
@Past//表示时间必须是一个过去值
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date birth;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", birth=" + birth + "]";
}
}
2.service类
@Service
public class UserService {
public void save() {
System.out.println("Save User");
}
}
3.Controller类
@Controller
@RequestMapping("/intergrate")
public class UserController {
@Resource
private UserService userService;
@RequestMapping(value = "/save", method = RequestMethod.GET)
public String saveUser() {
return "save_user";
}
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String saveUser(@RequestBody @ModelAttribute User u) {
System.out.println(u);
userService.save();
return "success";
}
}
4.在web.xml中配置Spring
<!--配置Spring-->
<listener>
<display-name>contextLoaderListener</display-name>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-service.xml</param-value>
</context-param>
5.编写Spring配置文件
<?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"
xsi:schemaLocation="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.xsd">
<!--包扫描-->
<context:component-scan base-package="intergrate.service"/>
</beans>
6.前端页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>存入用户信息</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/intergrate/user" method="post">
id:<input type="text" name="id" title="id"/><br/>
name:<input type="text" name="name" title="name"/><br/>
date:<input type="text" name="birth" title="birth"/><br/>
<input type="submit" value="submit"/>
</form>
</body>
</html>