SpringMVC
文章目錄
ssm: mybatis+spring+springMVC MVC三層架構
官方文檔:https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc
javaSE:認真學習
JavaWeb:認真學習
框架: 研究官方文檔,鍛鍊自學能力,鍛鍊筆記能力
SpringMVC + Vue +SpringBoot + SpringBoot +SpringCloud +Linux
Spring:IOC+AOP(重點)
springMVC:springmvc的執行流程!(重點)
springmvc:ssm框架整合
1.回顧MVC
MVC:模型 視圖 控制器
1.1、什麼是MVC
- MVC是模型(Model)、視圖(View)、控制器(Controller)的簡寫,是一種軟件設計規範。
- 是將業務邏輯、數據、顯示分離的方法來組織代碼。
- MVC主要作用是降低了視圖與業務邏輯間的雙向偶合。
- MVC不是一種設計模式,MVC是一種架構模式。當然不同的MVC存在差異。
Model(模型): 數據模型,提供要展示的數據,因此包含數據和行爲,可以認爲是領域模型或JavaBean組件(包含數據和行爲),不過現在一般都分離開來:Value Object(數據Dao) 和 服務層(行爲Service)。也就是模型提供了模型數據查詢和模型數據的狀態更新等功能,包括數據和業務。
View(視圖): 負責進行模型的展示,一般就是我們見到的用戶界面,客戶想看到的東西。
Controller(控制器): 接收用戶請求,委託給模型進行處理(狀態改變),處理完畢後把返回的模型數據返回給視圖,由視圖負責展示。也就是說控制器做了個調度員的工作。
最典型的MVC就是JSP + servlet + javabean的模式。
1.2、Model1時代
- 在web早期的開發中,通常採用的都是Model1。
- Model1中,主要分爲兩層,視圖層和模型層。
Model1優點:架構簡單,比較適合小型項目開發;
Model1缺點:JSP職責不單一,職責過重,不便於維護;
1.3、Model2時代
Model2把一個項目分成三部分,包括視圖、控制、模型。
- 用戶發請求
- Servlet接收請求數據,並調用對應的業務邏輯方法
- 業務處理完畢,返回更新後的數據給servlet
- servlet轉向到JSP,由JSP來渲染頁面
- 響應給前端更新後的頁面
職責分析:
Controller:控制器
- 取得表單數據
- 調用業務邏輯
- 轉向指定的頁面
Model:模型
- 業務邏輯
- 保存數據的狀態
View:視圖
- 顯示頁面
Model2這樣不僅提高的代碼的複用率與項目的擴展性,且大大降低了項目的維護成本。Model 1模式的實現比較簡單,適用於快速開發小規模項目,Model1中JSP頁面身兼View和Controller兩種角色,將控制邏輯和表現邏輯混雜在一起,從而導致代碼的重用性非常低,增加了應用的擴展性和維護的難度。Model2消除了Model1的缺點。
1.4、回顧Servlet
-
新建一個Maven工程當做父工程!pom依賴!
<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>
-
建立一個Moudle:springmvc-01-servlet , 添加Web app的支持!
-
導入servlet 和 jsp 的 jar 依賴
<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>
-
編寫一個Servlet類,用來處理用戶的請求
package com.kuang.servlet; //實現Servlet接口 public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //取得參數 String method = req.getParameter("method"); if (method.equals("add")){ req.getSession().setAttribute("msg","執行了add方法"); } if (method.equals("delete")){ req.getSession().setAttribute("msg","執行了delete方法"); } //業務邏輯 //視圖跳轉 req.getRequestDispatcher("/WEB-INF/jsp/hello.jsp").forward(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); } }
-
編寫Hello.jsp,在WEB-INF目錄下新建一個jsp的文件夾,新建hello.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Kuangshen</title> </head> <body> ${msg} </body> </html>
-
在web.xml中註冊Servlet
<?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>HelloServlet</servlet-name> <servlet-class>com.kuang.servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/user</url-pattern> </servlet-mapping> </web-app>
-
配置Tomcat,並啓動測試
-
- localhost:8080/user?method=add
- localhost:8080/user?method=delete
MVC框架要做哪些事情
- 將url映射到java類或java類的方法 .
- 封裝用戶提交的數據 .
- 處理請求–調用相關的業務處理–封裝響應數據 .
- 將響應的數據進行渲染 . jsp / html 等表示層數據 .
說明:
常見的服務器端MVC框架有:Struts、Spring MVC、ASP.NET MVC、Zend Framework、JSF;常見前端MVC框架:vue、angularjs、react、backbone;由MVC演化出了另外一些模式如:MVP、MVVM 等等…
2、什麼是SpringMVC
2.1、概述
Spring MVC是Spring Framework的一部分,是基於Java實現MVC的輕量級Web框架。
查看官方文檔:https://docs.spring.io/spring/docs/5.2.0.RELEASE/spring-framework-reference/web.html#spring-web
我們爲什麼要學習SpringMVC呢?
Spring MVC的特點:
- 輕量級,簡單易學
- 高效 , 基於請求響應的MVC框架
- 與Spring兼容性好,無縫結合
- 約定優於配置
- 功能強大:RESTful、數據驗證、格式化、本地化、主題等
- 簡潔靈活
Spring的web框架圍繞DispatcherServlet [ 調度Servlet ] 設計。
DispatcherServlet的作用是將請求分發到不同的處理器。從Spring 2.5開始,使用Java 5或者以上版本的用戶可以採用基於註解形式進行開發,十分簡潔;
正因爲SpringMVC好 , 簡單 , 便捷 , 易學 , 天生和Spring無縫集成(使用SpringIoC和Aop) , 使用約定優於配置 . 能夠進行簡單的junit測試 . 支持Restful風格 .異常處理 , 本地化 , 國際化 , 數據驗證 , 類型轉換 , 攔截器 等等…所以我們要學習 .
最重要的一點還是用的人多 , 使用的公司多 .
2.2、中心控制器
Spring的web框架圍繞DispatcherServlet設計。DispatcherServlet的作用是將請求分發到不同的處理器。從Spring 2.5開始,使用Java 5或者以上版本的用戶可以採用基於註解的controller聲明方式。
Spring MVC框架像許多其他MVC框架一樣, 以請求爲驅動 , 圍繞一箇中心Servlet分派請求及提供其他功能,DispatcherServlet是一個實際的Servlet (它繼承自HttpServlet 基類)。
SpringMVC的原理如下圖所示:
當發起請求時被前置的控制器攔截到請求,根據請求參數生成代理請求,找到請求對應的實際控制器,控制器處理請求,創建數據模型,訪問數據庫,將模型響應給中心控制器,控制器使用模型與視圖渲染視圖結果,將結果返回給中心控制器,再將結果返回給請求者。
2.3、SpringMVC執行原理(重點)
圖爲SpringMVC的一個較完整的流程圖,實線表示SpringMVC框架提供的技術,不需要開發者實現,虛線表示需要開發者實現。
簡要分析執行流程
-
DispatcherServlet表示前置控制器,是整個SpringMVC的控制中心。用戶發出請求,DispatcherServlet接收請求並攔截請求。
我們假設請求的url爲 : http://localhost:8080/SpringMVC/hello
如上url拆分成三部分:
http://localhost:8080 服務器域名
SpringMVC 部署在服務器上的web站點
hello 表示控制器
通過分析,如上url表示爲:請求位於服務器 localhost:8080 上的SpringMVC站點的hello控制器。
-
HandlerMapping爲處理器映射。DispatcherServlet調用HandlerMapping,HandlerMapping根據請求url查找Handler。
-
HandlerExecution表示具體的Handler,其主要作用是根據url查找控制器,如上url被查找控制器爲:hello。
-
HandlerExecution將解析後的信息傳遞給DispatcherServlet,如解析控制器映射等。
-
HandlerAdapter表示處理器適配器,其按照特定的規則去執行Handler。
-
Handler讓具體的Controller執行。
-
Controller將具體的執行信息返回給HandlerAdapter,如ModelAndView。
-
HandlerAdapter將視圖邏輯名或模型傳遞給DispatcherServlet。
-
DispatcherServlet調用視圖解析器(ViewResolver)來解析HandlerAdapter傳遞的邏輯視圖名。
-
視圖解析器將解析的邏輯視圖名傳給DispatcherServlet。
-
DispatcherServlet根據視圖解析器解析的視圖結果,調用具體的視圖。
-
最終視圖呈現給用戶。
如果這個圖不好理解,我又畫了一個便於理解的流程圖,方便大家理解!
爲什麼說MVC原理是重點呢,在實際開發中。我們經常需要自定義一些組件。因此,理解原理是十分必要的!
2.4 組件簡單講解
1、前端控制器DispatcherServlet
作用:接收請求,響應結果,相當於轉發器,中央處理器。
有了DispatcherServlet減少了其它組件之間的耦合度。
2、處理器映射器HandlerMapping
作用:根據請求的url查找Handler
3、處理器適配器HandlerAdapter
作用:按照特定規則(HandlerAdapter要求的規則)去執行Handler
4、處理器Handler(需要程序員開發)
注意:編寫Handler時按照HandlerAdapter的要求去做,這樣適配器纔可以去正確執行Handler
5、視圖解析器View resolver
作用:進行視圖解析,根據邏輯視圖名解析成真正的視圖
6、視圖View(需要程序員開發jsp)
View是一個接口,實現類支持不同的View類型(jsp、freemarker、pdf…)
以上就是簡單的介紹啦!
如果對原理還不理解,那麼就來實戰吧!
實戰出真理!!!
3.第一個MVC程序
Hello,SpringMVC
在上一節中,我們講解了 什麼是SpringMVC以及它的執行原理!
現在我們來看看如何快速使用SpringMVC編寫我們的程序吧!
3.1 配置版
1、新建一個Moudle , springmvc-02-hello , 添加web的支持!
2、確定導入了SpringMVC 的依賴!
3、配置web.xml , 註冊DispatcherServlet
<?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">
<!--1.註冊DispatcherServlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--關聯一個springmvc的配置文件:【servlet-name】-servlet.xml-->
<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>
4、編寫SpringMVC 的 配置文件!名稱:springmvc-servlet.xml : [servletname]-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 http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
5、添加 處理映射器
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
6、添加 處理器適配器
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
7、添加 視圖解析器
<!--視圖解析器: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>
8、編寫我們要操作業務Controller ,要麼實現Controller接口,要麼增加註解;需要返回一個ModelAndView,裝數據,封視圖;
package com.kuang.controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//注意:這裏我們先導入Controller接口
public class HelloController implements Controller {
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
//ModelAndView 模型和視圖
ModelAndView mv = new ModelAndView();
//封裝對象,放在ModelAndView中。Model
mv.addObject("msg","HelloSpringMVC!");
//封裝要跳轉的視圖,放在ModelAndView中
mv.setViewName("hello"); //: /WEB-INF/jsp/hello.jsp
return mv;
}
}
9、將自己的類交給SpringIOC容器,註冊bean
<!--Handler--><bean id="/hello" class="com.kuang.controller.HelloController"/>
10、寫要跳轉的jsp頁面,顯示ModelandView存放的數據,以及我們的正常頁面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Kuangshen</title>
</head>
<body>
${msg}
</body>
</html>
11、配置Tomcat 啓動測試!
可能遇到的問題:訪問出現404,排查步驟:
- 查看控制檯輸出,看一下是不是缺少了什麼jar包。
- 如果jar包存在,顯示無法輸出,就在IDEA的項目發佈中,添加lib依賴!
- 重啓Tomcat 即可解決!
可能會遇到報500的問題:
查看當前的pom.xml下的spring-webmvc的版本是否太高了,這裏tomcat8版本與5.1.9版本不適配
適配版本:4.x.x與tomcat8版本適配
5.1.9與tomcat9版本適配
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.2.RELEASE</version>
</dependency>
小結:看這個估計大部分同學都能理解其中的原理了,但是我們實際開發纔不會這麼寫,不然就瘋了,還學這個玩意幹嘛!我們來看個註解版實現,這纔是SpringMVC的精髓,到底有多麼簡單,看這個圖就知道了。
3.2 註解版
1、新建一個Moudle,springmvc-03-hello-annotation 。添加web支持!
2、由於Maven可能存在資源過濾的問題,我們將配置完善
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
3、在pom.xml文件引入相關的依賴:主要有Spring框架核心庫、Spring MVC、servlet , JSTL等。我們在父依賴中已經引入了!
4、配置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">
<!--1.註冊servlet-->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--通過初始化參數指定SpringMVC配置文件的位置,進行關聯-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<!-- 啓動順序,數字越小,啓動越早 -->
<load-on-startup>1</load-on-startup>
</servlet>
<!--所有請求都會被springmvc攔截 -->
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
/ 和 /* 的區別:< url-pattern > / </ url-pattern > 不會匹配到.jsp, 只針對我們編寫的請求;即:.jsp 不會進入spring的 DispatcherServlet類 。< url-pattern > /* </ url-pattern > 會匹配 *.jsp,會出現返回 jsp視圖 時再次進入spring的DispatcherServlet 類,導致找不到對應的controller所以報404錯。
-
-
注意web.xml版本問題,要最新版!
-
註冊DispatcherServlet
-
關聯SpringMVC的配置文件
-
啓動級別爲1
-
映射路徑爲 / 【不要用/*,會404】
-
-
5、添加Spring MVC配置文件
-
在resource目錄下添加springmvc-servlet.xml配置文件,配置的形式與Spring容器配置基本類似,爲了支持基於註解的IOC,設置了自動掃描包的功能,具體配置信息如下:
-
<?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"> <!-- 自動掃描包,讓指定包下的註解生效,由IOC容器統一管理 --> <context:component-scan base-package="com.kuang.controller"/> <!-- 讓Spring MVC不處理靜態資源 --> <mvc:default-servlet-handler /> <!-- 支持mvc註解驅動 在spring中一般採用@RequestMapping註解來完成映射關係 要想使@RequestMapping註解生效 必須向上下文中註冊DefaultAnnotationHandlerMapping 和一個AnnotationMethodHandlerAdapter實例 這兩個實例分別在類級別和方法級別處理。 而annotation-driven配置幫助我們自動完成上述兩個實例的注入。 --> <mvc:annotation-driven /> <!-- 視圖解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <!-- 前綴 --> <property name="prefix" value="/WEB-INF/jsp/" /> <!-- 後綴 --> <property name="suffix" value=".jsp" /> </bean> </beans>
-
在視圖解析器中我們把所有的視圖都存放在/WEB-INF/目錄下,這樣可以保證視圖安全,因爲這個目錄下的文件,客戶端不能直接訪問。
-
-
讓IOC的註解生效
-
靜態資源過濾 :HTML . JS . CSS . 圖片 , 視頻 …
-
MVC的註解驅動
-
配置視圖解析器
-
-
6、創建Controller
-
編寫一個Java控制類:com.kuang.controller.HelloController , 注意編碼規範
-
package com.kuang.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/HelloController") public class HelloController { //真實訪問地址 : 項目名/HelloController/hello @RequestMapping("/hello") public String sayHello(Model model){ //向模型中添加屬性msg與值,可以在JSP頁面中取出並渲染 model.addAttribute("msg","hello,SpringMVC"); //web-inf/jsp/hello.jsp return "hello"; } }
-
- @Controller是爲了讓Spring IOC容器初始化時自動掃描到;
- @RequestMapping是爲了映射請求路徑,這裏因爲類與方法上都有映射所以訪問時應該是/HelloController/hello;
- 方法中聲明Model類型的參數是爲了把Action中的數據帶到視圖中;
- 方法返回的結果是視圖的名稱hello,加上配置文件中的前後綴變成WEB-INF/jsp/hello.jsp。
-
7、創建視圖層
-
在WEB-INF/ jsp目錄中創建hello.jsp , 視圖可以直接取出並展示從Controller帶回的信息;
-
可以通過EL表示取出Model中存放的值,或者對象;
-
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>SpringMVC</title> </head> <body> ${msg} </body> </html>
8、配置Tomcat運行
配置Tomcat , 開啓服務器 , 訪問 對應的請求路徑!
OK,運行成功!
3.3 小結
實現步驟其實非常的簡單:
- 新建一個web項目
- 導入相關jar包
- 編寫web.xml , 註冊DispatcherServlet
- 編寫springmvc配置文件
- 接下來就是去創建對應的控制類 , controller
- 最後完善前端視圖和controller之間的對應
- 測試運行調試.
使用springMVC必須配置的三大件:
處理器映射器、處理器適配器、視圖解析器
通常,我們只需要手動配置視圖解析器,而處理器映射器和處理器適配器只需要開啓註解驅動即可,而省去了大段的xml配置
再來回顧下原理吧~
下面我們準備研究下Controller及RestFul風格!
4.RestFul和控制器
控制器Controller
在上一節中,我們編寫了我們的第一個SpringMVC程序!
現在我們來看看裏面的控制器和路徑請求的具體內容吧!
4.1 控制器Controller
-
控制器複雜提供訪問應用程序的行爲,通常通過接口定義或註解定義兩種方法實現。
-
控制器負責解析用戶的請求並將其轉換爲一個模型。
-
在Spring MVC中一個控制器類可以包含多個方法
-
在Spring MVC中,對於Controller的配置方式有很多種
4.2 實現Controller接口
Controller是一個接口,在org.springframework.web.servlet.mvc包下,接口中只有一個方法;
//實現該接口的類獲得控制器功能
public interface Controller {
//處理請求且返回一個模型與視圖對象
ModelAndView handleRequest(HttpServletRequest var1, HttpServletResponse var2) throws Exception;
}
測試
-
新建一個Moudle,springmvc-04-controller 。將剛纔的03 拷貝一份, 我們進行操作!
-
- 刪掉HelloController
- mvc的配置文件只留下 視圖解析器!
-
編寫一個Controller類,ControllerTest1
//定義控制器 //注意點:不要導錯包,實現Controller接口,重寫方法; public class ControllerTest1 implements Controller { public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { //返回一個模型視圖對象 ModelAndView mv = new ModelAndView(); mv.addObject("msg","Test1Controller"); mv.setViewName("test"); return mv; } }
-
編寫完畢後,去Spring配置文件中註冊請求的bean;name對應請求路徑,class對應處理請求的類
<bean name="/t1" class="com.kuang.controller.ControllerTest1"/>
-
編寫前端test.jsp,注意在WEB-INF/jsp目錄下編寫,對應我們的視圖解析器
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Kuangshen</title> </head> <body> ${msg} </body> </html>
-
配置Tomcat運行測試,我這裏沒有項目發佈名配置的就是一個 / ,所以請求不用加項目名,OK!
說明:
-
實現接口Controller定義控制器是較老的辦法
-
缺點是:一個控制器中只有一個方法,如果要多個方法則需要定義多個Controller;定義的方式比較麻煩;
4.3 使用註解@Controller
-
@Controller註解類型用於聲明Spring類的實例是一個控制器(在講IOC時還提到了另外3個註解);
-
Spring可以使用掃描機制來找到應用程序中所有基於註解的控制器類,爲了保證Spring能找到你的控制器,需要在配置文件中聲明組件掃描。
<!-- 自動掃描指定的包,下面所有註解類交給IOC容器管理 --> <context:component-scan base-package="com.kuang.controller"/>
-
增加一個ControllerTest2類,使用註解實現;
//@Controller註解的類會自動添加到Spring上下文中 @Controller public class ControllerTest2{ //映射訪問路徑 @RequestMapping("/t2") public String index(Model model){ //Spring MVC會自動實例化一個Model對象用於向視圖中傳值 model.addAttribute("msg", "ControllerTest2"); //返回視圖位置 return "test"; } }
-
運行tomcat測試
可以發現,我們的兩個請求都可以指向一個視圖,但是頁面結果的結果是不一樣的,從這裏可以看出視圖是被複用的,而控制器與視圖之間是弱偶合關係。
註解方式是平時使用的最多的方式!
4.4 RequestMapping
@RequestMapping
-
@RequestMapping註解用於映射url到控制器類或一個特定的處理程序方法。可用於類或方法上。用於類上,表示類中的所有響應請求的方法都是以該地址作爲父路徑。
-
爲了測試結論更加準確,我們可以加上一個項目名測試 myweb
-
只註解在方法上面
@Controller public class TestController { @RequestMapping("/h1") public String test(){ return "test"; } }
訪問路徑:http://localhost:8080 / 項目名 / h1
-
同時註解類與方法
@Controller @RequestMapping("/admin") public class TestController { @RequestMapping("/h1") public String test(){ return "test"; } }
訪問路徑:http://localhost:8080 / 項目名/ admin /h1 , 需要先指定類的路徑再指定方法的路徑;
4.5 RestFul 風格
概念
Restful就是一個資源定位及資源操作的風格。不是標準也不是協議,只是一種風格。基於這個風格設計的軟件可以更簡潔,更有層次,更易於實現緩存等機制。
功能
資源:互聯網所有的事物都可以被抽象爲資源
資源操作:使用POST、DELETE、PUT、GET,使用不同方法對資源進行操作。
分別對應 添加、 刪除、修改、查詢。
傳統方式操作資源 :通過不同的參數來實現不同的效果!方法單一,post 和 get
http://127.0.0.1/item/queryItem.action?id=1 查詢,GET
http://127.0.0.1/item/saveItem.action 新增,POST
http://127.0.0.1/item/updateItem.action 更新,POST
http://127.0.0.1/item/deleteItem.action?id=1 刪除,GET或POST
使用RESTful操作資源 :可以通過不同的請求方式來實現不同的效果!如下:請求地址一樣,但是功能可以不同!
http://127.0.0.1/item/1 查詢,GET
http://127.0.0.1/item 新增,POST
http://127.0.0.1/item 更新,PUT
http://127.0.0.1/item/1 刪除,DELETE
學習測試
-
在新建一個類 RestFulController
@Controller public class RestFulController { }
-
在Spring MVC中可以使用 @PathVariable 註解,讓方法參數的值對應綁定到一個URI模板變量上。
@Controller public class RestFulController { //映射訪問路徑 @RequestMapping("/commit/{p1}/{p2}") public String index(@PathVariable int p1, @PathVariable int p2, Model model){ int result = p1+p2; //Spring MVC會自動實例化一個Model對象用於向視圖中傳值 model.addAttribute("msg", "結果:"+result); //返回視圖位置 return "test"; } }
-
我們來測試請求查看下
-
思考:使用路徑變量的好處?
-
-
使路徑變得更加簡潔;
-
獲得參數更加方便,框架會自動進行類型轉換。
-
通過路徑變量的類型可以約束訪問參數,如果類型不一樣,則訪問不到對應的請求方法,如這裏訪問是的路徑是/commit/1/a,則路徑與方法不匹配,而不會是參數轉換失敗。
-
-
我們來修改下對應的參數類型,再次測試
//映射訪問路徑 @RequestMapping("/commit/{p1}/{p2}") public String index(@PathVariable int p1, @PathVariable String p2, Model model){ String result = p1+p2; //Spring MVC會自動實例化一個Model對象用於向視圖中傳值 model.addAttribute("msg", "結果:"+result); //返回視圖位置 return "test"; }
使用method屬性指定請求類型
用於約束請求的類型,可以收窄請求範圍。指定請求謂詞的類型如GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE等
我們來測試一下:
-
增加一個方法
//映射訪問路徑,必須是POST請求 @RequestMapping(value = "/hello",method = {RequestMethod.POST}) public String index2(Model model){ model.addAttribute("msg", "hello!"); return "test"; }
-
我們使用瀏覽器地址欄進行訪問默認是Get請求,會報錯405:
-
如果將POST修改爲GET則正常了;
//映射訪問路徑,必須是Get請求 @RequestMapping(value = "/hello",method = {RequestMethod.GET}) public String index2(Model model){ model.addAttribute("msg", "hello!"); return "test"; }
小結:
Spring MVC 的 @RequestMapping 註解能夠處理 HTTP 請求的方法, 比如 GET, PUT, POST, DELETE 以及 PATCH。
所有的地址欄請求默認都會是 HTTP GET 類型的。
方法級別的註解變體有如下幾個:組合註解
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
@GetMapping 是一個組合註解,平時使用的會比較多!
它所扮演的是 @RequestMapping(method =RequestMethod.GET) 的一個快捷方式。
4.6 擴展:小黃鴨調試法
場景一:我們都有過向別人(甚至可能向完全不會編程的人)提問及解釋編程問題的經歷,但是很多時候就在我們解釋的過程中自己卻想到了問題的解決方案,然後對方卻一臉茫然。
場景二:你的同行跑來問你一個問題,但是當他自己把問題說完,或說到一半的時候就想出答案走了,留下一臉茫然的你。
其實上面兩種場景現象就是所謂的小黃鴨調試法(Rubber Duck Debuging),又稱橡皮鴨調試法,它是我們軟件工程中最常使用調試方法之一。
此概念據說來自《程序員修煉之道》書中的一個故事,傳說程序大師隨身攜帶一隻小黃鴨,在調試代碼的時候會在桌上放上這隻小黃鴨,然後詳細地向鴨子解釋每行代碼,然後很快就將問題定位修復了。
下面我們準備研究下參數接受和結果跳轉!
5.數據處理及跳轉
在上一節中,我們瞭解了控制器和Restful風格操作
現在我們來看看SpringMVC參數接收處理和結果跳轉處理吧!
5.1 結果跳轉方式
5.1.1 ModelAndView
設置ModelAndView對象 , 根據view的名稱 , 和視圖解析器跳到指定的頁面 .
頁面 : {視圖解析器前綴} + viewName +{視圖解析器後綴}
<!-- 視圖解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前綴 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 後綴 -->
<property name="suffix" value=".jsp" />
</bean>
對應的controller類
public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
//返回一個模型視圖對象
ModelAndView mv = new ModelAndView();
mv.addObject("msg","ControllerTest1");
mv.setViewName("test");
return mv;
}
}
5.1.2 ServletAPI
通過設置ServletAPI , 不需要視圖解析器 .
1、通過HttpServletResponse進行輸出
2、通過HttpServletResponse實現重定向
3、通過HttpServletResponse實現轉發
@Controller
public class ResultGo {
@RequestMapping("/result/t1")
public void test1(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
rsp.getWriter().println("Hello,Spring BY servlet API");
}
@RequestMapping("/result/t2")
public void test2(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
rsp.sendRedirect("/index.jsp");
}
@RequestMapping("/result/t3")
public void test3(HttpServletRequest req, HttpServletResponse rsp) throws Exception {
//轉發
req.setAttribute("msg","/result/t3");
req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,rsp);
}
}
5.1.3 SpringMVC
通過SpringMVC來實現轉發和重定向 - 無需視圖解析器;
測試前,需要將視圖解析器註釋掉
@Controller
public class ResultSpringMVC {
@RequestMapping("/rsm/t1")
public String test1(){
//轉發
return "/index.jsp";
}
@RequestMapping("/rsm/t2")
public String test2(){
//轉發二
return "forward:/index.jsp";
}
@RequestMapping("/rsm/t3")
public String test3(){
//重定向
return "redirect:/index.jsp";
}
}
通過SpringMVC來實現轉發和重定向 - 有視圖解析器;
重定向 , 不需要視圖解析器 , 本質就是重新請求一個新地方嘛 , 所以注意路徑問題.
可以重定向到另外一個請求實現 .
@Controller
public class ResultSpringMVC2 {
@RequestMapping("/rsm2/t1")
public String test1(){
//轉發
return "test";
}
@RequestMapping("/rsm2/t2")
public String test2(){
//重定向
return "redirect:/index.jsp";
//return "redirect:hello.do"; //hello.do爲另一個請求/
}
}
5.2 數據處理
5.2.1 處理提交數據
1、提交的域名稱和處理方法的參數名一致
提交數據 : http://localhost:8080/hello?name=kuangshen
處理方法 :
@RequestMapping("/hello")
public String hello(String name){
System.out.println(name);
return "hello";
}
後臺輸出 : kuangshen
2、提交的域名稱和處理方法的參數名不一致
提交數據 : http://localhost:8080/hello?username=kuangshen
處理方法 :
//@RequestParam("username") : username提交的域的名稱 .
@RequestMapping("/hello")
public String hello(@RequestParam("username") String name){
System.out.println(name);
return "hello";
}
後臺輸出 : kuangshen
3、提交的是一個對象
要求提交的表單域和對象的屬性名一致 , 參數使用對象即可
1、實體類
public class User {
private int id;
private String name;
private int age;
//構造
//get/set
//tostring()
}
2、提交數據 : http://localhost:8080/mvc04/user?name=kuangshen&id=1&age=15
3、處理方法 :
@RequestMapping("/user")
public String user(User user){
System.out.println(user);
return "hello";
}
後臺輸出 : User { id=1, name=‘kuangshen’, age=15 }
說明:如果使用對象的話,前端傳遞的參數名和對象名必須一致,否則就是null。
5.2.2 數據顯示到前端
第一種 : 通過ModelAndView
我們前面一直都是如此 . 就不過多解釋
public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
//返回一個模型視圖對象
ModelAndView mv = new ModelAndView();
mv.addObject("msg","ControllerTest1");
mv.setViewName("test");
return mv;
}
}
第二種 : 通過ModelMap
ModelMap
@RequestMapping("/hello")
public String hello(@RequestParam("username") String name, ModelMap model){
//封裝要顯示到視圖中的數據
//相當於req.setAttribute("name",name);
model.addAttribute("name",name);
System.out.println(name);
return "hello";
}
第三種 : 通過Model
Model
@RequestMapping("/ct2/hello")
public String hello(@RequestParam("username") String name, Model model){
//封裝要顯示到視圖中的數據
//相當於req.setAttribute("name",name);
model.addAttribute("msg",name);
System.out.println(name);
return "test";
}
5.2.3 對比
就對於新手而言簡單來說使用區別就是:
Model 只有寥寥幾個方法只適合用於儲存數據,簡化了新手對於Model對象的操作和理解;
ModelMap 繼承了 LinkedMap ,除了實現了自身的一些方法,同樣的繼承 LinkedMap 的方法和特性;
ModelAndView 可以在儲存數據的同時,可以進行設置返回的邏輯視圖,進行控制展示層的跳轉。
當然更多的以後開發考慮的更多的是性能和優化,就不能單單僅限於此的瞭解。
請使用80%的時間打好紮實的基礎,剩下18%的時間研究框架,2%的時間去學點英文,框架的官方文檔永遠是最好的教程。
5.2.4 亂碼問題
測試步驟:
1、我們可以在首頁編寫一個提交的表單
<form action="/e/t" method="post">
<input type="text" name="name">
<input type="submit">
</form>
2、後臺編寫對應的處理類
@Controller
public class Encoding {
@RequestMapping("/e/t")
public String test(Model model,String name){
model.addAttribute("msg",name); //獲取表單提交的值
return "test"; //跳轉到test頁面顯示輸入的值
}
}
3、輸入中文測試,發現亂碼
不得不說,亂碼問題是在我們開發中十分常見的問題,也是讓我們程序猿比較頭大的問題!
以前亂碼問題通過過濾器解決 , 而SpringMVC給我們提供了一個過濾器 , 可以在web.xml中配置 .
修改了xml文件需要重啓服務器!
<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>
但是我們發現 , 有些極端情況下.這個過濾器對get的支持不好 .
處理方法 :
1、修改tomcat配置文件 :設置編碼!
<Connector URIEncoding="utf-8" port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
2、自定義過濾器
package com.kuang.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
/**
* 解決get和post請求 全部亂碼的過濾器
*/
public class GenericEncodingFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//處理response的字符編碼
HttpServletResponse myResponse=(HttpServletResponse) response;
myResponse.setContentType("text/html;charset=UTF-8");
// 轉型爲與協議相關對象
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
// 對request包裝增強
HttpServletRequest myrequest = new MyRequest(httpServletRequest);
chain.doFilter(myrequest, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
//自定義request對象,HttpServletRequest的包裝類
class MyRequest extends HttpServletRequestWrapper {
private HttpServletRequest request;
//是否編碼的標記
private boolean hasEncode;
//定義一個可以傳入HttpServletRequest對象的構造函數,以便對其進行裝飾
public MyRequest(HttpServletRequest request) {
super(request);// super必須寫
this.request = request;
}
// 對需要增強方法 進行覆蓋
@Override
public Map getParameterMap() {
// 先獲得請求方式
String method = request.getMethod();
if (method.equalsIgnoreCase("post")) {
// post請求
try {
// 處理post亂碼
request.setCharacterEncoding("utf-8");
return request.getParameterMap();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else if (method.equalsIgnoreCase("get")) {
// get請求
Map<String, String[]> parameterMap = request.getParameterMap();
if (!hasEncode) { // 確保get手動編碼邏輯只運行一次
for (String parameterName : parameterMap.keySet()) {
String[] values = parameterMap.get(parameterName);
if (values != null) {
for (int i = 0; i < values.length; i++) {
try {
// 處理get亂碼
values[i] = new String(values[i]
.getBytes("ISO-8859-1"), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
}
hasEncode = true;
}
return parameterMap;
}
return super.getParameterMap();
}
//取一個值
@Override
public String getParameter(String name) {
Map<String, String[]> parameterMap = getParameterMap();
String[] values = parameterMap.get(name);
if (values == null) {
return null;
}
return values[0]; // 取回參數的第一個值
}
//取所有值
@Override
public String[] getParameterValues(String name) {
Map<String, String[]> parameterMap = getParameterMap();
String[] values = parameterMap.get(name);
return values;
}
}
這個也是我在網上找的一些大神寫的,一般情況下,SpringMVC默認的亂碼處理就已經能夠很好的解決了!
然後在web.xml中配置這個過濾器即可!
亂碼問題,需要平時多注意,在儘可能能設置編碼的地方,都設置爲統一編碼 UTF-8!
有了這些知識,我們馬上就可以進行SSM整合了!
6.Json交互處理
6.1 什麼是JSON?
- JSON(JavaScript Object Notation, JS 對象標記) 是一種輕量級的數據交換格式,目前使用特別廣泛。
- 採用完全獨立於編程語言的文本格式來存儲和表示數據。
- 簡潔和清晰的層次結構使得 JSON 成爲理想的數據交換語言。
- 易於人閱讀和編寫,同時也易於機器解析和生成,並有效地提升網絡傳輸效率。
在 JavaScript 語言中,一切都是對象。因此,任何JavaScript 支持的類型都可以通過 JSON 來表示,例如字符串、數字、對象、數組等。看看他的要求和語法格式:
- 對象表示爲鍵值對,數據由逗號分隔
- 花括號保存對象
- 方括號保存數組
JSON 鍵值對是用來保存 JavaScript 對象的一種方式,和 JavaScript 對象的寫法也大同小異,鍵/值對組合中的鍵名寫在前面並用雙引號 “” 包裹,使用冒號 : 分隔,然後緊接着值:
{"name": "QinJiang"}
{"age": "3"}
{"sex": "男"}
很多人搞不清楚 JSON 和 JavaScript 對象的關係,甚至連誰是誰都不清楚。其實,可以這麼理解:
JSON 是 JavaScript 對象的字符串表示法,它使用文本表示一個 JS 對象的信息,本質是一個字符串。
var obj = {a: 'Hello', b: 'World'}; //這是一個對象,注意鍵名也是可以使用引號包裹的
var json = '{"a": "Hello", "b": "World"}'; //這是一個 JSON 字符串,本質是一個字符串
6.2 JSON 和 JavaScript 對象互轉
要實現從JSON字符串轉換爲JavaScript 對象,使用 JSON.parse() 方法:
var obj = JSON.parse('{"a": "Hello", "b": "World"}');
//結果是 {a: 'Hello', b: 'World'}
要實現從JavaScript 對象轉換爲JSON字符串,使用 JSON.stringify() 方法:
var json = JSON.stringify({a: 'Hello', b: 'World'});
//結果是 '{"a": "Hello", "b": "World"}'
代碼測試
1、新建一個module ,springmvc-05-json , 添加web的支持
2、在web目錄下新建一個 json-1.html , 編寫測試內容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JSON_秦疆</title>
</head>
<body>
<script type="text/javascript">
//編寫一個js的對象
var user = {
name:"秦疆",
age:3,
sex:"男"
};
//將js對象轉換成json字符串
var str = JSON.stringify(user);
console.log(str);
//將json字符串轉換爲js對象
var user2 = JSON.parse(str);
console.log(user2.age,user2.name,user2.sex);
</script>
</body>
</html>
3、在IDEA中使用瀏覽器打開,查看控制檯輸出!
Controller返回JSON數據
Jackson應該是目前比較好的json解析工具了
當然工具不止這一個,比如還有阿里巴巴的 fastjson 等等。
我們這裏使用Jackson,使用它需要導入它的jar包;
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
配置SpringMVC需要的配置
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">
<!--1.註冊servlet-->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--通過初始化參數指定SpringMVC配置文件的位置,進行關聯-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<!-- 啓動順序,數字越小,啓動越早 -->
<load-on-startup>1</load-on-startup>
</servlet>
<!--所有請求都會被springmvc攔截 -->
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<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>
</web-app>
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"
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">
<!-- 自動掃描指定的包,下面所有註解類交給IOC容器管理 -->
<context:component-scan base-package="com.kuang.controller"/>
<!-- 視圖解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前綴 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 後綴 -->
<property name="suffix" value=".jsp" />
</bean>
</beans>
我們隨便編寫一個User的實體類,然後我們去編寫我們的測試Controller;
package com.kuang.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
//需要導入lombok
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private int age;
private String sex;
}
這裏我們需要兩個新東西,一個是@ResponseBody,一個是ObjectMapper對象,我們看下具體的用法
編寫一個Controller;
@Controller
public class UserController {
@RequestMapping("/json1")
@ResponseBody
public String json1() throws JsonProcessingException {
//創建一個jackson的對象映射器,用來解析數據
ObjectMapper mapper = new ObjectMapper();
//創建一個對象
User user = new User("秦疆1號", 3, "男");
//將我們的對象解析成爲json格式
String str = mapper.writeValueAsString(user);
//由於@ResponseBody註解,這裏會將str轉成json格式返回;十分方便
return str;
}
}
配置Tomcat , 啓動測試一下!
http://localhost:8080/json1
發現出現了亂碼問題,我們需要設置一下他的編碼格式爲utf-8,以及它返回的類型;
通過@RequestMaping的produces屬性來實現,修改下代碼
//produces:指定響應體返回類型和編碼
@RequestMapping(value = "/json1",produces = "application/json;charset=utf-8")
再次測試, http://localhost:8080/json1 , 亂碼問題OK!
【注意:使用json記得處理亂碼問題】
代碼優化
6.3 亂碼統一解決
上一種方法比較麻煩,如果項目中有許多請求則每一個都要添加,可以通過Spring配置統一指定,這樣就不用每次都去處理了!
我們可以在springmvc的配置文件上添加一段消息StringHttpMessageConverter轉換配置!
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<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>
6.4 返回json字符串統一解決
在類上直接使用 @RestController ,這樣子,裏面所有的方法都只會返回 json 字符串了,不用再每一個都添加@ResponseBody !我們在前後端分離開發中,一般都使用 @RestController ,十分便捷!
@RestController
public class UserController {
//produces:指定響應體返回類型和編碼
@RequestMapping(value = "/json1")
public String json1() throws JsonProcessingException {
//創建一個jackson的對象映射器,用來解析數據
ObjectMapper mapper = new ObjectMapper();
//創建一個對象
User user = new User("秦疆1號", 3, "男");
//將我們的對象解析成爲json格式
String str = mapper.writeValueAsString(user);
//由於@ResponseBody註解,這裏會將str轉成json格式返回;十分方便
return str;
}
}
啓動tomcat測試,結果都正常輸出!
測試集合輸出
增加一個新的方法
@RequestMapping("/json2")
public String json2() throws JsonProcessingException {
//創建一個jackson的對象映射器,用來解析數據
ObjectMapper mapper = new ObjectMapper();
//創建一個對象
User user1 = new User("秦疆1號", 3, "男");
User user2 = new User("秦疆2號", 3, "男");
User user3 = new User("秦疆3號", 3, "男");
User user4 = new User("秦疆4號", 3, "男");
List<User> list = new ArrayList<User>();
list.add(user1);
list.add(user2);
list.add(user3);
list.add(user4);
//將我們的對象解析成爲json格式
String str = mapper.writeValueAsString(list);
return str;
}
運行結果 : 十分完美,沒有任何問題!
輸出時間對象
增加一個新的方法
@RequestMapping("/json3")
public String json3() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
//創建時間一個對象,java.util.Date
Date date = new Date();
//將我們的對象解析成爲json格式
String str = mapper.writeValueAsString(date);
return str;
}
運行結果 :
- 默認日期格式會變成一個數字,是1970年1月1日到當前日期的毫秒數!
- Jackson 默認是會把時間轉成timestamps形式
解決方案:取消timestamps形式 , 自定義時間格式
@RequestMapping("/json4")
public String json4() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
//不使用時間戳的方式
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
//自定義日期格式對象
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//指定日期格式
mapper.setDateFormat(sdf);
Date date = new Date();
String str = mapper.writeValueAsString(date);
return str;
}
運行結果 : 成功的輸出了時間!
抽取爲工具類
如果要經常使用的話,這樣是比較麻煩的,我們可以將這些代碼封裝到一個工具類中;我們去編寫下
package com.kuang.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.text.SimpleDateFormat;
public class JsonUtils {
public static String getJson(Object object) {
return getJson(object,"yyyy-MM-dd HH:mm:ss");
}
public static String getJson(Object object,String dateFormat) {
ObjectMapper mapper = new ObjectMapper();
//不使用時間差的方式
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
//自定義日期格式對象
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
//指定日期格式
mapper.setDateFormat(sdf);
try {
return mapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}
我們使用工具類,代碼就更加簡潔了!
@RequestMapping("/json5")
public String json5() throws JsonProcessingException {
Date date = new Date();
String json = JsonUtils.getJson(date);
return json;
}
大功告成!完美!
6.5 FastJson
fastjson.jar是阿里開發的一款專門用於Java開發的包,可以方便的實現json對象與JavaBean對象的轉換,實現JavaBean對象與json字符串的轉換,實現json對象與json字符串的轉換。實現json的轉換方法很多,最後的實現結果都是一樣的。
fastjson 的 pom依賴!
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.60</version>
</dependency>
fastjson 三個主要的類:
JSONObject 代表 json 對象
- JSONObject實現了Map接口, 猜想 JSONObject底層操作是由Map實現的。
- JSONObject對應json對象,通過各種形式的get()方法可以獲取json對象中的數據,也可利用諸如size(),isEmpty()等方法獲取"鍵:值"對的個數和判斷是否爲空。其本質是通過實現Map接口並調用接口中的方法完成的。
JSONArray 代表 json 對象數組
- 內部是有List接口中的方法來完成操作的。
JSON代表 JSONObject和JSONArray的轉化
- JSON類源碼分析與使用
- 仔細觀察這些方法,主要是實現json對象,json對象數組,javabean對象,json字符串之間的相互轉化。
代碼測試,我們新建一個FastJsonDemo 類
package com.kuang.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kuang.pojo.User;
import java.util.ArrayList;
import java.util.List;
public class FastJsonDemo {
public static void main(String[] args) {
//創建一個對象
User user1 = new User("秦疆1號", 3, "男");
User user2 = new User("秦疆2號", 3, "男");
User user3 = new User("秦疆3號", 3, "男");
User user4 = new User("秦疆4號", 3, "男");
List<User> list = new ArrayList<User>();
list.add(user1);
list.add(user2);
list.add(user3);
list.add(user4);
System.out.println("*******Java對象 轉 JSON字符串*******");
String str1 = JSON.toJSONString(list);
System.out.println("JSON.toJSONString(list)==>"+str1);
String str2 = JSON.toJSONString(user1);
System.out.println("JSON.toJSONString(user1)==>"+str2);
System.out.println("\n****** JSON字符串 轉 Java對象*******");
User jp_user1=JSON.parseObject(str2,User.class);
System.out.println("JSON.parseObject(str2,User.class)==>"+jp_user1);
System.out.println("\n****** Java對象 轉 JSON對象 ******");
JSONObject jsonObject1 = (JSONObject) JSON.toJSON(user2);
System.out.println("(JSONObject) JSON.toJSON(user2)==>"+jsonObject1.getString("name"));
System.out.println("\n****** JSON對象 轉 Java對象 ******");
User to_java_user = JSON.toJavaObject(jsonObject1, User.class);
System.out.println("JSON.toJavaObject(jsonObject1, User.class)==>"+to_java_user);
}
}
這種工具類,我們只需要掌握使用就好了,在使用的時候在根據具體的業務去找對應的實現。和以前的commons-io那種工具包一樣,拿來用就好了!
Json在我們數據傳輸中十分重要,一定要學會使用!
7.整合SSM框架
整合SSM框架
在上一節中,我們瞭解了SpringMVC參數接收處理和結果跳轉處理!
現在我們來看看,如何集成SSM框架!完整項目的整合!
7.1 整合SSM
環境要求
環境:
- IDEA
- MySQL 5.7.19
- Tomcat 9
- Maven 3.6
要求:
- 需要熟練掌握MySQL數據庫,Spring,JavaWeb及MyBatis知識,簡單的前端知識;
數據庫環境
創建一個存放書籍數據的數據庫表
CREATE DATABASE `ssmbuild`;
USE `ssmbuild`;
DROP TABLE IF EXISTS `books`;
CREATE TABLE `books` (
`bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT '書id',
`bookName` VARCHAR(100) NOT NULL COMMENT '書名',
`bookCounts` INT(11) NOT NULL COMMENT '數量',
`detail` VARCHAR(200) NOT NULL COMMENT '描述',
KEY `bookID` (`bookID`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES
(1,'Java',1,'從入門到放棄'),
(2,'MySQL',10,'從刪庫到跑路'),
(3,'Linux',5,'從進門到進牢');
基本環境搭建
1、新建一Maven項目!ssmbuild , 添加web的支持
2、導入相關的pom依賴!
<dependencies>
<!--Junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--數據庫驅動-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- 數據庫連接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!--Servlet - JSP -->
<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>
<!--Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<!--Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
</dependencies>
3、Maven資源過濾設置
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
4、建立基本結構和配置框架!
-
com.kuang.pojo
-
com.kuang.dao
-
com.kuang.service
-
com.kuang.controller
-
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> </configuration>
-
applicationContext.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 http://www.springframework.org/schema/beans/spring-beans.xsd"> </beans>
7.1.1 Mybatis層編寫
1、數據庫配置文件 database.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456
2、IDEA關聯數據庫
3、編寫MyBatis的核心配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.kuang.pojo"/>
</typeAliases>
<mappers>
<mapper resource="com/kuang/dao/BookMapper.xml"/>
</mappers>
</configuration>
4、編寫數據庫對應的實體類 com.kuang.pojo.Books
使用lombok插件!
package com.kuang.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
}
5、編寫Dao層的 Mapper接口!
package com.kuang.dao;
import com.kuang.pojo.Books;
import java.util.List;
public interface BookMapper {
//增加一個Book
int addBook(Books book);
//根據id刪除一個Book
int deleteBookById(int id);
//更新Book
int updateBook(Books books);
//根據id查詢,返回一個Book
Books queryBookById(int id);
//查詢全部Book,返回list集合
List<Books> queryAllBook();
}
6、編寫接口對應的 Mapper.xml 文件。需要導入MyBatis的包;
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kuang.dao.BookMapper">
<!--增加一個Book-->
<insert id="addBook" parameterType="Books">
insert into ssmbuild.books(bookName,bookCounts,detail)
values (#{bookName}, #{bookCounts}, #{detail})
</insert>
<!--根據id刪除一個Book-->
<delete id="deleteBookById" parameterType="int">
delete from ssmbuild.books where bookID=#{bookID}
</delete>
<!--更新Book-->
<update id="updateBook" parameterType="Books">
update ssmbuild.books
set bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail}
where bookID = #{bookID}
</update>
<!--根據id查詢,返回一個Book-->
<select id="queryBookById" resultType="Books">
select * from ssmbuild.books
where bookID = #{bookID}
</select>
<!--查詢全部Book-->
<select id="queryAllBook" resultType="Books">
SELECT * from ssmbuild.books
</select>
</mapper>
7、編寫Service層的接口和實現類
接口:
package com.kuang.service;
import com.kuang.pojo.Books;
import java.util.List;
//BookService:底下需要去實現,調用dao層
public interface BookService {
//增加一個Book
int addBook(Books book);
//根據id刪除一個Book
int deleteBookById(int id);
//更新Book
int updateBook(Books books);
//根據id查詢,返回一個Book
Books queryBookById(int id);
//查詢全部Book,返回list集合
List<Books> queryAllBook();
}
實現類:
package com.kuang.service;
import com.kuang.dao.BookMapper;
import com.kuang.pojo.Books;
import java.util.List;
public class BookServiceImpl implements BookService {
//調用dao層的操作,設置一個set接口,方便Spring管理
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
public int addBook(Books book) {
return bookMapper.addBook(book);
}
public int deleteBookById(int id) {
return bookMapper.deleteBookById(id);
}
public int updateBook(Books books) {
return bookMapper.updateBook(books);
}
public Books queryBookById(int id) {
return bookMapper.queryBookById(id);
}
public List<Books> queryAllBook() {
return bookMapper.queryAllBook();
}
}
OK,到此,底層需求操作編寫完畢!
7.1.2 Spring層
1、配置Spring整合MyBatis,我們這裏數據源使用c3p0連接池;
2、我們去編寫Spring整合Mybatis的相關的配置文件;spring-dao.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"
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">
<!-- 配置整合mybatis -->
<!-- 1.關聯數據庫文件 -->
<context:property-placeholder location="classpath:database.properties"/>
<!-- 2.數據庫連接池 -->
<!--數據庫連接池
dbcp 半自動化操作 不能自動連接
c3p0 自動化操作(自動的加載配置文件 並且設置到對象裏面)
-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 配置連接池屬性 -->
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!-- c3p0連接池的私有屬性 -->
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<!-- 關閉連接後不自動commit -->
<property name="autoCommitOnClose" value="false"/>
<!-- 獲取連接超時時間 -->
<property name="checkoutTimeout" value="10000"/>
<!-- 當獲取連接失敗重試次數 -->
<property name="acquireRetryAttempts" value="2"/>
</bean>
<!-- 3.配置SqlSessionFactory對象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入數據庫連接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!-- 4.配置掃描Dao接口包,動態實現Dao接口注入到spring容器中 -->
<!--解釋 :https://www.cnblogs.com/jpfss/p/7799806.html-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 給出需要掃描Dao接口包 -->
<property name="basePackage" value="com.kuang.dao"/>
</bean>
</beans>
3、Spring整合service層
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 掃描service相關的bean -->
<context:component-scan base-package="com.kuang.service" />
<!--BookServiceImpl注入到IOC容器中-->
<bean id="BookServiceImpl" class="com.kuang.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!-- 配置事務管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入數據庫連接池 -->
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
Spring層搞定!再次理解一下,Spring就是一個大雜燴,一個容器!對吧!
7.1.3 SpringMVC層
1、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">
<!--DispatcherServlet-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!--一定要注意:我們這裏加載的是總的配置文件,之前被這裏坑了!-->
<param-value>classpath:applicationContext.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>
<!--encodingFilter-->
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--Session過期時間-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
2、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
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 配置SpringMVC -->
<!-- 1.開啓SpringMVC註解驅動 -->
<mvc:annotation-driven />
<!-- 2.靜態資源默認servlet配置-->
<mvc:default-servlet-handler/>
<!-- 3.配置jsp 顯示ViewResolver視圖解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 4.掃描web相關的bean -->
<context:component-scan base-package="com.kuang.controller" />
</beans>
3、Spring配置整合文件,applicationContext.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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="spring-dao.xml"/>
<import resource="spring-service.xml"/>
<import resource="spring-mvc.xml"/>
</beans>
配置文件,暫時結束!Controller 和 視圖層編寫
1、BookController 類編寫 , 方法一:查詢全部書籍
@Controller
@RequestMapping("/book")
public class BookController {
@Autowired
@Qualifier("BookServiceImpl")
private BookService bookService;
@RequestMapping("/allBook")
public String list(Model model) {
List<Books> list = bookService.queryAllBook();
model.addAttribute("list", list);
return "allBook";
}
}
2、編寫首頁 index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE HTML>
<html>
<head>
<title>首頁</title>
<style type="text/css">
a {
text-decoration: none;
color: black;
font-size: 18px;
}
h3 {
width: 180px;
height: 38px;
margin: 100px auto;
text-align: center;
line-height: 38px;
background: deepskyblue;
border-radius: 4px;
}
</style>
</head>
<body>
<h3>
<a href="${pageContext.request.contextPath}/book/allBook">點擊進入列表頁</a>
</h3>
</body>
</html>
3、書籍列表頁面 allbook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>書籍列表</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>書籍列表 —— 顯示所有書籍</small>
</h1>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4 column">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">新增</a>
</div>
</div>
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-hover table-striped">
<thead>
<tr>
<th>書籍編號</th>
<th>書籍名字</th>
<th>書籍數量</th>
<th>書籍詳情</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<c:forEach var="book" items="${requestScope.get('list')}">
<tr>
<td>${book.getBookID()}</td>
<td>${book.getBookName()}</td>
<td>${book.getBookCounts()}</td>
<td>${book.getDetail()}</td>
<td>
<a href="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.getBookID()}">更改</a> |
<a href="${pageContext.request.contextPath}/book/del/${book.getBookID()}">刪除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
4、BookController 類編寫 , 方法二:添加書籍
@RequestMapping("/toAddBook")
public String toAddPaper() {
return "addBook";
}
@RequestMapping("/addBook")
public String addPaper(Books books) {
System.out.println(books);
bookService.addBook(books);
return "redirect:/book/allBook";
}
5、添加書籍頁面:addBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>新增書籍</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>新增書籍</small>
</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/addBook" method="post">
書籍名稱:<input type="text" name="bookName"><br><br><br>
書籍數量:<input type="text" name="bookCounts"><br><br><br>
書籍詳情:<input type="text" name="detail"><br><br><br>
<input type="submit" value="添加">
</form>
</div>
6、BookController 類編寫 , 方法三:修改書籍
@RequestMapping("/toUpdateBook")
public String toUpdateBook(Model model, int id) {
Books books = bookService.queryBookById(id);
System.out.println(books);
model.addAttribute("book",books );
return "updateBook";
}
@RequestMapping("/updateBook")
public String updateBook(Model model, Books book) {
System.out.println(book);
bookService.updateBook(book);
Books books = bookService.queryBookById(book.getBookID());
model.addAttribute("books", books);
return "redirect:/book/allBook";
}
7、修改書籍頁面 updateBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>修改信息</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>修改信息</small>
</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/updateBook" method="post">
<input type="hidden" name="bookID" value="${book.getBookID()}"/>
書籍名稱:<input type="text" name="bookName" value="${book.getBookName()}"/>
書籍數量:<input type="text" name="bookCounts" value="${book.getBookCounts()}"/>
書籍詳情:<input type="text" name="detail" value="${book.getDetail() }"/>
<input type="submit" value="提交"/>
</form>
</div>
8、BookController 類編寫 , 方法四:刪除書籍
@RequestMapping("/del/{bookId}")
public String deleteBook(@PathVariable("bookId") int id) {
bookService.deleteBookById(id);
return "redirect:/book/allBook";
}
配置Tomcat,進行運行!
到目前爲止,這個SSM項目整合已經完全的OK了,可以直接運行進行測試!這個練習十分的重要,大家需要保證,不看任何東西,自己也可以完整的實現出來!
項目結構圖
小結及展望
這個是同學們的第一個SSM整合案例,一定要爛熟於心!
SSM框架的重要程度是不言而喻的,學到這裏,大家已經可以進行基本網站的單獨開發。但是這只是增刪改查的基本操作。可以說學到這裏,大家纔算是真正的步入了後臺開發的門。也就是能找一個後臺相關工作的底線。
或許很多人,工作就做這些事情,但是對於個人的提高來說,還遠遠不夠!
我們後面還要學習一些 SpringMVC 的知識!
- Ajax 和 Json
- 文件上傳和下載
- 攔截器
8.Ajax研究
Ajax研究
簡介
-
AJAX = Asynchronous JavaScript and XML(異步的 JavaScript 和 XML)。
-
AJAX 是一種在無需重新加載整個網頁的情況下,能夠更新部分網頁的技術。
-
Ajax 不是一種新的編程語言,而是一種用於創建更好更快以及交互性更強的Web應用程序的技術。
-
在 2005 年,Google 通過其 Google Suggest 使 AJAX 變得流行起來。Google Suggest能夠自動幫你完成搜索單詞。
-
Google Suggest 使用 AJAX 創造出動態性極強的 web 界面:當您在谷歌的搜索框輸入關鍵字時,JavaScript 會把這些字符發送到服務器,然後服務器會返回一個搜索建議的列表。
-
就和國內百度的搜索框一樣!
-
傳統的網頁(即不用ajax技術的網頁),想要更新內容或者提交一個表單,都需要重新加載整個網頁。
-
使用ajax技術的網頁,通過在後臺服務器進行少量的數據交換,就可以實現異步局部更新。
-
使用Ajax,用戶可以創建接近本地桌面應用的直接、高可用、更豐富、更動態的Web用戶界面。
僞造Ajax
我們可以使用前端的一個標籤來僞造一個ajax的樣子。iframe標籤
1、新建一個module :sspringmvc-06-ajax , 導入web支持!
2、編寫一個 ajax-frame.html 使用 iframe 測試,感受下效果
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>kuangshen</title>
</head>
<body>
<script type="text/javascript">
window.onload = function(){
var myDate = new Date();
document.getElementById('currentTime').innerText = myDate.getTime();
};
function LoadPage(){
var targetUrl = document.getElementById('url').value;
console.log(targetUrl);
document.getElementById("iframePosition").src = targetUrl;
}
</script>
<div>
<p>請輸入要加載的地址:<span id="currentTime"></span></p>
<p>
<input id="url" type="text" value="https://www.baidu.com/"/>
<input type="button" value="提交" onclick="LoadPage()">
</p>
</div>
<div>
<h3>加載頁面位置:</h3>
<iframe id="iframePosition" style="width: 100%;height: 500px;"></iframe>
</div>
</body>
</html>
3、使用IDEA開瀏覽器測試一下!
利用AJAX可以做:
- 註冊時,輸入用戶名自動檢測用戶是否已經存在。
- 登陸時,提示用戶名密碼錯誤
- 刪除數據行時,將行ID發送到後臺,後臺在數據庫中刪除,數據庫刪除成功後,在頁面DOM中將數據行也刪除。
- …等等
jQuery.ajax
純JS原生實現Ajax我們不去講解這裏,直接使用jquery提供的,方便學習和使用,避免重複造輪子,有興趣的同學可以去了解下JS原生XMLHttpRequest !
Ajax的核心是XMLHttpRequest對象(XHR)。XHR爲向服務器發送請求和解析服務器響應提供了接口。能夠以異步方式從服務器獲取新數據。
jQuery 提供多個與 AJAX 有關的方法。
通過 jQuery AJAX 方法,您能夠使用 HTTP Get 和 HTTP Post 從遠程服務器上請求文本、HTML、XML 或 JSON – 同時您能夠把這些外部數據直接載入網頁的被選元素中。
jQuery 不是生產者,而是大自然搬運工。
jQuery Ajax本質就是 XMLHttpRequest,對他進行了封裝,方便調用!
jQuery.ajax(...)
部分參數:
url:請求地址
type:請求方式,GET、POST(1.9.0之後用method)
headers:請求頭
data:要發送的數據
contentType:即將發送信息至服務器的內容編碼類型(默認: "application/x-www-form-urlencoded; charset=UTF-8")
async:是否異步
timeout:設置請求超時時間(毫秒)
beforeSend:發送請求前執行的函數(全局)
complete:完成之後執行的回調函數(全局)
success:成功之後執行的回調函數(全局)
error:失敗之後執行的回調函數(全局)
accepts:通過請求頭髮送給服務器,告訴服務器當前客戶端可接受的數據類型
dataType:將服務器端返回的數據轉換成指定類型
"xml": 將服務器端返回的內容轉換成xml格式
"text": 將服務器端返回的內容轉換成普通文本格式
"html": 將服務器端返回的內容轉換成普通文本格式,在插入DOM中時,如果包含JavaScript標籤,則會嘗試去執行。
"script": 嘗試將返回值當作JavaScript去執行,然後再將服務器端返回的內容轉換成普通文本格式
"json": 將服務器端返回的內容轉換成相應的JavaScript對象
"jsonp": JSONP 格式使用 JSONP 形式調用函數時,如 "myurl?callback=?" jQuery 將自動替換 ? 爲正確的函數名,以執行回調函數
我們來個簡單的測試,使用最原始的HttpServletResponse處理 , .最簡單 , 最通用
1、配置web.xml 和 springmvc的配置文件,複製上面案例的即可 【記得靜態資源過濾和註解驅動配置上】
<?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">
<!-- 自動掃描指定的包,下面所有註解類交給IOC容器管理 -->
<context:component-scan base-package="com.kuang.controller"/>
<mvc:default-servlet-handler />
<mvc:annotation-driven />
<!-- 視圖解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前綴 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 後綴 -->
<property name="suffix" value=".jsp" />
</bean>
</beans>
2、編寫一個AjaxController
@Controller
public class AjaxController {
@RequestMapping("/a1")
public void ajax1(String name , HttpServletResponse response) throws IOException {
if ("admin".equals(name)){
response.getWriter().print("true");
}else{
response.getWriter().print("false");
}
}
}
3、導入jquery , 可以使用在線的CDN , 也可以下載導入
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.1.1.min.js"></script>
4、編寫index.jsp測試
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
<%--<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>--%>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.1.1.min.js"></script>
<script>
function a1(){
$.post({
url:"${pageContext.request.contextPath}/a1",
data:{'name':$("#txtName").val()},
success:function (data,status) {
alert(data);
alert(status);
}
});
}
</script>
</head>
<body>
<%--onblur:失去焦點觸發事件--%>
用戶名:<input type="text" id="txtName" onblur="a1()"/>
</body>
</html>
5、啓動tomcat測試!打開瀏覽器的控制檯,當我們鼠標離開輸入框的時候,可以看到發出了一個ajax的請求!是後臺返回給我們的結果!測試成功!
Springmvc實現
實體類user
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private int age;
private String sex;
}
我們來獲取一個集合對象,展示到前端頁面
@RequestMapping("/a2")
public List<User> ajax2(){
List<User> list = new ArrayList<User>();
list.add(new User("秦疆1號",3,"男"));
list.add(new User("秦疆2號",3,"男"));
list.add(new User("秦疆3號",3,"男"));
return list; //由於@RestController註解,將list轉成json格式返回
}
前端頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<input type="button" id="btn" value="獲取數據"/>
<table width="80%" align="center">
<tr>
<td>姓名</td>
<td>年齡</td>
<td>性別</td>
</tr>
<tbody id="content">
</tbody>
</table>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.1.1.min.js"></script>
<script>
$(function () {
$("#btn").click(function () {
$.post("${pageContext.request.contextPath}/a2",function (data) {
console.log(data)
var html="";
for (var i = 0; i <data.length ; i++) {
html+= "<tr>" +
"<td>" + data[i].name + "</td>" +
"<td>" + data[i].age + "</td>" +
"<td>" + data[i].sex + "</td>" +
"</tr>"
}
$("#content").html(html);
});
})
})
</script>
</body>
</html>
成功實現了數據回顯!可以體會一下Ajax的好處!
註冊提示效果
我們再測試一個小Demo,思考一下我們平時註冊時候,輸入框後面的實時提示怎麼做到的;如何優化
我們寫一個Controller
@RequestMapping("/a3")
public String ajax3(String name,String pwd){
String msg = "";
//模擬數據庫中存在數據
if (name!=null){
if ("admin".equals(name)){
msg = "OK";
}else {
msg = "用戶名輸入錯誤";
}
}
if (pwd!=null){
if ("123456".equals(pwd)){
msg = "OK";
}else {
msg = "密碼輸入有誤";
}
}
return msg; //由於@RestController註解,將msg轉成json格式返回
}
前端頁面 login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>ajax</title>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.1.1.min.js"></script>
<script>
function a1(){
$.post({
url:"${pageContext.request.contextPath}/a3",
data:{'name':$("#name").val()},
success:function (data) {
if (data.toString()=='OK'){
$("#userInfo").css("color","green");
}else {
$("#userInfo").css("color","red");
}
$("#userInfo").html(data);
}
});
}
function a2(){
$.post({
url:"${pageContext.request.contextPath}/a3",
data:{'pwd':$("#pwd").val()},
success:function (data) {
if (data.toString()=='OK'){
$("#pwdInfo").css("color","green");
}else {
$("#pwdInfo").css("color","red");
}
$("#pwdInfo").html(data);
}
});
}
</script>
</head>
<body>
<p>
用戶名:<input type="text" id="name" onblur="a1()"/>
<span id="userInfo"></span>
</p>
<p>
密碼:<input type="text" id="pwd" onblur="a2()"/>
<span id="pwdInfo"></span>
</p>
</body>
</html>
【記得處理json亂碼問題】
測試一下效果,動態請求響應,局部刷新,就是如此!
獲取baidu接口Demo
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>JSONP百度搜索</title>
<style>
#q{
width: 500px;
height: 30px;
border:1px solid #ddd;
line-height: 30px;
display: block;
margin: 0 auto;
padding: 0 10px;
font-size: 14px;
}
#ul{
width: 520px;
list-style: none;
margin: 0 auto;
padding: 0;
border:1px solid #ddd;
margin-top: -1px;
display: none;
}
#ul li{
line-height: 30px;
padding: 0 10px;
}
#ul li:hover{
background-color: #f60;
color: #fff;
}
</style>
<script>
// 2.步驟二
// 定義demo函數 (分析接口、數據)
function demo(data){
var Ul = document.getElementById('ul');
var html = '';
// 如果搜索數據存在 把內容添加進去
if (data.s.length) {
// 隱藏掉的ul顯示出來
Ul.style.display = 'block';
// 搜索到的數據循環追加到li裏
for(var i = 0;i<data.s.length;i++){
html += '<li>'+data.s[i]+'</li>';
}
// 循環的li寫入ul
Ul.innerHTML = html;
}
}
// 1.步驟一
window.onload = function(){
// 獲取輸入框和ul
var Q = document.getElementById('q');
var Ul = document.getElementById('ul');
// 事件鼠標擡起時候
Q.onkeyup = function(){
// 如果輸入框不等於空
if (this.value != '') {
// ☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆JSONPz重點☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆
// 創建標籤
var script = document.createElement('script');
//給定要跨域的地址 賦值給src
//這裏是要請求的跨域的地址 我寫的是百度搜索的跨域地址
script.src = 'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd='+this.value+'&cb=demo';
// 將組合好的帶src的script標籤追加到body裏
document.body.appendChild(script);
}
}
}
</script>
</head>
<body>
<input type="text" id="q" />
<ul id="ul">
</ul>
</body>
</html>
Ajax在我們開發中十分重要,一定要學會使用!
9.攔截器+文件上傳下載
這是SpringMVC視頻同步的最後一章:攔截器以及文件的上傳和下載實現!
攔截器
概述
SpringMVC的處理器攔截器類似於Servlet開發中的過濾器Filter,用於對處理器進行預處理和後處理。開發者可以自己定義一些攔截器來實現特定的功能。
**過濾器與攔截器的區別:**攔截器是AOP思想的具體應用。
過濾器
- servlet規範中的一部分,任何java web工程都可以使用
- 在url-pattern中配置了/*之後,可以對所有要訪問的資源進行攔截
攔截器
- 攔截器是SpringMVC框架自己的,只有使用了SpringMVC框架的工程才能使用
- 攔截器只會攔截訪問的控制器方法, 如果訪問的是jsp/html/css/image/js是不會進行攔截的
自定義攔截器
那如何實現攔截器呢?
想要自定義攔截器,必須實現 HandlerInterceptor 接口。
1、新建一個Moudule , springmvc-07-Interceptor , 添加web支持
2、配置web.xml 和 springmvc-servlet.xml 文件
3、編寫一個攔截器
package com.kuang.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyInterceptor implements HandlerInterceptor {
//在請求處理的方法之前執行
//如果返回true執行下一個攔截器
//如果返回false就不執行下一個攔截器
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
System.out.println("------------處理前------------");
return true;
}
//在請求處理方法執行之後執行
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
System.out.println("------------處理後------------");
}
//在dispatcherServlet處理後執行,做清理工作.
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
System.out.println("------------清理------------");
}
}
4、在springmvc的配置文件中配置攔截器
<!--關於攔截器的配置-->
<mvc:interceptors>
<mvc:interceptor>
<!--/** 包括路徑及其子路徑-->
<!--/admin/* 攔截的是/admin/add等等這種 , /admin/add/user不會被攔截-->
<!--/admin/** 攔截的是/admin/下的所有-->
<mvc:mapping path="/**"/>
<!--bean配置的就是攔截器-->
<bean class="com.kuang.interceptor.MyInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
5、編寫一個Controller,接收請求
package com.kuang.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
//測試攔截器的控制器
@Controller
public class InterceptorController {
@RequestMapping("/interceptor")
@ResponseBody
public String testFunction() {
System.out.println("控制器中的方法執行了");
return "hello";
}
}
6、前端 index.jsp
<a href="${pageContext.request.contextPath}/interceptor">攔截器測試</a>
7、啓動tomcat 測試一下!
驗證用戶是否登錄 (認證用戶)
實現思路
1、有一個登陸頁面,需要寫一個controller訪問頁面。
2、登陸頁面有一提交表單的動作。需要在controller中處理。判斷用戶名密碼是否正確。如果正確,向session中寫入用戶信息。返回登陸成功。
3、攔截用戶請求,判斷用戶是否登陸。如果用戶已經登陸。放行, 如果用戶未登陸,跳轉到登陸頁面
測試:
1、編寫一個登陸頁面 login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<h1>登錄頁面</h1>
<hr>
<body>
<form action="${pageContext.request.contextPath}/user/login">
用戶名:<input type="text" name="username"> <br>
密碼:<input type="password" name="pwd"> <br>
<input type="submit" value="提交">
</form>
</body>
</html>
2、編寫一個Controller處理請求
package com.kuang.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("/user")
public class UserController {
//跳轉到登陸頁面
@RequestMapping("/jumplogin")
public String jumpLogin() throws Exception {
return "login";
}
//跳轉到成功頁面
@RequestMapping("/jumpSuccess")
public String jumpSuccess() throws Exception {
return "success";
}
//登陸提交
@RequestMapping("/login")
public String login(HttpSession session, String username, String pwd) throws Exception {
// 向session記錄用戶身份信息
System.out.println("接收前端==="+username);
session.setAttribute("user", username);
return "success";
}
//退出登陸
@RequestMapping("logout")
public String logout(HttpSession session) throws Exception {
// session 過期
session.invalidate();
return "login";
}
}
3、編寫一個登陸成功的頁面 success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>登錄成功頁面</h1>
<hr>
${user}
<a href="${pageContext.request.contextPath}/user/logout">註銷</a>
</body>
</html>
4、在 index 頁面上測試跳轉!啓動Tomcat 測試,未登錄也可以進入主頁!
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<h1>首頁</h1>
<hr>
<%--登錄--%>
<a href="${pageContext.request.contextPath}/user/jumplogin">登錄</a>
<a href="${pageContext.request.contextPath}/user/jumpSuccess">成功頁面</a>
</body>
</html>
5、編寫用戶登錄攔截器
package com.kuang.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class LoginInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
// 如果是登陸頁面則放行
System.out.println("uri: " + request.getRequestURI());
if (request.getRequestURI().contains("login")) {
return true;
}
HttpSession session = request.getSession();
// 如果用戶已登陸也放行
if(session.getAttribute("user") != null) {
return true;
}
// 用戶沒有登陸跳轉到登陸頁面
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
return false;
}
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
6、在Springmvc的配置文件中註冊攔截器
<!--關於攔截器的配置-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean id="loginInterceptor" class="com.kuang.interceptor.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
7、再次重啓Tomcat測試!
OK,測試登錄攔截功能無誤.
文件上傳和下載
準備工作
文件上傳是項目開發中最常見的功能之一 ,springMVC 可以很好的支持文件上傳,但是SpringMVC上下文中默認沒有裝配MultipartResolver,因此默認情況下其不能處理文件上傳工作。如果想使用Spring的文件上傳功能,則需要在上下文中配置MultipartResolver。
前端表單要求:爲了能上傳文件,必須將表單的method設置爲POST,並將enctype設置爲multipart/form-data。只有在這樣的情況下,瀏覽器纔會把用戶選擇的文件以二進制數據發送給服務器;
對錶單中的 enctype 屬性做個詳細的說明:
- application/x-www=form-urlencoded:默認方式,只處理表單域中的 value 屬性值,採用這種編碼方式的表單會將表單域中的值處理成 URL 編碼方式。
- multipart/form-data:這種編碼方式會以二進制流的方式來處理表單數據,這種編碼方式會把文件域指定文件的內容也封裝到請求參數中,不會對字符編碼。
- text/plain:除了把空格轉換爲 “+” 號外,其他字符都不做編碼處理,這種方式適用直接通過表單發送郵件。
<form action="" enctype="multipart/form-data" method="post">
<input type="file" name="file"/>
<input type="submit">
</form>
一旦設置了enctype爲multipart/form-data,瀏覽器即會採用二進制流的方式來處理表單數據,而對於文件上傳的處理則涉及在服務器端解析原始的HTTP響應。在2003年,Apache Software Foundation發佈了開源的Commons FileUpload組件,其很快成爲Servlet/JSP程序員上傳文件的最佳選擇。
- Servlet3.0規範已經提供方法來處理文件上傳,但這種上傳需要在Servlet中完成。
- 而Spring MVC則提供了更簡單的封裝。
- Spring MVC爲文件上傳提供了直接的支持,這種支持是用即插即用的MultipartResolver實現的。
- Spring MVC使用Apache Commons FileUpload技術實現了一個MultipartResolver實現類:
- CommonsMultipartResolver。因此,SpringMVC的文件上傳還需要依賴Apache Commons FileUpload的組件。
文件上傳
1、導入文件上傳的jar包,commons-fileupload , Maven會自動幫我們導入他的依賴包 commons-io包;
<!--文件上傳-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<!--servlet-api導入高版本的-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
2、配置bean:multipartResolver
【注意!!!這個bena的id必須爲:multipartResolver , 否則上傳文件會報400的錯誤!在這裏栽過坑,教訓!】
<!--文件上傳配置-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 請求的編碼格式,必須和jSP的pageEncoding屬性一致,以便正確讀取表單的內容,默認爲ISO-8859-1 -->
<property name="defaultEncoding" value="utf-8"/>
<!-- 上傳文件大小上限,單位爲字節(10485760=10M) -->
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="40960"/>
</bean>
CommonsMultipartFile 的 常用方法:
- String getOriginalFilename():獲取上傳文件的原名
- InputStream getInputStream():獲取文件流
- void transferTo(File dest):將上傳文件保存到一個目錄文件中
我們去實際測試一下
3、編寫前端頁面
<form action="/upload" enctype="multipart/form-data" method="post">
<input type="file" name="file"/>
<input type="submit" value="upload">
</form>
4、Controller
package com.kuang.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
@Controller
public class FileController {
//@RequestParam("file") 將name=file控件得到的文件封裝成CommonsMultipartFile 對象
//批量上傳CommonsMultipartFile則爲數組即可
@RequestMapping("/upload")
public String fileUpload(@RequestParam("file") CommonsMultipartFile file , HttpServletRequest request) throws IOException {
//獲取文件名 : file.getOriginalFilename();
String uploadFileName = file.getOriginalFilename();
//如果文件名爲空,直接回到首頁!
if ("".equals(uploadFileName)){
return "redirect:/index.jsp";
}
System.out.println("上傳文件名 : "+uploadFileName);
//上傳路徑保存設置
String path = request.getServletContext().getRealPath("/upload");
//如果路徑不存在,創建一個
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
System.out.println("上傳文件保存地址:"+realPath);
InputStream is = file.getInputStream(); //文件輸入流
OutputStream os = new FileOutputStream(new File(realPath,uploadFileName)); //文件輸出流
//讀取寫出
int len=0;
byte[] buffer = new byte[1024];
while ((len=is.read(buffer))!=-1){
os.write(buffer,0,len);
os.flush();
}
os.close();
is.close();
return "redirect:/index.jsp";
}
}
5、測試上傳文件,OK!
採用file.Transto 來保存上傳的文件
1、編寫Controller
/*
* 採用file.Transto 來保存上傳的文件
*/
@RequestMapping("/upload2")
public String fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
//上傳路徑保存設置
String path = request.getServletContext().getRealPath("/upload");
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
//上傳文件地址
System.out.println("上傳文件保存地址:"+realPath);
//通過CommonsMultipartFile的方法直接寫文件(注意這個時候)
file.transferTo(new File(realPath +"/"+ file.getOriginalFilename()));
return "redirect:/index.jsp";
}
2、前端表單提交地址修改
3、訪問提交測試,OK!
文件下載
文件下載步驟:
1、設置 response 響應頭
2、讀取文件 – InputStream
3、寫出文件 – OutputStream
4、執行操作
5、關閉流 (先開後關)
代碼實現:
@RequestMapping(value="/download")
public String downloads(HttpServletResponse response ,HttpServletRequest request) throws Exception{
//要下載的圖片地址
String path = request.getServletContext().getRealPath("/upload");
String fileName = "基礎語法.jpg";
//1、設置response 響應頭
response.reset(); //設置頁面不緩存,清空buffer
response.setCharacterEncoding("UTF-8"); //字符編碼
response.setContentType("multipart/form-data"); //二進制傳輸數據
//設置響應頭
response.setHeader("Content-Disposition",
"attachment;fileName="+URLEncoder.encode(fileName, "UTF-8"));
File file = new File(path,fileName);
//2、 讀取文件--輸入流
InputStream input=new FileInputStream(file);
//3、 寫出文件--輸出流
OutputStream out = response.getOutputStream();
byte[] buff =new byte[1024];
int index=0;
//4、執行 寫出操作
while((index= input.read(buff))!= -1){
out.write(buff, 0, index);
out.flush();
}
out.close();
input.close();
return null;
}
前端
<a href="/download">點擊下載</a>
測試,文件下載OK,大家可以和我們之前學習的JavaWeb原生的方式對比一下,就可以知道這個便捷多了!
tFile 的 常用方法:
- String getOriginalFilename():獲取上傳文件的原名
- InputStream getInputStream():獲取文件流
- void transferTo(File dest):將上傳文件保存到一個目錄文件中
我們去實際測試一下
3、編寫前端頁面
<form action="/upload" enctype="multipart/form-data" method="post">
<input type="file" name="file"/>
<input type="submit" value="upload">
</form>
4、Controller
package com.kuang.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
@Controller
public class FileController {
//@RequestParam("file") 將name=file控件得到的文件封裝成CommonsMultipartFile 對象
//批量上傳CommonsMultipartFile則爲數組即可
@RequestMapping("/upload")
public String fileUpload(@RequestParam("file") CommonsMultipartFile file , HttpServletRequest request) throws IOException {
//獲取文件名 : file.getOriginalFilename();
String uploadFileName = file.getOriginalFilename();
//如果文件名爲空,直接回到首頁!
if ("".equals(uploadFileName)){
return "redirect:/index.jsp";
}
System.out.println("上傳文件名 : "+uploadFileName);
//上傳路徑保存設置
String path = request.getServletContext().getRealPath("/upload");
//如果路徑不存在,創建一個
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
System.out.println("上傳文件保存地址:"+realPath);
InputStream is = file.getInputStream(); //文件輸入流
OutputStream os = new FileOutputStream(new File(realPath,uploadFileName)); //文件輸出流
//讀取寫出
int len=0;
byte[] buffer = new byte[1024];
while ((len=is.read(buffer))!=-1){
os.write(buffer,0,len);
os.flush();
}
os.close();
is.close();
return "redirect:/index.jsp";
}
}
5、測試上傳文件,OK!
採用file.Transto 來保存上傳的文件
1、編寫Controller
/*
* 採用file.Transto 來保存上傳的文件
*/
@RequestMapping("/upload2")
public String fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
//上傳路徑保存設置
String path = request.getServletContext().getRealPath("/upload");
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
//上傳文件地址
System.out.println("上傳文件保存地址:"+realPath);
//通過CommonsMultipartFile的方法直接寫文件(注意這個時候)
file.transferTo(new File(realPath +"/"+ file.getOriginalFilename()));
return "redirect:/index.jsp";
}
2、前端表單提交地址修改
3、訪問提交測試,OK!
文件下載
文件下載步驟:
1、設置 response 響應頭
2、讀取文件 – InputStream
3、寫出文件 – OutputStream
4、執行操作
5、關閉流 (先開後關)
代碼實現:
@RequestMapping(value="/download")
public String downloads(HttpServletResponse response ,HttpServletRequest request) throws Exception{
//要下載的圖片地址
String path = request.getServletContext().getRealPath("/upload");
String fileName = "基礎語法.jpg";
//1、設置response 響應頭
response.reset(); //設置頁面不緩存,清空buffer
response.setCharacterEncoding("UTF-8"); //字符編碼
response.setContentType("multipart/form-data"); //二進制傳輸數據
//設置響應頭
response.setHeader("Content-Disposition",
"attachment;fileName="+URLEncoder.encode(fileName, "UTF-8"));
File file = new File(path,fileName);
//2、 讀取文件--輸入流
InputStream input=new FileInputStream(file);
//3、 寫出文件--輸出流
OutputStream out = response.getOutputStream();
byte[] buff =new byte[1024];
int index=0;
//4、執行 寫出操作
while((index= input.read(buff))!= -1){
out.write(buff, 0, index);
out.flush();
}
out.close();
input.close();
return null;
}
前端
<a href="/download">點擊下載</a>
測試,文件下載OK,大家可以和我們之前學習的JavaWeb原生的方式對比一下,就可以知道這個便捷多了!
攔截器及文件操作在我們開發中十分重要,一定要學會使用!
小結
| 博主整理的springmvc筆記是學習B站狂神說SpringMVC後,對學習過程進行回顧整理的。附上視頻教程:
https://www.bilibili.com/video/BV1aE41167Tu.
如果整理過程中博主有理解不對的地方,歡迎各位小夥伴留言指正,博主一定虛心接受並改正!
如果覺得博主的學習筆記對你有所幫助,可以給博主點一個贊👍