Spring MVC淺入淺出——不吹牛逼不裝逼
Spring MVC淺入淺出——不吹牛逼不裝逼
前言
上文書說了Spring相關的知識,對Spring來了個淺入淺出,大家應該瞭解到,Spring在三層架構中主做Service層,那還有Web層,也就是Controller層,這個就由SpringMVC來解決了。SpringMVC是Web層的一個框架,它是Spring的組成部分,可以先看看下面這張圖:
SpringMVC工作原理
MVC模式在之前我已經寫過部落格了《Web開發模式》,學SpringMVC之前有必要先看一下MVC模式。
SpringMVC框架主要由DispatcherServlet、處理器對映、控制器、檢視解析器、檢視組成,其工作流程如下:
- 客戶端請求提交到DispatcherServlet;
- 由DispatcherServlet控制器尋找一個或多個HandlerMapping,找到處理請求的Controller;
- DispatcherServlet將請求提交到Controller;
- Controller呼叫業務邏輯處理後返回ModelAndView;
- DispatcherServlet尋找一個或多個ViewResolver檢視解析器,找到ModelAndView指定的檢視;
- 檢視負責將結果顯示到客戶端。
在SpringMVC工作流程中包含4個SpringMVC介面,即DispatcherServlet、HandlerMapping、Controller和ViewResolver。SpringMVC所有的請求都經過DispatcherServlet來統一分發,在DispatcherServlet將請求分發給Controller之前需要藉助SpringMVC提供的HandlerMapping定位到具體的Controller。
HandlerMapping介面負責完成客戶請求到Controller對映。
Controller介面將處理使用者請求,這和Java 中Servlet扮演的角色是一致的。一旦Controller處理完使用者請求,將返回ModelAndView物件給DispatcherServlet前端控制器,ModelAndView中包含了模型(Model)和檢視(View)。
從巨集觀角度考慮,DispatcherServlet是整個Web應用的控制器;從微觀考慮,Controller是單個Http請求處理過程中的控制器,而ModelAndView是Http請求過程中返回的模型(Model)和檢視(View)。
ViewResolver介面(檢視解析器)在Web應用中負責查詢View物件,從而將相應結果渲染給客戶。
基於註解的控制器
在使用Web應用開發時Controller是Web應用的核心,Controller實現類包含了對使用者請求的處理邏輯,是使用者請求和業務邏輯之間的橋樑就,是SpringMVC框架的核心部分,負責具體的業務邏輯處理。傳統風格的控制器是實現Controller介面的類。傳統風格的控制器不僅需要在配置檔案中部署對映,而且只能編寫一個處理方法,不夠靈活。
基於註解的控制器具有以下兩個優點:
- 在基於註解的控制器類中可以編寫多個處理方法,進而可以處理多個請求(動作),這就允許將相關的操作編寫在同一個控制器類中,從而減少控制器類的數量,方便以後的維護。
- 基於註解的控制器不需要在配置檔案中部署對映,僅需要使用RequestMapping註釋型別註解一個方法進行請求處理。
在SpringMVC中使用掃描機制找到應用中所有基於註解的控制器類,所以,為了讓控制器類被SpringMVC框架掃描到,需要在配置檔案中宣告spring-context,並使用<context:component-scan/>元素指定控制器類的基本包(確保所有控制類都在基本包及其子包下)。示例如下:
<?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:tx="http://www.springframework.org/schema/tx" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd "> <!--配置註解要掃描的包--> <context:component-scan base-package="com.my"></context:component-scan> <!--配置檢視解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--配置字首--> <property name="prefix" value="/"></property> <!--配置字尾--> <property name="suffix" value=".jsp"></property> </bean> </beans>
說這麼多,用例項說話吧
例項解說
Pom.xml
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <!--spring核心依賴--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.1.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.1.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>5.1.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.1.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.1.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>5.1.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.1.5.RELEASE</version> </dependency> </dependencies>
spring-config.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:tx="http://www.springframework.org/schema/tx" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd "> <!--配置註解要掃描的包--> <context:component-scan base-package="com.my"></context:component-scan> <mvc:annotation-driven></mvc:annotation-driven> <!--配置spring-jdbcTemplate--> <!--配置資料來源--> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <!--MySQL資料庫驅動--> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <!--連線資料庫的URL--> <property name="url" value="jdbc:mysql://localhost:3306/bbb?useUnicode=true&characterEncoding=UTF-8"></property> <!--連線資料庫的使用者名稱--> <property name="username" value="root"></property> <!--連線資料庫的密碼--> <property name="password" value="root"></property> </bean> <!--配置JDBC模板--> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> <!--配置事務--> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!--註冊事務註解驅動--> <tx:annotation-driven transaction-manager="txManager"></tx:annotation-driven> <!--配置檢視解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--配置字首--> <property name="prefix" value="/"></property> <!--配置字尾--> <property name="suffix" value=".jsp"></property> </bean> </beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app> <!--部署DispatcherServlet--> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--表示容器在啟動時立即載入servlet--> <load-on-startup>1</load-on-startup> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-config.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <!--處理所有URL--> <url-pattern>/</url-pattern> </servlet-mapping> <!--處理中文亂碼--> <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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--設定訪問靜態資源--> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.jpg</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.png</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.gif</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.mp3</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.mp4</url-pattern> </servlet-mapping> </web-app>
User
package com.my.pojo; public class User { private int id; private String username; private String password; public User() { } public User(int id, String username, String password) { this.id = id; this.username = username; this.password = password; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + '}'; } }
UserDao
package com.my.dao; public interface UserDao { public void add(); public void delete(); public void update(); public void query(); }
UserDaoImpl
package com.my.dao.impl; import com.my.dao.UserDao; import com.my.pojo.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import java.util.List; @Repository("userDao") public class UserDaoImpl implements UserDao { @Autowired //使用配置檔案中的JDBC模板 private JdbcTemplate jdbcTemplate; @Override public void add() { String insertSql = "insert into user values(null,?,?)"; for (int i=0;i<15;i++){ Object parem1[] = {"成功","123456"}; jdbcTemplate.update(insertSql,parem1); } System.out.println("UserDao中的新增功能實現了"); } @Override public void delete() { String deleteSql = "delete from user where id=?"; Object parem2[] = {5}; jdbcTemplate.update(deleteSql,parem2); System.out.println("UserDao中的刪除功能實現了"); } @Override public void update() { String updateSql = "update user set username=? , password=? where id =?"; Object parem3[] = {"修改","654321",3}; jdbcTemplate.update(updateSql,parem3); System.out.println("UserDao中的修改功能實現了"); } @Override public void query() { String selectSql = "select * from user"; RowMapper<User> rowMapper = new BeanPropertyRowMapper<User>(User.class); List<User> list = jdbcTemplate.query(selectSql,rowMapper,null); System.out.println("UserDao中的查詢功能實現了"); for (User user : list){ System.out.println(user); } } }
UserService
package com.my.service; public interface UserService { public void add(); public void delete(); public void update(); public void query(); }
UserServiceImpl
package com.my.service.impl; import com.my.dao.UserDao; import com.my.dao.impl.UserDaoImpl; import com.my.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao ; @Override public void add() { userDao.add(); } @Override public void delete() { userDao.delete(); } @Override public void update() { userDao.update(); } @Override public void query() { userDao.query(); } }
UserController
package com.my.controller; import com.my.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.stereotype.Controller; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @RequestMapping("/add") public String add(){ userService.add(); return "index"; } @RequestMapping("/delete") public String delete(){ userService.delete(); return "index"; } @RequestMapping("/update") public String update(){ userService.update(); return "index"; } @RequestMapping("/query") public String query(){ userService.query(); return "index"; } }
測試結果
結束
欲看下文如何,請看下回講解。
*****************************************************************************************************
我的部落格園地址:https://www.cnblogs.com/zyx110/
轉載請說明出處
我不能保證我所說的都是對的,但我能保證每一篇都是用心去寫的,我始終認同“分享的越多,你的價值增值越大”,歡迎大家關注我的技術分享“Java匹馬行天下”和學習心得分享“匹馬行天下”,在分享中進步,越努力越幸運,人生贏在轉折處,改變從現在開始!
支援我的朋友們記得點波推薦哦,您的肯定就是我前進的動力。
&n