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>

中央轉發器被springboot自動接管,不再需要我們在web.xml中配置,我們現在的項目也不是web項目,也不存在web.xml,

org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,

?控制器

控制器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();
}

文件上傳大小可以通過配置來修改
打開application.properties, 默認限制是10MB,我們可以任意修改

@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();
}

文件上傳大小可以通過配置來修改
打開application.properties, 默認限制是10MB,我們可以任意修改

二、消息轉換和格式化

?Springboot自動配置了消息轉換器

格式化轉換器的自動注冊?

時間類型我們可以在這里修改?

在配置文件中指定好時間的模式我們就可以輸入了?

?三、springboot自動擴展SpringMVC

在實際開發中springboot并非完全自動化,很多跟業務相關我們需要自己擴展,springboot給我提供了接口。

我們可以來通過實現WebMvcConfigurer接口來擴展

public interface WebMvcConfigurer {
default void configurePathMatch(PathMatchConfigurer configurer) {
}

default void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
}

default void configureAsyncSupport(AsyncSupportConfigurer configurer) {
}

default void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
}

default void addFormatters(FormatterRegistry registry) {
}

default void addInterceptors(InterceptorRegistry registry) {
}

default void addResourceHandlers(ResourceHandlerRegistry registry) {
}

default void addCorsMappings(CorsRegistry registry) {
}

default void addViewControllers(ViewControllerRegistry registry) {
}

default void configureViewResolvers(ViewResolverRegistry registry) {
}

default void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
}

default void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> handlers) {
}

default void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
}

default void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
}

default void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
}

default void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
}

@Nullable
default Validator getValidator() {
return null;
}

@Nullable
default MessageCodesResolver getMessageCodesResolver() {
return null;
}
}

3.1 在容器中注冊視圖控制器(請求轉發)?

創建一個MyMVCCofnig實現WebMvcConfigurer接口,實現一下addViewControllers方法,我們完成通過/tx訪問,轉發到success.html的工作

@Configuration
public class MyMVCCofnig implements WebMvcConfigurer{
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController(
"/tx").setViewName("success");
}

}

3.2 注冊格式化

?用來可以對請求過來的日期格式化的字符串來做定制化。當然通過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);
}
});
}

3.3 消息轉換器擴展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;

?3.4 攔截器注冊

1.創建攔截器

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("最終攔截");
}
}

2. 攔截器注冊

?

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

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/pingmian/90298.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/90298.shtml
英文地址,請注明出處:http://en.pswp.cn/pingmian/90298.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

C#_定時器_解析

問題一:這里加lock是啥意思?它的原理是, 為什么可以鎖住? private readonly Timer _timer;/// <summary>/// 構造函數中初始化定時器/// </summary>public FtpTransferService(){// 初始化定時器_timer new Timer(_intervalMinutes * 60 * 1000);_timer.Elapsed…

Trae開發uni-app+Vue3+TS項目飄紅踩坑

前情 Trae IDE上線后我是第一時間去使用體驗的&#xff0c;但是因為一直排隊問題不得轉戰Cursor&#xff0c;等到Trae出付費模式的時候&#xff0c;我已經辦了Cursor的會員&#xff0c;本來是想等會員過期了再轉戰Trae的&#xff0c;但是最近Cursor開始做妖了 網上有一堆怎么…

低代碼中的統計模型是什么?有什么作用?

低代碼開發平臺中的統計模型是指通過可視化配置、拖拽操作或少量代碼即可應用的數據分析工具&#xff0c;旨在幫助技術人員及非技術人員快速實現數據描述、趨勢預測和業務決策。其核心價值在于降低數據分析門檻&#xff0c;使業務人員無需深入掌握統計原理或編程技能&#xff0…

Linux 下在線安裝啟動VNC

描述 Linux中的VNC就類似于Windows中的遠程桌面系統 本文只記錄在Cent OS 7的系統下在線安裝VNC。 安裝VNC 1、安裝VNC yum install tigervnc-server2、配置VNC的密碼 為用戶設置 VNC 密碼&#xff08;首次運行會提示輸入&#xff0c;也可以提前輸入&#xff09; vncpasswd密碼…

支持OCR和AI解釋的Web PDF閱讀器:解決大文檔閱讀難題

支持OCR和AI解釋的Web PDF閱讀器&#xff1a;解決大文檔閱讀難題一、背景&#xff1a;為什么需要這個工具&#xff1f;問題場景解決方案二、技術原理&#xff1a;如何實現這些功能&#xff1f;1、核心技術組件2、工作流程3、關鍵點三、操作指南1、環境準備2、生成Html代碼3、We…

研發過程都有哪些

產品規劃與定義 (Product Planning & Definition) 在詳細的需求調研之前&#xff0c;通常會進行市場分析、競品分析、確立產品目標和核心價值。這個階段決定了“我們要做什么”以及“為什么要做”。 系統設計與架構 (System & Architectural Design) 這是開發的“藍圖”…

舊物回收小程序系統開發——開啟綠色生活新篇章

在當今社會&#xff0c;環保已經成為全球關注的焦點話題。隨著人們生活水平的提高&#xff0c;消費能力不斷增強&#xff0c;各類物品的更新換代速度日益加快&#xff0c;大量舊物被隨意丟棄&#xff0c;不僅造成了資源的巨大浪費&#xff0c;還對環境產生了嚴重的污染。在這樣…

UE5 UI 水平框

