【2021-11-22】心態上的一個錯誤糾正
SpringMVC學習
一、SpringMVC概述
- SpringMVC是基於Java實現了MVC模型的輕量級Web框架。
二、SpringMVC開發
2.1、基於配置開發
2.1.1、相關依賴匯入
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.itheima</groupId> <artifactId>SpringMVC01</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <!--servlet 3.1規範--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!--jsp座標--> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <!--spring座標--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.9.RELEASE</version> </dependency> <!--springWeb座標--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.1.9.RELEASE</version> </dependency> <!--spring-mvc座標--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.9.RELEASE</version> </dependency> <!--lombok相關依賴(需要下載相關的外掛)--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.6</version> </dependency> <!--json相關座標3個--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.9.0</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <target>1.8</target> <source>1.8</source> <encoding>utf-8</encoding> </configuration> </plugin> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <port>80</port> <path>/</path> </configuration> </plugin> </plugins> </build> </project>
2.1.2、核心配置檔案
1、在resources中定義spring-mvc.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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> // Controller 處理之後的結果會被拼接這個地址,轉發到對應JSP檔案總展示 <!-- 檢視分解解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 這是字首 --> <property name="prefix" value="/"></property> <!-- 這是字尾 --> <property name="suffix" value=".jsp"></property> <!-- 在spring的控制器中,返回的是一個字串,那麼請求的路徑則是,字首+返回字串+字尾 --> </bean> // “ /test ”是前端拼接的地址,對應的請求會被 class 對應的 Controller 處理 <bean name="/test" class="com.itheima.controller.TestController"></bean> </beans>
2、在WEB-INFO檔案的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> <!--伺服器已啟動就會載入dispatcherServlet--> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--伺服器啟啟動之後,就會讀取spring-mvc.xml中配置,載入"xx"路徑下的所有標記為bean的類--> <!-- 配置DispatcherServlet的一個初始化引數:配置SpringMVC配置檔案位置和名稱,這個也可以不配置,如果不配置,則預設是WEB-INFO下的springMVC-servlet.xml --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:applicationcontent.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> </web-app>
1、springmvc配置攔截的三種方式
- " / ": 攔截所有請求但是不包括JSP頁面,但是會攔截靜態頁面如:img、js、css
- " /* " : 攔截所有請求包括JSP頁面
- “ *.do ” : 所以以“ .do ”結尾的前端請求都會被攔截
2.1.3、定義一個類作為控制器
1、方式一:實現“ Controller “ 介面,重寫裡面方法。
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestController implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndViw mv = new ModelAndView();
// 設定訪問jsp檔案的地址
mv.setViewNew("/hello.jsp");
// 設定需要返回的資訊
mv.addObject("msg","welcome to springmvc");
return mv;
}
}
2、方式二:實現” HttpRequestHandler “ 介面,重寫裡面的方法。
public class TestController implements HttpRequestHandler
public void handleRequest(HttpServlertRequest request,HttpServlertResponse response) throws ServletException,IOException{
System.out.println("welcome to springmvc");
}
注:需要把建立對應的Controller 在 spring-mvc.xml檔案中註冊成Bean,交給Spring容器進行管理。
2.2、基於註解開發
2.2.1、相關依賴匯入
- 和基於配置檔案開發匯入的依賴一致
2.2.2、核心配置檔案
1、在resources中定義spring-mvc.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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 定義掃描的包 -->
<context:component-scan base-package="被掃描包的全路徑類名"/>
<!--開啟SpringMVC註解驅動-->
<mvc:annotation-driven conversion-service="conversionService"/>
// Controller 處理之後的結果會被拼接這個地址,轉發到對應JSP檔案總展示
<!-- 檢視分解解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 這是字首 -->
<property name="prefix" value="/"></property>
<!-- 這是字尾 -->
<property name="suffix" value=".jsp"></property>
<!-- 在spring的控制器中,返回的是一個字串,那麼請求的路徑則是,字首+返回字串+字尾 -->
</bean>
</beans>
2、在WEB-INFO檔案的web.xml檔案中定義相關配置
- 和基於配置檔案開發進行的配置檔案一致。
2.2.3、定義一個類作為控制器
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @Controller是控制器的註解
*/
@Controller
@RequestMapping("/test")
public class UserController {
@RequestMapping("/save")
public String save() {
System.out.println("save is run .....");
return "/success.jsp";
}
@RequestMapping("/requestParam")
public String requestParam(String name){
System.out.println(name);
return "/success.jsp";
}
}
注:@RequestMapping("/test")這裡的“ /test ”,作為父類的路徑,前端請求的url地址為:http://localhost:8080/test/save,類裡面的每個方法請求的都會加上這個字首,其也可以不進行配置。如果不配置前端的訪問地址為:http://localhost:8080/save。
2.3、基於java程式碼開發
2.3.1、相關依賴匯入
- 和基於配置檔案開發匯入的依賴一致
2.3.2、配置類的建立
1、定義配置類代替“ 在resources中定義spring-mvc.xml檔案 ”。
@Configuration
@ComponentScan("com.itheima.controller") // 指定包掃描的位置
@EnableWebMvc //mvc的註解驅動
public class SpringMVCConfig implements WebMvcConfigurer {
// 註解配置放行指定資源格式
/* public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/img/**").addResourceLocations("/img/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
registry.addResourceHandler("/css/**").addResourceLocations("/css/");
}*/
/**
* 放行靜態資原始檔 (一般配置這種方式就可以)
* @param configurer
*/
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
==**注意:**==替代Spring-mvc.xml檔案,必須實現WebMvcConfigurer介面。
==**注意:**==之前spring-mvc.xml檔案是在web.xml中讀取的,我們知道,伺服器啟動時,會自動解析web.xml;那麼當我們採用純註解配置時,如何自動去解析該配置類呢。這裡我們會用到之前咱們提到的spi機制。
2、定義配置類代替“ 在WEB-INFO檔案的web.xml檔案 ”
package com.itheima.config;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;
import javax.servlet.Filter;
// 該類中onStartup方法會在伺服器啟動時自動執行
public class WebConfig extends AbstractDispatcherServletInitializer {
// 配置Springmvc容器,載入web層bean
protected WebApplicationContext createServletApplicationContext() {
AnnotationConfigWebApplicationContext acwc = new AnnotationConfigWebApplicationContext();
acwc.register(SpringMVCConfig.class);
return acwc;
}
// 配置DispatcherServlet的訪問路徑
protected String[] getServletMappings() {
return new String[]{"/"};
}
// 配置Spring容器,載入service層和dao層bean
protected WebApplicationContext createRootApplicationContext() {
AnnotationConfigWebApplicationContext acwc = new AnnotationConfigWebApplicationContext();
acwc.register(SpringConfig.class);
return acwc;
}
// 新增Post請求引數亂碼過濾器
protected Filter[] getServletFilter(){
CharacterEncodingFilter cef = new CharacterEncodingFilter();
cef.setEncoding("utf-8");
cef.setForceEncoding(true);
return new Filter[]{cef};
}
}
2.3.2、定義一個類作為控制器
- 和基於註解開發定義的“ Controller ”一致。
三、SpringMVC請求
3.1、請求地址獲取
- 1、@RequestMapping 獲取請求url:
● 註解用於獲取請求的url地址,其可以加在類上和方法上。加上類有作為父路徑的作用,所以類中的方法的請求地址都會拼接類上的路徑。
2、@RequestMapping 設定請求方式:
● @RequestMapping(value="/testMethod",method=RequestMethod.POST),其中" method "就是用於指定請求方式。
● @RequestMapping(value="/testMethod",method=RequestMethod.POST,method=RequestMethod.GET),支援POST和GET兩種方式。
● @RequestMapping(value="/testMethod"),預設支援兩種請求方式。
3、@RequestMapping 引數對映配合註解 @PathVariable使用
@RequestMapping(value="/detail/{id}", method = {RequestMethod.GET})
public ModelAndView getDetail(@PathVariable(value="id") Integer id){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("id", id);
modelAndView.setViewName("detail");
return modelAndView;
}
請求地址:http://localhost:8080/detail/123
4、URL萬用字元設定:
● 我們還可以通過萬用字元對URL對映進行配置。
○ “?”: 表示 1 個字元。
○ “*”:表示匹配多個字元。
○ “**”:表示匹配0個或多個路徑。
5、URL正則表示式對映:
@RequestMapping(value="/reg/{name:\w+}-{age:\d+}", method = {RequestMethod.GET})
public ModelAndView regUrlTest(@PathVariable(value="name") String name, @PathVariable(value="age") Integer age){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("name", name);
modelAndView.addObject("age", age);
modelAndView.setViewName("regurltest");
return modelAndView;
}
請求地址:http://localhost:8080/reg/Lihua-18 該訪問地址能正常訪問。
請求地址:http://localhost:8080/reg/Lihua-xx 該訪問地址不能正常訪問。
6、限制URL所接收的請求引數:
● 指定對映請求必須包含某個引數:@RequestMapping(value="/paramstest", params="example")
○ 地址:http://localhost:8080/paramstest?example ,必須包含“example”才能正確訪問。
● 指定對映請求必須不包含某個引數:@RequestMapping(value="/paramstest", params="!example")
○ 地址:http://localhost:8080/paramstest?example ,包含“example”不能正確訪問。
● 指定對映請求中或者某引數必須等於某個值:@RequestMapping(value="/paramstest", params="example=test")
○ 地址:http://localhost:8080/paramstest?example=test ,example=test才能正確訪問。
● 指定對映請求中或者某引數必須不等於某個值:@RequestMapping(value="/paramstest", params="example=!test")
○ 地址:http://localhost:8080/paramstest?example=test ,example=!test才能正確訪問。
● 當我們為params指定多個引數時如:params={"example1", "example2"},表示的是and關係,即兩個引數限制必須同時滿足。
7、限制URL所接收請求頭引數:
● 指定對映請求頭必須包含某引數:@RequestMapping(value="/headerTest", headers = "example")
● 指定對映請求頭必須不包含某引數:@RequestMapping(value="/headerTest", headers = "!example")。
● .指定對映請求頭中或者某引數必須等於某個值:@RequestMapping(value="/headerTest", headers = "Accept=text/html")。
● .指定對映請求頭中或者某引數必須不等於某個值:@RequestMapping(value="/headerTest", headers = "Accept!=text/html")。
● 當我們為headers指定多個引數時如:headers={"example1", "example2"},表示的是and關係,即兩個引數限制必須同時滿足。