一、springMVC
1.构建项目 注意:创建一个maven(webapp)工程 创建过程中需要填写一组键值解决创建项目过慢原因:
archetypeCatalog -- internal
1.1补全目录结构 创建文件夹 java 和 resource,右键设置为特定文件夹
1.2 导入依赖
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
1.3创建配置文件
创建xml文件
1.4编写配置文件 1.前端控制器-web.xml 位置:web.xml文件
<!--配置前端控制器-->
<servlet>
<servlet-name>DispatcherServlet</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>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
2.springmvc.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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--开启注解的扫描-->
<context:component-scan base-package="com.jredu"></context:component-scan>
<!--视图解析器-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--开启注解-->
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
1.5启动流程分析
1.6详细流程
说明:在springMVC的各个组件中,处理器映射器、处理器适配器、视图解析器称为SpringMVC的三大组件。 2.RequestMapping注解 2.1说明 作用:用于建立前端请求调用后端接口 作用范围: 1.方法: 2.类:写在类上面可以实现分模块()
@Controller
@RequestMapping("/helloController ")//请求的一级路径
public class HelloController {
@RequestMapping("/say")//请求的二级路径
public String say(){
System.out.println("hello world");
return "success";
}
}
//前端请求后端接口
<a href="/helloController /say">入门程序</a>
2.2属性
属性:
value:用于指定请求的URL,和path属性作用一样。 path:同上 method:用于指定请求的方式get、post params:用于指定限定请求的参数条件 params={"username"} headers:用于指定请求头的信息
3.请求参数的绑定
3.1 String类型 保证请求携带参数的key与处理方法接受参数名一致 3.2 引用数据类型 保证参数名与bean对象的属性名一致
4.中文乱码解决
<!--解决中文乱码-->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<async-supported>true</async-supported>
<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>
5.自定义类型转换器
5.1 注解转换
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date date;
5.2 自定义类型转换
1.定义一个类,实现Converter接口,该接口有两个泛型
public class StringToDateConverter implements Converter<String, Date> {
/**
* Converter<String,Date> :org.springframework.core.convert.converter.Converter包下的
* String: 原类型
* Date: 目标类型
* 字符串转换时间类型
* @param s 字符串
* @return 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 (ParseException e) {
throw new RuntimeException("类型转换失败");
}
}
}
2.配置类型转换器springmvc.xml
<!--配置类型转换器-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.jredu.utils.StringToDateConverter"/>
</set>
</property>
</bean>
3.生效处理
<mvc:annotation-driven conversion-service="conversionService"/>
6.常用注解
6.1 RequestParam 作用:把请求中指定名称的参数给控制器中的形参赋值,当参数名称不一致时,使用该注解实现绑定。 属性: value:请求参数中的名称。 required:请求参数中是否必须提供此参数,默认值:true表示必须提供,如果不提供将报错。
<%--testRequestParam--%>
<a href="anno/testRequest?username=哈哈">小白</a>
@RequestMapping("/testRequest")
public String testRequest(@RequestParam("username",required = true) String name){
System.out.println(name);
return "success";
}
6.2 RequestBody 作用:获取请对象
@RequestMapping("/testRequestBody")
public String testRequestBody(@RequestBody String body){
System.out.println(body);
return "success";
}
6.3 pathVariable(restful风格) 作用:用于绑定url中的占位符,例 /delete/{id},这个id就是url占位符 属性:value: required:
<a href="anno/testPathVariable/10">testPathVariable</a><br>
@RequestMapping("/testPathValue/{id}")
public String testPathValue(@PathVariable(name = "id") String id){
System.out.println(id);
return "success";
}
6.4 CookieValue
@RequestMapping("/testCookieValue")
public String testCookieValue(@CookieValue(name = "cokies") String cokies){
System.out.println(cokies);
return "success";
}
//按照名字取cookie值 7.返回值 7.1 String 会跳转到想对象的返回值字符串的对应的jsp页面 7.2 void 会默认跳转请求路径名称的.jsp 如: @RequestMapping("/anno") public class AnnoController { @RequestMapping("/testvoid") public void testvoid(){ } //默认跳转路径anno/testvoid.jsp 7.3 关键字
redirect重定向 8.静态资源拦截问题 在springmvc.xml配置文件中配置静态资源不被拦截
8.1 响应前台依赖jar包
com.fasterxml.jackson.core jackson-databind 2.9.8 com.fasterxml.jackson.core jackson-core 2.9.8 com.fasterxml.jackson.core jackson-annotations 2.9.8 二、SpringMVC实现文件上传 1、依赖 commons-fileupload commons-fileupload 1.3.1 commons-io commons-io 2.4 2、文件上传前提3.传统上传方式 @Controller public class FileUploadController { @RequestMapping("/upload") public String upload(HttpServletRequest req) throws Exception { String path = req.getSession().getServletContext().getRealPath("/uploads/"); File file = new File(path); if (!file.exists()){ file.mkdirs(); } //获取文件上传工厂 DiskFileItemFactory factory = new DiskFileItemFactory(); //文件上传器 ServletFileUpload upload = new ServletFileUpload(factory); //解析request请求 List fileItems = upload.parseRequest(req); for (FileItem item:fileItems){ 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"; } } 4.SpringMVC上传文件 4.1原理分析
4.2 代码实现 1.配置文件上传解析器
2.准备页面 springmvc: 选择文件 :3.编写控制层 @RequestMapping(value = "/upload1") public String upload1(MultipartFile file, HttpServletRequest req ) throws IOException { System.out.println("文件上传。。。"); String path = req.getSession().getServletContext().getRealPath("/uploads/"); File f = new File(path); if (!f.exists()){ f.mkdirs(); } //获取文件名称 String fileName = file.getOriginalFilename(); String uuid = UUID.randomUUID().toString().replace("-", "") ; fileName = uuid + fileName.hashCode(); file.transferTo(new File(path,fileName)); return "success"; } 说明:文件解析器的id 必须是 multipartResolver ,另外页面中 input type="file" name="file" name值要与控制层中的 MultipartFile file 参数名一致。 5.跨服务器上传文件 实际开发中,会有很多处理不同功能的服务器。 应用服务器:部署应用 数据服务器:运行数据库 缓存服务器:redis缓存 文件服务器:存储文件 5.1 跨服务器上传原理图例
5.2 代码实现 1.导入依赖
com.sun.jersey jersey-core 1.9 com.sun.jersey jersey-client 1.19 2.准备页面 springmvc跨服务器上传: 选择文件 :3.代码实现 @RequestMapping(value = "/upload2") public String upload2(MultipartFile file) throws IOException { //1.定义上传路径 String path = "http://xxx.xxx.xxx.xxx/uploads/"; //2.获取文件名称 String fileName = file.getOriginalFilename(); String uuid = UUID.randomUUID().toString().replace("-", "") ; fileName = uuid + fileName.hashCode(); //3.创建客户端 com.sun.jersey.api.client.Client; Client client = Client.create(); //4.和图片服务器进行连接 WebResource webResource = client.resource(path + fileName); //5.上传文件 webResource.put(file.getBytes()); return "success"; } 常见错误: https://blog.csdn.net/NewObjectMe/article/details/103840456 三、异常处理 1、图例说明
2、编写自定义异常类
3、配置异常处理器(跳转友好提示页) 需要实现 HandlerExceptionResolver 接口
在springmvc配置自己写的异常处理类
四、拦截器 1.说明图例
2.编写自定义拦截器 package com.jredu.interceptor; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /**
- 自定义拦截器
/
public class MyInterceptor implements HandlerInterceptor {
/*
- 预处理,在Controller执行之前执行
- @param request * @param response
- @param handler
- @return true 放行 false不放行
- @throws Exception / public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("拦截器生效"); return true; } /*
- 后处理方法,也就是controller执行完毕之后在执行
- @param request
- @param response
- @param handler
- @param modelAndView / @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } /*
- 页面执行后,会触发执行
- @param request
- @param response
- @param handler
- @param ex
- @throws Exception */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
} } 3.配置拦截器
mvc:interceptors mvc:interceptor
<mvc:mapping path="/user/**"/>
</mvc:interceptor> </mvc:interceptors>