文章目錄slot區分尺寸和對齊方式尺寸&#xff1a;自動模式尺寸&#xff1a;填充模式對齊常用設置所有按鈕大小一致&#xff0c;不受文本影響靠右排列和unity的HorizontalLayout不太一樣slot 以在水平框中放入帶文字的按鈕為例 UI如下布置 按鈕的大小受slot的尺寸、對齊和內部…

【Golang】Go語言變量

Go語言變量 文章目錄Go語言變量一、Go語言變量二、變量聲明2.1、第一種聲明方式2.2、第二種聲明方式2.3、第三種聲明方式2.4、多變量聲明2.5、打印變量占用字節一、Go語言變量 變量來源于數學&#xff0c;是計算機語言中能存儲計算結果或能表示值抽象的概念變量可以通過變量名…

Qt WebEngine Widgets的使用

一、Qt WebEngine基本概念Qt WebEngine中主要分為三個模塊&#xff1a;Qt WebEngine Widgets模塊&#xff0c;主要用于創建基于C Widgets部件的Web程序&#xff1b;Qt WebEngine模塊用來創建基于Qt Quick的Web程序&#xff1b;Qt WebEngine Core模塊用來與Chromeium交互。網頁玄…

【C++】標準模板庫(STL)—— 學習算法的利器

【C】標準模板庫&#xff08;STL&#xff09;—— 學習算法的利器學習 STL 需要注意的幾點及 STL 簡介一、什么是 STL&#xff1f;二、學習 STL 前的先修知識三、STL 常見容器特點對比四、學習 STL 的關鍵注意點五、STL 學習路線建議六、總結七、下一章 vector容器快速上手學習…

YOLO算法演進綜述:從YOLOv1到YOLOv13的技術突破與應用實踐,一文掌握YOLO家族全部算法!

引言&#xff1a;介紹目標檢測技術背景和YOLO算法的演進意義。YOLO算法發展歷程&#xff1a;使用階段劃分方式系統梳理各代YOLO的技術演進&#xff0c;包含早期奠基、效率優化、注意力機制和高階建模四個階段。YOLOv13的核心技術創新&#xff1a;詳細解析HyperACE機制、FullPAD…

快速將前端得依賴打為tar包(yarn.lock版本)并且推送至nexus私有依賴倉庫(筆記)

第一步創建js文件 文件名為downloadNpmPackage.jsprocess.env.NODE_TLS_REJECT_UNAUTHORIZED "0";const fs require("fs"); const path require("path"); const request require("request");// 設置依賴目錄 const downUrl "…

Unity VS Unreal Engine ,“電影像游戲的時代” 新手如何抉擇引擎?(結)

Unity VS Unreal Engine &#xff0c;“電影像游戲的時代” 新手如何抉擇引擎&#xff1f;(1)-CSDN博客 這是我的上一篇文章&#xff0c;如果你仍然困惑選擇引擎的事情&#xff0c;我們不妨從別的方面看看 注意&#xff1a;我們可能使用"UE5"來表示Unreal Engine系…

EVAL長度限制突破方法

EVAL長度限制突破方法 <?php $param $_REQUEST[param]; If (strlen($param) < 17 && stripos($param, eval) false && stripos($param, assert) false) //長度小于17&#xff0c;沒有eval和assert關鍵字 {eval($param); } //stripos — 查找字符串…

Linux部署.net Core 環境

我的環境 直接下載安裝就可以了 wget https://builds.dotnet.microsoft.com/dotnet/Sdk/8.0.315/dotnet-sdk-8.0.315-linux-x64.tar.gzmkdir -p $HOME/dotnet && tar zxf dotnet-sdk-8.0.315-linux-x64.tar.gz -C $HOME/dotnet export DOTNET_ROOT$HOME/dotnet expor…

ARM-定時器-PWM通道輸出

學習內容需求點亮4個燈&#xff0c;采用pwm的方式。定時器通道引腳AFLED序號T3CH0PD12AF2LED5CH1PD13AF2LED6CH2PD14AF2LED7CH3PD15AF2LED8實現LED5, LED6, LED7, LED8呼吸燈效果通用定時器多通道點亮T3定時器下的多個通道的燈。開發流程添加Timer依賴初始化PWM相關GPIO初始化P…

javaSE(List集合ArrayList實現類與LinkedList實現類)day15

目錄 List集合&#xff1a; 1、ArrayList類&#xff1a; &#xff08;1&#xff09;數據結構&#xff1a; &#xff08;2&#xff09;擴容機制 &#xff08;3&#xff09;ArrayList的初始化&#xff1a; &#xff08;4&#xff09;ArrayList的添加元素方法 &#xff08;5…

解決 WSL 中無法訪問 registry-1.docker.io/v2/,無法用 docker 拉取 image

文章目錄無法拉取docker鏡像補充遷移 WSL 位置Install Docker無法拉取docker鏡像 docker run hello-world Unable to find image hello-world:latest locally docker: Error response from daemon: Get "https://registry-1.docker.io/v2/": context deadline excee…

【C++】簡單學——list類

模擬實現之前需要了解的概念帶頭雙向鏈表&#xff08;double-linked&#xff09;&#xff0c;允許在任何位置進行插入區別相比vector和string&#xff0c;多了這個已經沒有下標[ ]了&#xff0c;因為迭代器其實才是主流&#xff08;要包頭文件<list>&#xff09;方法構造…