1. SpringMVC使用流程
引入依赖
< properties>
< project.build.sourceEncoding> UTF-8</ project.build.sourceEncoding>
< maven.compiler.source> 1.8</ maven.compiler.source>
< maven.compiler.target> 1.8</ maven.compiler.target>
< spring.version> 5.0.2.RELEASE</ spring.version>
</ properties>
< dependency>
< groupId> org.springframework</ groupId>
< artifactId> spring-web</ artifactId>
< version> ${spring.version}</ version>
</ dependency>
< dependency>
< groupId> org.springframework</ groupId>
< artifactId> spring-webmvc</ artifactId>
< version> ${spring.version}</ version>
</ dependency>
< dependency>
< groupId> javax.servlet</ groupId>
< artifactId> servlet-api</ artifactId>
< version> 2.5</ version>
< scope> provided</ scope>
</ dependency>
< dependency>
< groupId> javax.servlet.jsp</ groupId>
< artifactId> jsp-api</ artifactId>
< version> 2.0</ version>
< scope> provided</ scope>
</ dependency>
springmvc.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
< beans xmlns = " http://www.springframework.org/schema/beans"
xmlns: mvc= " http://www.springframework.org/schema/mvc"
xmlns: context= " http://www.springframework.org/schema/context"
xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance"
xsi: schemaLocation= "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd" >
< context: component-scan base-package = " cn.zh" > </ context: component-scan>
< bean id = " internalResourceViewResolver" class = " org.springframework.web.servlet.view.InternalResourceViewResolver" >
< property name = " prefix" value = " /WEB-INF/pages/" />
< property name = " suffix" value = " .jsp" />
</ bean>
< bean id = " conversionService" class = " org.springframework.context.support.ConversionServiceFactoryBean" >
< property name = " converters" >
< set>
< bean class = " cn.zh.utils.StringToDateConverter" > </ bean>
</ set>
</ property>
</ bean>
< mvc: annotation-driven conversion-service = " conversionService" />
</ beans>
web.xml配置
<! DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
< web-app>
< display-name> Archetype Created Web Application</ display-name>
< 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:springmvc.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>
< filter>
< filter-name> characterEncodingFilter</ filter-name>
< filter-class> org.springframework.web.filter.CharacterEncodingFilter</ filter-class>
< init-param>
< param-name> encoding</ param-name>
< param-value> UTF-8</ param-value>
</ init-param>
</ filter>
< filter-mapping>
< filter-name> characterEncodingFilter</ filter-name>
< url-pattern> /*</ url-pattern>
</ filter-mapping>
</ web-app>
注解方式使用springMVC
* RequestMapping注解
* method:接收什么类型的请求
* params:接收的参数中要有指定的属性
* headers:必须包含对应的请求头
@Controller
@RequestMapping ( "/anno" )
@SessionAttributes ( value = { "msg" } )
public class AnnoController {
@RequestMapping ( "/testRequestParam" )
public String testRequestParam ( @RequestParam ( name = "name" ) String username) {
System . out. println ( "执行了。。。。。" ) ;
return "success" ;
}
public String testRequestBody ( @RequestBody String body) {
System . out. println ( body) ;
return "success" ;
}
@RequestMapping ( value = "/testPathVariable/{sid}" , method = RequestMethod . POST)
public String testPathVariable ( @PathVariable ( name = "sid" ) String id) {
System . out. println ( id) ;
return "success" ;
}
@RequestMapping ( value = "/testRequestHeader" )
public String testRequestHeader ( @RequestHeader ( value = "Accept" ) String header) {
System . out. println ( header) ;
return "success" ;
}
@RequestMapping ( value = "/testCookieValue" )
public String testCookieValue ( @CookieValue ( value = "JSESSIONID" ) String cookieValue) {
System . out. println ( cookieValue) ;
return "success" ;
}
@RequestMapping ( value = "/testModelAttribute" )
public String testModelAttribute ( User user) {
System . out. println ( "testModelAttribute执行了........." ) ;
System . out. println ( user) ;
return "success" ;
}
@ModelAttribute
public User showUser ( String uname) {
System . out. println ( "showUser执行了.........." ) ;
User user = new User ( ) ;
user. setUname ( uname) ;
user. setAge ( 20 ) ;
user. setDate ( new Date ( ) ) ;
return user;
}
@RequestMapping ( value = "/testSessionAttributes" )
public String testSessionAttributes ( Model model) {
System . out. println ( "testSessionAttributes..........." ) ;
model. addAttribute ( "msg" , "cc" ) ;
return "success" ;
}
@RequestMapping ( value = "/getSessionAttributes" )
public String getSessionAttributes ( ModelMap modelMap) {
System . out. println ( "testSessionAttributes..........." ) ;
Model msg = ( Model ) modelMap. get ( "msg" ) ;
return "success" ;
}
@RequestMapping ( value = "/delSessionAttributes" )
public String delSessionAttributes ( SessionStatus status) {
System . out. println ( "testSessionAttributes..........." ) ;
status. setComplete ( ) ;
return "success" ;
}
@RequestMapping ( "/testServlet" )
public String testServlet ( HttpServletRequest request, HttpServletResponse response) {
System . out. println ( request) ;
HttpSession session = request. getSession ( ) ;
System . out. println ( session) ;
return "success" ;
}
}
自定义的类型转换器
public class StringToDateConverter implements Converter < String , Date > {
@Override
public Date convert ( String s) {
if ( s == null ) {
throw new RuntimeException ( "请您传入数据" ) ;
}
DateFormat df = new SimpleDateFormat ( "yyyy-MM-dd" ) ;
try {
return df. parse ( s) ;
} catch ( Exception e) {
throw new RuntimeException ( "有错误!" ) ;
}
}
}
2. 响应方法
配置前端控制器
<?xml version="1.0" encoding="UTF-8"?>
< beans xmlns = " http://www.springframework.org/schema/beans"
xmlns: mvc= " http://www.springframework.org/schema/mvc"
xmlns: context= " http://www.springframework.org/schema/context"
xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance"
xsi: schemaLocation= "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd" >
< context: component-scan base-package = " cn.zh" />
< bean id = " internalResourceViewResolver" class = " org.springframework.web.servlet.view.InternalResourceViewResolver" >
< property name = " prefix" value = " /WEB-INF/pages/" />
< property name = " suffix" value = " .jsp" />
</ bean>
< mvc: resources mapping = " /js/**" location = " /js/" />
< mvc: resources mapping = " /images/**" location = " /images/" />
< mvc: resources mapping = " /css/**" location = " /css/" />
< mvc: annotation-driven/>
</ beans>
response的多种方式
@Controller
@RequestMapping ( "/user" )
public class UserController {
@RequestMapping ( "/testString" )
public String testString ( Model model) {
System . out. println ( "testString方法执行了........" ) ;
User user = new User ( ) ;
user. setUsername ( "cc" ) ;
user. setPassword ( "123" ) ;
user. setAge ( 22 ) ;
model. addAttribute ( "user" , user) ;
return "success" ;
}
@RequestMapping ( "/testVoid" )
public void testVoid ( HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException {
System . out. println ( "testVoid方法执行了........" ) ;
response. setCharacterEncoding ( "UTF-8" ) ;
response. setContentType ( "text/html;charset=UTF-8" ) ;
response. getWriter ( ) . print ( "你好,hello" ) ;
return ;
}
@RequestMapping ( "/testModelAndView" )
public ModelAndView testModelAndView ( ) {
ModelAndView mv = new ModelAndView ( ) ;
System . out. println ( "testModelAndView方法执行了........" ) ;
User user = new User ( ) ;
user. setUsername ( "cc" ) ;
user. setPassword ( "123" ) ;
user. setAge ( 22 ) ;
mv. addObject ( "user" , user) ;
mv. setViewName ( "success" ) ;
return mv;
}
@RequestMapping ( "/testForwardOrRedirect" )
public String testForwardOrRedirect ( ) {
System . out. println ( "testForwardOrRedirect方法执行了........" ) ;
return "redirect:/index.jsp" ;
}
@RequestMapping ( "/testAjax" )
public @ResponseBody User testAjax ( @RequestBody User user) {
System . out. println ( user) ;
user. setUsername ( "ha" ) ;
user. setAge ( 33 ) ;
return user;
}
}
3. 文件上传
springMVC.xml
<?xml version="1.0" encoding="UTF-8"?>
< beans xmlns = " http://www.springframework.org/schema/beans"
xmlns: mvc= " http://www.springframework.org/schema/mvc"
xmlns: context= " http://www.springframework.org/schema/context"
xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance"
xsi: schemaLocation= "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd" >
< context: component-scan base-package = " cn.zh" />
< bean id = " internalResourceViewResolver" class = " org.springframework.web.servlet.view.InternalResourceViewResolver" >
< property name = " prefix" value = " /WEB-INF/pages/" />
< property name = " suffix" value = " .jsp" />
</ bean>
< bean id = " multipartResolver" class = " org.springframework.web.multipart.commons.CommonsMultipartResolver" >
< property name = " maxUploadSize" value = " 10485760" > </ property>
</ bean>
< mvc: resources mapping = " /js/**" location = " /js/" />
< mvc: resources mapping = " /images/**" location = " /images/" />
< mvc: resources mapping = " /css/**" location = " /css/" />
< mvc: annotation-driven/>
</ beans>
实现文件上传
@Controller
@RequestMapping ( "/user" )
public class UserController {
@RequestMapping ( "/fileUpload1" )
public String fileUpload1 ( HttpServletRequest request) throws Exception {
System . out. println ( "文件上传" ) ;
String path = request. getSession ( ) . getServletContext ( ) . getRealPath ( "/uploads/" ) ;
File file = new File ( path) ;
if ( ! file. exists ( ) ) {
file. mkdirs ( ) ;
}
DiskFileItemFactory factory = new DiskFileItemFactory ( ) ;
ServletFileUpload upload = new ServletFileUpload ( factory) ;
List < FileItem > items = upload. parseRequest ( request) ;
for ( FileItem item : items) {
if ( item. isFormField ( ) ) {
} else {
String filename = item. getName ( ) ;
String uuid = UUID. randomUUID ( ) . toString ( ) . replace ( "-" , "" ) ;
filename= uuid+ "_" + filename;
item. write ( new File ( path, filename) ) ;
item. delete ( ) ;
}
}
return "success" ;
}
@RequestMapping ( "/fileUpload2" )
public String fileUpload2 ( HttpServletRequest request, MultipartFile upload) throws IOException {
String path = request. getSession ( ) . getServletContext ( ) . getRealPath ( "/uploads/" ) ;
File file = new File ( path) ;
if ( ! file. exists ( ) ) {
file. mkdirs ( ) ;
}
String filename = upload. getOriginalFilename ( ) ;
String uuid = UUID. randomUUID ( ) . toString ( ) . replace ( "-" , "" ) ;
filename= uuid+ "_" + filename;
upload. transferTo ( new File ( path, filename) ) ;
return "success" ;
}
@RequestMapping ( "/fileUpload3" )
public String fileUpload3 ( MultipartFile upload) throws IOException {
String path = "http://localhost:9090/uploads/" ;
String filename = upload. getOriginalFilename ( ) ;
String uuid = UUID. randomUUID ( ) . toString ( ) . replace ( "-" , "" ) ;
filename= uuid+ "_" + filename;
Client client = Client . create ( ) ;
WebResource webResource = client. resource ( path + filename) ;
webResource. put ( upload. getBytes ( ) ) ;
return "success" ;
}
}
4. 异常处理
springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
< beans xmlns = " http://www.springframework.org/schema/beans"
xmlns: mvc= " http://www.springframework.org/schema/mvc"
xmlns: context= " http://www.springframework.org/schema/context"
xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance"
xsi: schemaLocation= "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd" >
< context: component-scan base-package = " cn.zh" />
< bean id = " internalResourceViewResolver" class = " org.springframework.web.servlet.view.InternalResourceViewResolver" >
< property name = " prefix" value = " /WEB-INF/pages/" />
< property name = " suffix" value = " .jsp" />
</ bean>
< mvc: resources mapping = " /js/**" location = " /js/" />
< mvc: resources mapping = " /images/**" location = " /images/" />
< mvc: resources mapping = " /css/**" location = " /css/" />
< bean id = " sysExceptionResolver" class = " cn.zh.exception.SysExceptionResolver" > </ bean>
< mvc: annotation-driven/>
</ beans>
定义异常处理器
public class SysExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException ( HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
SysException e = null ;
if ( ex instanceof SysException ) {
e = ( SysException ) ex;
} else {
e = new SysException ( "系统正在维护........" ) ;
}
ModelAndView mv = new ModelAndView ( ) ;
mv. addObject ( "errorMsg" , e. getMessage ( ) ) ;
mv. setViewName ( "error" ) ;
return mv;
}
}
5. 拦截器
springmvc.xml配置拦截器
<?xml version="1.0" encoding="UTF-8"?>
< beans xmlns = " http://www.springframework.org/schema/beans"
xmlns: mvc= " http://www.springframework.org/schema/mvc"
xmlns: context= " http://www.springframework.org/schema/context"
xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance"
xsi: schemaLocation= "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd" >
< context: component-scan base-package = " cn.zh" />
< bean id = " internalResourceViewResolver" class = " org.springframework.web.servlet.view.InternalResourceViewResolver" >
< property name = " prefix" value = " /WEB-INF/pages/" />
< property name = " suffix" value = " .jsp" />
</ bean>
< mvc: resources mapping = " /js/**" location = " /js/" />
< mvc: resources mapping = " /images/**" location = " /images/" />
< mvc: resources mapping = " /css/**" location = " /css/" />
< mvc: interceptors>
< mvc: interceptor>
< mvc: mapping path = " /user/*" />
< bean class = " cn.zh.interceptor.MyInterceptor1" > </ bean>
</ mvc: interceptor>
</ mvc: interceptors>
< mvc: annotation-driven/>
</ beans>
拦截器实现
public class MyInterceptor1 implements HandlerInterceptor {
@Override
public boolean preHandle ( HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System . out. println ( "执行了..." ) ;
return true ;
}
}