Springboot整合springmvc
Springmvc的自动解管理
中央转发器(DispatcherServlet)
控制器
视图解析器
静态资源访问
消息转换器
格式化
静态资源管理
中央转发器
Xml无需配置
<servlet>
<servlet-name>chapter2</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>chapter2</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
控制器
控制器Controller在springboot的注解扫描范围内自动管理。
视图解析器自动管理
Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.
ContentNegotiatingViewResolver:组合所有的视图解析器的;
曾经的配置文件无需再配
<bean id="de" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value="*.jsp"></property>
</bean>
源码:
public ContentNegotiatingViewResolver viewResolver(BeanFactory beanFactory) { |
当我们做文件上传的时候我们也会发现multipartResolver是自动被配置好的
页面
<form action="/upload" method="post" enctype="multipart/form-data"> |
Controller
@ResponseBody
@RequestMapping("/upload")
public String upload(@RequestParam("pic")MultipartFile file, HttpServletRequest request){
String contentType = file.getContentType();
String fileName = file.getOriginalFilename();
/*System.out.println("fileName-->" + fileName);
System.out.println("getContentType-->" + contentType);*/
//String filePath = request.getSession().getServletContext().getRealPath("imgupload/");
String filePath = "D:/imgup/";
try {
this.uploadFile(file.getBytes(), filePath, fileName);
} catch (Exception e) {
// TODO: handle exception
}
return "success";
}
public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath);
if(!targetFile.exists()){
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath+fileName);
out.write(file);
out.flush();
out.close();
}
消息转换和格式化
格式化转换器的自动注册
Springboot扩展springmvc
我们可以来通过实现WebMvcConfigurer接口来扩展
在容器中注册视图控制器(请求转发)
@Configuration } |
注册格式化器
用来可以对请求过来的日期格式化的字符串来做定制化。当然通过application.properties配置也可以办到。
@Override |
消息转换器扩展fastjson
在pom.xml中引入fastjson
<dependency> |
配置消息转换器,添加fastjson
@Override |
在实体类上可以继续控制
public class User |
拦截器注册
创建拦截器
public class MyInterceptor implements HandlerInterceptor { |
拦截器注册
@Override |