javascript
SpringMVC以及SSM整合
本人才疏學淺,如有錯誤歡迎批評!轉載請注明出處:https://www.cnblogs.com/lee-yangyaozi/p/11226145.html
SpringMVC概述
Spring Web MVC是一種基于Java的實現了Web MVC設計模式的請求驅動類型的輕量級Web框架,即使用了MVC架構模式的思想,將web層進行職責解耦,基于請求驅動指的就是使用請求-響應模型,框架的目的就是幫助我們簡化開發,Spring Web MVC也是要簡化我們日常Web開發的。
?
什么是MVC
- 接收用戶請求,委托給模型進行處理(狀態改變),處理完畢后把返回的模型數據返回給視圖,由視圖負責展示。 也就是說控制器做了個調度員的工作。
?
SpringMVC的強大之處
- Spring MVC 實現了即用的 MVC 的核心概念。它為控制器和處理程序提供了大量與此模式相關的功能。并且當向 MVC 添加反轉控制(Inversion of Control,IoC)時,它使應用程序高度解耦,提供了通過簡單的配置更改即可動態更改組件的靈活性。Spring MVC 為您提供了完全控制應用程序的各個方面的力量。
- Spring 的 Web MVC 模塊是圍繞 DispatcherServlet 而設計的。DispatcherServlet 給處理程序分派請求,執行視圖解析,并且處理語言環境和主題解析,此外還為上傳文件提供支持。
- DispatcherServlet 通過使用處理程序映射來決定哪一個處理程序應當處理傳入的請求。處理程序映射只是用于標識使用哪一個處理程序來處理特定 URL 模式的映射。處理程序是只有一種方法 ModelAndView handleRequest(request,response) 的控制器接口的實現。Spring 還有一些可用的高級處理程序實現;其中一個重要的高級處理程序實現是 SimpleFormController,它提供了將命令對象綁定到表單、對其執行驗證等功能。
這些描述都是我從別的文檔上摘下來了,看得云里霧里的,我個人理解,SpringMVC其實就是對servlet的封裝。沒用ssm的時候,前端頁面調用Controller(servlet)時需要在web.xml內為每一個servlet進行配置,非常麻煩;使用SpringMVC之后,只需要幾個注解就可以輕松訪問Controller,并且數據的傳輸也變得非常方便,其實說白了,框架就是簡化開發而存在的,使得程序員更關注在業務上而不是(基礎)代碼上。
?
常用的SpringMVC注解
- @Controller:表明該類是一個Controller
- @RequestMapping:前端訪問地址
- @RequestBody:將 HTTP 請求正文插入方法中,使用適合的 HttpMessageConverter 將請求體寫入某個對象
- @ResponseBody:加在方法前,表明該方法的返回值不再是jsp頁面名稱,而是向前端傳輸數據
- @RestController:表明該類是一個Controller,并且相當于類中全部方法都是@ResponseBody方法
- @RequestParam("xxx"):加在方法參數前,其內的名字和前端傳來的參數名相同,常用于方法參數名和前端表單元素名不同
- @PathVariable:獲取請求路徑中部分數據
?
SSM整合
- 加入依賴(jar)包
?
<dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version><scope>provided</scope></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>4.3.8.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>4.3.8.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>4.3.8.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>4.3.8.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-beans</artifactId><version>4.3.8.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>4.3.8.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>4.3.8.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>4.3.8.RELEASE</version></dependency><dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId><version>2.8.2</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.3</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>1.7.21</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>1.7.21</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.46</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.10</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.2.8</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.3.1</version></dependency><dependency><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-core</artifactId><version>1.3.7</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.8</version></dependency><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.2</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.5</version></dependency><dependency><groupId>taglibs</groupId><artifactId>standard</artifactId><version>1.1.2</version></dependency><dependency><groupId>jstl</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency>?
- 配置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"><context-param><param-name>log4jConfigLocation</param-name><param-value>classpath:log4j.properties</param-value></context-param><context-param><param-name>log4jRefreshInterval</param-name><param-value>60000</param-value></context-param><!-- Log4j的監聽器要放在spring監聽器前面 --><listener><listener-class>org.springframework.web.util.Log4jConfigListener</listener-class></listener><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-context*.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><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><servlet-name>springServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath*:/spring-mvc*.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>springServlet</servlet-name><url-pattern>/</url-pattern></servlet-mapping><welcome-file-list><welcome-file>static/index.html</welcome-file><welcome-file>index.htm</welcome-file><welcome-file>index.jsp</welcome-file></welcome-file-list></web-app>?
<?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"><context-param><param-name>log4jConfigLocation</param-name><param-value>classpath:log4j.properties</param-value></context-param><context-param><param-name>log4jRefreshInterval</param-name><param-value>60000</param-value></context-param><!-- Log4j的監聽器要放在spring監聽器前面 --><listener><listener-class>org.springframework.web.util.Log4jConfigListener</listener-class></listener><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-context*.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><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><servlet-name>springServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath*:/spring-mvc*.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>springServlet</servlet-name><url-pattern>/</url-pattern></servlet-mapping><welcome-file-list><welcome-file>static/index.html</welcome-file><welcome-file>index.htm</welcome-file><welcome-file>index.jsp</welcome-file></welcome-file-list></web-app>?
- 編寫ssm的配置文件
db.properties
?
# JDBC jdbc.driverClass=com.mysql.jdbc.Driver jdbc.connectionURL=jdbc:mysql://localhost:3306/test?allowMultiQueries=true&useUnicode=true&characterEncoding=utf-8&useSSL=false jdbc.userName=root jdbc.password=123456# JDBC Pool jdbc.pool.init=1 jdbc.pool.minIdle=3 jdbc.pool.maxActive=20# JDBC Test jdbc.testSql=SELECT 'x' FROM DUAL#============================# #==== Framework settings ====# #============================## \u89c6\u56fe\u6587\u4ef6\u5b58\u653e\u8def\u5f84 web.view.prefix=/WEB-INF/views/ web.view.suffix=.jsp?
spring-context.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"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"><!--開啟注解掃描--><context:annotation-config/><!--不掃描Controller注解--><context:component-scan base-package="com.alfred"><context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/></context:component-scan><!-- 配置事務管理器 --><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/></bean><!-- 開啟事務注解驅動 --><tx:annotation-driven transaction-manager="transactionManager"/> </beans>spring-context-druid.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 http://www.springframework.org/schema/context/spring-context.xsd"><!-- 加載配置屬性文件 --><context:property-placeholder ignore-unresolvable="true" location="classpath:db.properties"/><!-- 數據源配置, 使用 Druid 數據庫連接池 --><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"><!-- 數據源驅動類可不寫,Druid默認會自動根據URL識別DriverClass --><property name="driverClassName" value="${jdbc.driverClass}"/><!-- 基本屬性 url、user、password --><property name="url" value="${jdbc.connectionURL}"/><property name="username" value="${jdbc.userName}"/><property name="password" value="${jdbc.password}"/><!-- 配置初始化大小、最小、最大 --><property name="initialSize" value="${jdbc.pool.init}"/><property name="minIdle" value="${jdbc.pool.minIdle}"/><property name="maxActive" value="${jdbc.pool.maxActive}"/><!-- 配置獲取連接等待超時的時間 --><property name="maxWait" value="60000"/><!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒 --><property name="timeBetweenEvictionRunsMillis" value="60000"/><!-- 配置一個連接在池中最小生存的時間,單位是毫秒 --><property name="minEvictableIdleTimeMillis" value="300000"/><property name="validationQuery" value="${jdbc.testSql}"/><property name="testWhileIdle" value="true"/><property name="testOnBorrow" value="false"/><property name="testOnReturn" value="false"/><!-- 配置監控統計攔截的filters --><property name="filters" value="stat"/></bean> </beans>?
spring-context-mybatis.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 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"><!-- 配置 SqlSession --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource"/><!-- 用于配置對應實體類所在的包,多個 package 之間可以用 ',' 號分割 --><property name="typeAliasesPackage" value="com.alfred.domain"/><!-- 用于配置對象關系映射配置文件所在目錄 --><property name="mapperLocations" value="classpath:/mapper/*.xml"/><property name="configLocation" value="classpath:/mybatis-config.xml"></property></bean><!-- 掃描 Mapper --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.alfred.mapper" /></bean> </beans>?
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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"><description>Spring MVC Configuration</description><!-- 加載配置屬性文件 --><context:property-placeholder ignore-unresolvable="true" location="classpath:db.properties"/><!-- 使用 Annotation 自動注冊 Bean,只掃描 @Controller --><context:component-scan base-package="com.alfred" use-default-filters="false"><context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/></context:component-scan><!-- 默認的注解映射的支持 --><mvc:annotation-driven/><!-- 定義視圖文件解析 --><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="${web.view.prefix}"/><property name="suffix" value="${web.view.suffix}"/></bean><!--文件上傳bean 定義--><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><!-- 默認編碼 --><property name="defaultEncoding" value="utf-8"/><!-- 文件大小最大值 --><property name="maxUploadSize" value="10485760000"/><!-- 內存中的最大值 --><property name="maxInMemorySize" value="40960"/><!-- 啟用是為了推遲文件解析,以便捕獲文件大小異常 --><property name="resolveLazily" value="true"/></bean><!-- 靜態資源映射 --><mvc:resources mapping="/static/**" location="/static/" cache-period="31536000"/><!-- 解決前后端分離跨域問題--><mvc:cors><mvc:mapping path="/**"allowed-origins="*"allowed-methods="POST, GET, OPTIONS, DELETE, PUT,PATCH"allowed-headers="Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"allow-credentials="true"/></mvc:cors></beans>?
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><!-- 全局參數 --><settings><!-- 打印 SQL 語句 --><setting name="logImpl" value="STDOUT_LOGGING" /><!-- 使全局的映射器啟用或禁用緩存。 --><setting name="cacheEnabled" value="false"/><!-- 全局啟用或禁用延遲加載。當禁用時,所有關聯對象都會即時加載。 --><setting name="lazyLoadingEnabled" value="true"/><!-- 當啟用時,有延遲加載屬性的對象在被調用時將會完全加載任意屬性。否則,每種屬性將會按需要加載。 --><setting name="aggressiveLazyLoading" value="true"/><!-- 是否允許單條 SQL 返回多個數據集 (取決于驅動的兼容性) default:true --><setting name="multipleResultSetsEnabled" value="true"/><!-- 是否可以使用列的別名 (取決于驅動的兼容性) default:true --><setting name="useColumnLabel" value="true"/><!-- 允許 JDBC 生成主鍵。需要驅動器支持。如果設為了 true,這個設置將強制使用被生成的主鍵,有一些驅動器不兼容不過仍然可以執行。 default:false --><setting name="useGeneratedKeys" value="false"/><!-- 指定 MyBatis 如何自動映射 數據基表的列 NONE:不映射 PARTIAL:部分 FULL:全部 --><setting name="autoMappingBehavior" value="PARTIAL"/><!-- 這是默認的執行類型 (SIMPLE: 簡單; REUSE: 執行器可能重復使用prepared statements語句;BATCH: 執行器可以重復執行語句和批量更新) --><setting name="defaultExecutorType" value="SIMPLE"/><!-- 使用駝峰命名法轉換字段。 --><setting name="mapUnderscoreToCamelCase" value="true"/><!-- 設置本地緩存范圍 session:就會有數據的共享 statement:語句范圍 (這樣就不會有數據的共享 ) defalut:session --><setting name="localCacheScope" value="SESSION"/><!-- 設置 JDBC 類型為空時,某些驅動程序 要指定值, default:OTHER,插入空值時不需要指定類型 --><setting name="jdbcTypeForNull" value="NULL"/></settings></configuration>?逆向工程(一鍵生成實體類、sql語句、接口)
pom文件
?
<dependency><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-core</artifactId><version>1.3.7</version></dependency><build><plugins><!-- mybatis逆向工程插件 --><plugin><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-maven-plugin</artifactId><version>1.3.5</version><dependencies><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.16</version></dependency></dependencies><configuration><!--配置文件的路徑--><configurationFile>src/main/resources/generator/generatorConfig.xml</configurationFile><overwrite>true</overwrite></configuration></plugin></plugins><!-- 解決配置文件不生效問題--><resources><resource><includes><include>**/*.*</include></includes><directory>src/main/resources</directory></resource></resources></build>?
?
?
配置文件
generatorConfig.xml
?
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfigurationPUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN""http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"><generatorConfiguration><context id="DB2Tables" targetRuntime="MyBatis3"><commentGenerator><property name="suppressDate" value="false"/><!-- 是否去除自動生成的注釋 true:是 : false:否 --><property name="suppressAllComments" value="true"/></commentGenerator><!--數據庫鏈接URL,用戶名、密碼 --><jdbcConnection driverClass="com.mysql.jdbc.Driver"connectionURL="jdbc:mysql://localhost:3306/beitong?serverTimezone=Asia/Shanghai"userId="root"password="101203"><!--<property name="serverTimezone" value="UTC"/>--><property name="nullCatalogMeansCurrent" value="true"/></jdbcConnection><!--指定生成entity實體類的具體位置--><javaModelGenerator targetPackage="com.alfred.domain" targetProject="./src/main/java"><property name="enableSubPackages" value="true"/><property name="trimStrings" value="true"/></javaModelGenerator><!--指定生成mybatis映射xml文件的包名和位置--><sqlMapGenerator targetPackage="mapper" targetProject="./src/main/resources"><property name="enableSubPackages" value="true"/></sqlMapGenerator><!--指定生成mapper接口的具體位置--><javaClientGenerator targetPackage="com.alfred.mapper" targetProject="./src/main/java" type="XMLMAPPER"><property name="enableSubPackages" value="true"/></javaClientGenerator><!--<!– 要生成entity/mapper的表名及自定義的DO名 –>--><!--<table tableName="users" domainObjectName="User"/>--><!--<table tableName="product_brand" domainObjectName="ProductBrand" />--><!--mybatis generator代碼生成器在默認的情況下會生成對于表實體類的一個Examle類, 可以更改生成器的配置可避免生成Examle類,enableCountByExample,enableUpdateByExample,enableDeleteByExample,enableSelectByExample等配置為false后, 就不會生成生成Examle類了 --><!--<table tableName="user" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"enableSelectByExample="false" selectByExampleQueryId="false"/><table tableName="commodity" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"enableSelectByExample="false" selectByExampleQueryId="false"/>--><table tableName="orders" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"enableSelectByExample="false" selectByExampleQueryId="false"/><!--<table tableName="orders_info" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"enableSelectByExample="false" selectByExampleQueryId="false"/><table tableName="cart" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"enableSelectByExample="false" selectByExampleQueryId="false"/><table tableName="user_address" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"enableSelectByExample="false" selectByExampleQueryId="false"/>--></context> </generatorConfiguration>?
轉載于:https://www.cnblogs.com/lee-yangyaozi/p/11226145.html
總結
以上是生活随笔為你收集整理的SpringMVC以及SSM整合的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 谈工作与学习
- 下一篇: JS创建多个下载任务