ElasticSearch-索引庫、文件操作
1.1、簡介
SpringMVC是Spring Framework的一部分,是基於Java實現MVC的輕量級框架。
官方文件:Spring Framework Reference Documentation
SpringMVC特點
- 輕量級,簡單易學
- 高效、基於請求響應的MVC框架
- 與Spring相容性好,無縫結合
- 約定大於配置
- 功能強大:RESTful、資料驗證、格式化、本地化、主題、註解、單元測試等
- 簡潔靈活
1.2、Hello SpringMVC
resources/springmvc-servlet.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" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/> <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/> <!--檢視解析器:DispatcherServlet給它的ModelAndView--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver"> <!--字首--> <property name="prefix" value="/WEB-INF/jsp/"/> <!--字尾--> <property name="suffix" value=".jsp"/> </bean> <!--Handler--> <bean id="/hello" class="com.zhang.controller.HelloController"/> </beans>
com.zhang.controller.HelloController
package com.zhang.controller; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author zhangxiny * @apiNote * @date 2021-12-30 20:03 */ public class HelloController implements Controller { public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { //檢視和模型 ModelAndView mv = new ModelAndView(); //封裝物件,放在ModelAndView中。Model mv.addObject("msg", "HelloSpringMVC!"); //封裝要跳轉的檢視,放在ModelAndView中 mv.setViewName("hello"); return mv; } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--關聯一個Spring配置檔案--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-servlet.xml</param-value> </init-param> <!--啟動級別1--> <load-on-startup>1</load-on-startup> </servlet> <!-- / 匹配所有請求:(不包括 jsp)--> <!-- /* 匹配所有請求:(包括jsp)--> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
pom.xml
<!--依賴-->
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
1.3、Spring執行原理
個人理解:SpringMVC底層還是Servlet,在web.xml配置後,SpringMVC就完全代理了Servlet。所以,所有的web請求,全都轉入了SpringMVC。
Spring執行的話,簡單分為三步,第一步是呼叫處理器對映器,有很多種對映方式,選擇得到bean的方式。第二步是呼叫處理器介面卡,將Contrller中的設定解析,並返回ModelAndView類,第三步呼叫檢視解析器,解析檢視並渲染至瀏覽器。
@Component
@Service
@Controller
@Repository
1.4、RestFul風格
優點:
- 請求路徑更加簡潔
- 獲得引數更加方便,框架會自動進行型別轉換
- 通過路徑型別約束訪問的型別,型別不一致,則請求不到對應的方法,會出現 405錯誤。
- 安全,不暴露變數名在url
1.5、重定向與轉發
轉發
@RequestMapping("login")
public String test2(Model model){
model.addAttribute("msg", "login");
return "admin/hello";
}
重定向
@RequestMapping("login")
public String test2(Model model){
model.addAttribute("msg", "login");
return "redirect:/hello1";
}
1.6、接收請求引數
第一種,普通接收
public String test1(String name, Model model){}
http://localhost:9091/user/t1?name=fdada
第二種,指定名稱接收
public String test1(@RequestParam("username") String name, Model model) {
http://localhost:9091/user/t1?username=fdada
第三種,接收物件
public String test2(User user){
http://localhost:9091/user/t2?name=fdada&id=3&age=2
1.7、亂碼問題解決
在web.xml中配置
<!--配置SpringMVC亂碼過濾-->
<filter>
<filter-name>encoding</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>encoding</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>
在tomcat中配置
<Connector port="9091" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
URIEncoding="UTF-8"/>
1.8、Jackson使用
-
匯入包 pom.xml
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.10.5.1</version> </dependency>
-
配置編碼 springmvc-servlet.xml
<mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <constructor-arg value="UTF-8"/> </bean> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper"> <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"> <property name="failOnEmptyBeans" value="false"/> </bean> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
-
使用ObjectMapper將Object轉成json
@ResponseBody @RequestMapping(value="/t1") public String test1() throws JsonProcessingException { User user = new User(1,"張三",32); ObjectMapper mapper = new ObjectMapper(); String str = mapper.writeValueAsString(user); return str; }
-
使用ObjectMapper將LIst轉成json
@RequestMapping(value="/j2") public String json2() throws JsonProcessingException { User user = new User(1,"張三",32); User user1 = new User(1,"張三",32); User user2 = new User(1,"張三",32); User user3 = new User(1,"張三",32); User user4 = new User(1,"張三",32); List<User> userList = new ArrayList<User>(); userList.add(user); userList.add(user1); userList.add(user2); userList.add(user3); userList.add(user4); ObjectMapper mapper = new ObjectMapper(); String str = mapper.writeValueAsString(userList); return str; }
-
封裝工具類 com.zhang.utils
public class JsonUtils { public static String getJson(Object object) throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.writeValueAsString(object); } public static String getJson(Object object,String dateFormat) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); //不使用時間戳的方式 mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); //自定義日期的格式 SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); mapper.setDateFormat(sdf); return mapper.writeValueAsString(object); } }
1.9、fastjson使用
-
匯入包
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.60</version> </dependency>
-
將JSON轉成String
@RequestMapping("j4") public String json4(){ User user = new User(1,"張三",32); User user1 = new User(1,"張三",32); User user2 = new User(1,"張三",32); User user3 = new User(1,"張三",32); User user4 = new User(1,"張三",32); List<User> userList = new ArrayList<User>(); userList.add(user); userList.add(user1); userList.add(user2); userList.add(user3); userList.add(user4); String s = JSON.toJSONString(userList); return s; }
1.10、ssm整合
程式碼包下載:https://zxy-me.oss-cn-beijing.aliyuncs.com/note/ssmbuild.rar