一.SpringMVC的請求:
新建web項目:pom.xml的座標導入:
<dependencies>
<!--mysql驅動-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--druid連接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.15</version>
</dependency>
<!--spring-jdbc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!--spring核心-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--spring整合junit-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
<!--springMVC-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!--servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!--jsp-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
(1)請求參數:
客戶端請求參數的格式是:name=value&name=value……
服務器要獲取請求的參數,有時還需要進行數據的封裝,SpringMVC可以接收如下類型的參數:
① 簡單類型
基本類型,基本類型的包裝類型,字符串
index.jsp
<h1>簡單類型參數訪問</h1>
<a href="${pageContext.request.contextPath}/user/simpleParam?username=java&age=19">簡單參數接收</a>
UserController
@Controller
@RequestMapping("/user")
public class UserController {
//簡單參數
@RequestMapping("/simpleParam")
public String simpleParam(String username,Integer age){
System.out.println("姓名:"+username);
System.out.println("年齡:"+age);
return "success";
}
}
注意:前端頁面的name屬性名必須與方法中的形參名稱一致,類型自定義
② 對象類型
User
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private String username;
private Integer age;
}
<h1>對象類型</h1>
<form action="${pageContext.request.contextPath}/user/objectParam" method="post">
用戶名:<input type="text" name="username"> <br>
年齡:<input type="text" name="age"><br>
<input type="submit" value="提交">
</form>
UserController
//對象參數
@RequestMapping("/objectParam")
public String objectParam(User user){
System.out.println(user);
return "success";
}
注意:表單元素的name屬性必須和user實體的屬性名一致
③ 數組類型
應用場景:批量刪除
index.jsp
<h1>數組類型</h1>
<form action="${pageContext.request.contextPath}/user/arrayParam" method="post">
<input type="checkbox" name="hobby" value="1" >足球 <br>
<input type="checkbox" name="hobby" value="2" >籃球 <br>
<input type="checkbox" name="hobby" value="3" >乒乓球 <br>
<input type="checkbox" name="hobby" value="4" >游泳 <br>
<input type="checkbox" name="hobby" value="5" >爬山 <br>
<input type="submit" value="愛好" > <br>
</form>
UserController
//數組參數
@RequestMapping("/arrayParam")
public String arrayParam(Integer[] hobby){
System.out.println(Arrays.toString(hobby));
return "success";
}
注意:複選框的name屬性名必須與數組的變量名一致:
④ 集合(複雜)類型
如果提交的是一個集合的數據,springMVC的方法形參是無法接收的,必須要通過實體類進行包裝纔行
QueryVo
@Data
@NoArgsConstructor
@AllArgsConstructor
public class QueryVo {
private String orderId;
private User user;
private Integer[] hobby;
private List<Object> list;
private Map<String,Object> map;
}
index.jsp
<h1>複合類型</h1>
<form action="${pageContext.request.contextPath}/user/allTypeParam" method="post">
訂單id:
<input type="text" name="orderId" value="1" > <br>
用戶名:<input type="text" name="user.username"> <br>
年齡:<input type="text" name="user.age"><br>
愛好:
<input type="checkbox" name="hobby" value="1" >足球 <br>
<input type="checkbox" name="hobby" value="2" >籃球 <br>
<input type="checkbox" name="hobby" value="3" >乒乓球 <br>
<input type="checkbox" name="hobby" value="4" >游泳 <br>
<input type="checkbox" name="hobby" value="5" >爬山 <br>
list集合
<%--
list[0] == 第一個元素
list[1] == 第二個元素
--%>
<input type="text" name="list[0]" placeholder="第一個元素">
<input type="text" name="list[1]" placeholder="第二個元素">
<input type="text" name="list[2]" placeholder="第三個元素"> <br>
map集合
<%--
map.put("key1",value);
map.put("key2",value);
--%>
<input type="text" name="map['key1']" placeholder="key1的值...">
<input type="text" name="map['key2']" placeholder="key2的值..."><br>
<input type="submit" value="複雜類型">
</form>
UserController
//複雜參數
@RequestMapping("/allTypeParam")
public String allTypeParam(QueryVo queryVo){
System.out.println(queryVo);
return "success";
}
(2)中文亂碼過濾器:
如果是get請求,tomcat8以上版本的服務器統一了UTF-8編碼,所以不會出現亂碼
如果是post請求,由於servlet規範當中post默認解碼方式爲:ISO-8859-1,所以出現了中文亂碼問題:
Spring框架提供了post請求中文過濾器
在web.xml 文件中配置如下即可:
<filter>
<filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
(3)自定義類型轉換器
應用場景:日期格式:
springMVC框架默認將字符串轉爲日期對象的格式爲(yyyy/MM/dd),這種格式在國內並不流行...
我們已經習慣使用了(yyyy-MM-dd),這時框架無法識別,頁面出現400的錯誤
所以springMVC考慮全面 ..支持了自定義類型轉換器的擴展...
自定義類型轉換器:
/*
自定義日期類型轉換器(yyyy-MM-dd)
*/
public class DateConverter implements Converter<String, Date> {
@Override
public Date convert(String source) { // 字符串 (yyyy-MM-dd)
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = simpleDateFormat.parse(source);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
spring-mvc.xml配置:
index.jsp
<h1>日期</h1>
<form action="${pageContext.request.contextPath}/user/getDate" method="post">
生日:<input type="date" name="birthday"> <br>
<input type="submit" value="日期">
</form>
UserController
//=============================================日期相關:
@RequestMapping("/getDate")
public String getDate(Date birthday){
System.out.println(birthday);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(simpleDateFormat.format(birthday));
return "success";
}
註解方案:
需要把spring-mvc文件裏的 關於時間轉換的內容註釋掉:然後修改UserController即可:
//=============================================日期相關:
@RequestMapping("/getDate")
public String getDate(@DateTimeFormat(pattern = "yyyy-MM-dd") Date birthday){
System.out.println(birthday);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(simpleDateFormat.format(birthday));
return "success";
}
(4)其他相關注解
① @RequestParam
應用場景:分頁查詢:
index.jsp
<h1>分頁參數RequestParam</h1>
<a href="${pageContext.request.contextPath}/user/findByPage?pageNum=1&size=10">分頁查詢</a>
UserController
//=============================================分頁查詢:
// 分頁查詢
/*
@RequestParam 註解
常用屬性
name/value:幫我們解決請求參數名和方法的變量名不一致問題.....
required: 默認值爲true,要求前端必須提交參數和值...
defaultValue:指定參數的默認值
*/
@RequestMapping("/findByPage")
public String findByPage(@RequestParam(name = "pageNum",defaultValue = "1") Integer currentPage,@RequestParam(name = "size",defaultValue = "10") Integer pageSize){
System.out.println("==="+currentPage);
System.out.println("==="+pageSize);
return "success";
}
② @RequestHeader
獲取請求頭,相當於:request.getHeader();
index.jsp
<h1>請求頭信息</h1>
<a href="${pageContext.request.contextPath}/user/requestHeader">請求頭信息</a>
UserController
//=============================================獲取請求頭信息:
@RequestMapping("/requestHeader")
public String requestHeader(@RequestHeader("User-Agent") String userAgent,@RequestHeader("Cookie") String cookie){
System.out.println("==="+userAgent);
System.out.println("==="+cookie);
return "success";
}
③ @CookieValue
專門獲取指定cookie名稱的值
index.jsp
<h1>cookieValue信息</h1>
<a href="${pageContext.request.contextPath}/user/cookieValue">回去指定cookies信息</a>
UserController
//=============================================獲取指定CookieValue
@RequestMapping("/cookieValue")
public String cookieValue(@CookieValue("JSESSIONID") String jsessionid){
System.out.println("jsessionid--"+jsessionid);
return "success";
}
(5)獲取Servlet相關API
我們也可以通過SpringMVC框架,操作Servlet原生API
index.jsp
<h1>servletAPI信息</h1>
<a href="${pageContext.request.contextPath}/user/servletApi?username=jack">servletAPI</a>
UserController
//=============================================獲取servlet相關api
@RequestMapping("/servletApi")
public void servletApi(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws ServletException, IOException{
// 獲取請求參數
String username = request.getParameter("username");
System.out.println(username);
request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request, response);
}
二.文件上傳“”
(1)文件上傳三要素:
-
表單的提交方式 method="POST"
-
表單的enctype屬性是多部分表單形式 enctype=“multipart/form-data"
-
表單項(元素)type="file"
<form action="" method="post" enctype="multipart/form-data">
姓名:<input type="text" name="username"> <br>
頭像:<input type="file" name="picFile"> <br>
</form>
上傳原理:
服務端代碼如何獲得請求體的內容
1.apache提供的file-uplaod工具包【開發中一般不用底層工具包】
2.Servlet3.0【原生servlet開發時使用...】
3.springMVC內置文件上傳(底層集成了file-uplaod)常用
(2)SpringMVC實現文件上傳
需求分析:
第一步:
<form action="${pageContext.request.contextPath}/user/upload"
method="post" enctype="multipart/form-data">
姓名:<input type="text" name="username"> <br>
頭像:<input type="file" name="picFile"> <br>
<input type="submit" value="文件上傳">
</form>
第二步:需要導入apache的文件上傳依賴:
<!--文件上傳-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
修改spring-mvc.xml
<!--
文件上傳組件擴展
id="multipartResolver" 此id必須是這個名稱...
-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--
限定文件的大小....
單位是字節(B)
限制大約在5MB左右...
-->
<property name="maxUploadSize" value="5024000"></property>
</bean>
第三步”
// 文件上傳
@RequestMapping("/upload")
public String upload(String username, MultipartFile picFile) {
System.out.println("普通項:" + username);
System.out.println("文件項:" + picFile);
System.out.println("文件名:" + picFile.getOriginalFilename());
// 保存到一個指定的磁盤目錄
try {
picFile.transferTo(new File("d:\\"+picFile.getOriginalFilename()));
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
三.靜態資源訪問的開啓:
我們在以上項目中訪問靜態資源 01.jpg 圖片時,出現了404問題,但是路徑規則沒問題。
原因:
在SpringMVC的前端控制器DispatcherServlet的url-pattern配置的是 /(缺省),代表除了jsp請求不攔截, 其他的所有請求都會攔截,包括一些靜態文件(html、css、js)等, 而攔截住之後,它又找不到對應的處理器方法來處理, 因此報錯.
開啓方式有三種方式:
(1)方式一:
spring-mvc.xml
<!--
靜態資源手動映射
mapping="/img/**" 瀏覽器發送請求
location="/img/" 靜態資源的路徑
-->
<mvc:resources mapping="/img/**" location="/img/"></mvc:resources>
(2)方式二 常用:
spring-mvc.xml
<!--配置tomcat默認的靜態資源處理-->
<mvc:default-servlet-handler/>
(3)方式三:
web.xml
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<!--
自定義一個不會與默認的tomcat衝突的攔截規則
配置:*.do 之後
什麼情況下才會被sprignMVC框架所攔截????
瀏覽器訪問的資源需要加上:/user/quick.do
所以靜態 123.png my.js my.css a.html 這些就不會被springMVC框架攔截,也就不會出現404的問題了...
-->
<url-pattern>*.do</url-pattern>
</servlet-mapping>
spring-mvc.xml文件配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--開啓註解組件掃描-->
<context:component-scan base-package="com.wsl.web"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5024000"></property>
</bean>
<!--開啓mvc註解支持-->
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
<!--擴展自定義類型轉換器-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.wsl.web.DateConverter"></bean>
</set>
</property>
</bean>
<!--<mvc:resources mapping="/image/**" location="/image/"></mvc:resources>-->
<!--<mvc:default-servlet-handler></mvc:default-servlet-handler>-->
</beans>