当前位置: 首页 > news >正文

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) {
    ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
 resolver.setContentNegotiationManager((ContentNegotiationManager)beanFactory.getBean(ContentNegotiationManager.class));
    resolver.setOrder(-2147483648);
return resolver;
}

 

当我们做文件上传的时候我们也会发现multipartResolver自动被配置好的

页面

<form action="/upload" method="post" enctype="multipart/form-data">
<input name="pic" type="file">
<input type="submit">
</form>

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
public class MyMVCCofnig implements WebMvcConfigurer{
@Override
public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/tx").setViewName("success");
    }

}

​​​​​​​​​​​​​​注册格式化器

用来可以对请求过来的日期格式化的字符串来做定制化。当然通过application.properties配置也可以办到。

@Override
public void addFormatters(FormatterRegistry registry) {
    registry.addFormatter(new Formatter<Date>() {
@Override
public String print(Date date, Locale locale) {
return null;
        }
@Override
public Date parse(String s, Locale locale) throws ParseException {
return new SimpleDateFormat("yyyy-MM-dd").parse(s);
        }
    });
}

​​​​​​​消息转换器扩展fastjson

在pom.xml中引入fastjson

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>

配置消息转换器,添加fastjson

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    FastJsonHttpMessageConverter fc = new FastJsonHttpMessageConverter();
    FastJsonConfig fastJsonConfig = new FastJsonConfig();
    fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
    fc.setFastJsonConfig(fastJsonConfig);
    converters.add(fc);
}

在实体类上可以继续控制

public class User
{

private  String username;

private  String password;

private int age;

private int score;

private int gender;

@JSONField(format = "yyyy-MM-dd")
private Date date;

​​​​​​​拦截器注册

创建拦截器

public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("前置拦截");
return true;
    }
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("后置拦截");
    }
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("最终拦截");
    }
}

拦截器注册

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new MyInterceptor())
            .addPathPatterns("/**")
            .excludePathPatterns("/hello2");
}

http://www.dtcms.com/a/297616.html

相关文章:

  • 基于Docker的GPU版本飞桨PaddleOCR部署深度指南(国内镜像)2025年7月底测试好用:从理论到实践的完整技术方案
  • 【赵渝强老师】MySQL中的数据库对象
  • 7月25号打卡
  • 海康监控集中管理解决方案全面分析
  • 设计仿真 | Simufact Forming模具疲劳分析助力预测模具寿命
  • 基于单片机的楼宇门禁系统的设计与实现
  • 目标导向的强化学习:问题定义与 HER 算法详解—强化学习(19)
  • [特殊字符] GitHub 2025年7月月度精选项目 Top5
  • Java NIO FileChannel在大文件传输中的性能优化实践指南
  • Movavi Video Editor v25.9.0 视频编辑软件中文特别版
  • Pytorch中cuda相关操作详见和代码示例
  • 【Chrome】下载chromedriver的地址
  • 线性代数 下
  • Chrome(谷歌)浏览器 数据JSON格式美化
  • JAVA知识点(六):性能调优与线上问题排查
  • vue+iview+i18n国际化
  • Day 3: 机器学习进阶算法与集成学习
  • 《Uniapp-Vue 3-TS 实战开发》自定义环形进度条组件
  • Zookeeper 3.6.3【详细技术讲解】整
  • Uniapp编写微信小程序,绘制动态圆环进度条
  • Welcome to the world of Go language
  • 鸿蒙端云一体化开发之创建和操作数据库
  • 内存 管理
  • 重读《人件》Peopleware -(22)Ⅲ 适当人选 Ⅵ 乐在其中(上)
  • 微服务架构中的资源调度与负载均衡实践
  • 股指期权可以随时平仓吗?
  • OSPF之多区域
  • cha的操作
  • 每日面试题14:CMS与G1垃圾回收器的区别
  • 2025.07.25【宏基因组】|PathoScope 安装与使用指南