通過idea建立Maven專案整合Spring+spring mvc+mybatis
寫這篇文章是為了整理一下idea下整合maven專案的步驟,也為了以後讓室友們參考
建立專案
File→new→project
然後就不斷next直到專案面板出來
設定資料夾
注意:這裡我個人習慣,在java下還建了ssm資料夾,然後再controll...資料夾,建議跟我一樣,不然你後面配置檔案需要更改
將專案資料夾設定成這個樣子
配置檔案
- 先修改pom.xml匯入專案所需依賴
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zhh</groupId> <artifactId>MavenTest</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>MavenTest Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> <!-- 配置相關jar包的版本 --> <spring.version>4.3.4.RELEASE</spring.version> <aspectj.version>1.8.9</aspectj.version> <mybatis.version>3.4.1</mybatis.version> <mybatis-spring.version>1.3.0</mybatis-spring.version> <jdbc.version>5.1.35</jdbc.version> <fastjson.version>1.2.23</fastjson.version> <log4j.version>2.7</log4j.version> <servlet.version>3.0-alpha-1</servlet.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- 新增spring依賴 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>${aspectj.version}</version> </dependency> <!-- 新增mybatis依賴 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- 新增mybatis-spring依賴 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis-spring.version}</version> </dependency> <!-- 資料庫驅動 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${jdbc.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.7.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.7.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.7.4</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <!-- apache公共包 --> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.10</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.8.0</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.1</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>net.sf.ezmorph</groupId> <artifactId>ezmorph</artifactId> <version>1.0.6</version> </dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.41</version> </dependency> <!-- log4j --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>${log4j.version}</version> </dependency> <!-- JSTL標籤類 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- serlvet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>${servlet.version}</version> <scope>provided</scope> </dependency> </dependencies> <build> <finalName>MavenTest</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.0.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.20.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.0</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> </build> </project>
注意:如果出現提示,按這兩個圖選擇,才能匯入依賴
這是匯入成功後的
- 修改WEB-INF資料夾下的web.xml
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- 設定Spring容器載入配置檔案的路徑 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mybatis.xml</param-value> </context-param> <!--解決POST亂碼問題--> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Spring監聽器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 防止Spring記憶體溢位監聽器 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!--springmvc前端控制器配置--> <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*:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
因為還沒有設定springmvc.xml,所以會報錯沒關係
- 在resources資料夾下新建jdbc.properties log4.properties spring-mvc.xml spring-mybatis.xml
程式碼如下
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8 jdbc.username=root jdbc.password=root #定義初始連線數 initialSize=0 #定義最大連線數 maxActive=20 #定義最大空閒 maxIdle=20 #定義最小空閒 minIdle=1 #定義最長等待時間 maxWait=60000
log4.properties
log4j.rootLogger=INFO,Console,File #控制檯日誌 log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.Target=System.out log4j.appender.Console.layout=org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=[%p][%t][%d{yyyy-MM-dd HH\:mm\:ss}][%C] - %m%n #普通檔案日誌 log4j.appender.File=org.apache.log4j.RollingFileAppender log4j.appender.File.File=logs/ssm.log log4j.appender.File.MaxFileSize=10MB #輸出日誌,如果換成DEBUG表示輸出DEBUG以上級別日誌 log4j.appender.File.Threshold=ALL log4j.appender.File.layout=org.apache.log4j.PatternLayout log4j.appender.File.layout.ConversionPattern=[%p][%t][%d{yyyy-MM-dd HH\:mm\:ss}][%C] - %m%n
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:p="http://www.springframework.org/schema/p" 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-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 自動掃描 @Controller--> <context:component-scan base-package="ssm.controller"/> <!-- 預設的註解對映 --> <mvc:annotation-driven /> <!-- 解除servlet對靜態資原始檔訪問的限制,使得靜態資源先經過 --> <!-- <mvc:default-servlet-handler />--> <mvc:resources mapping="/static/**" location="/static/" /> <!--避免IE執行AJAX時,下載JSON檔案的現象 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- 啟動SpringMVC的註解功能,完成請求和註解POJO的對映 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter"/> <!-- JSON轉換器 --> </list> </property> </bean> <!-- 定義跳轉的檔案的前後綴 ,檢視模式配置--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 自動給後面action的方法return的字串加上字首和字尾,變成一個 可用的url地址 --> <property name="prefix" value="/WEB-INF/page/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
靜態檔案例如css、js存放在static下(靜態資源只放開這個資料夾的訪問)
預設頁面存放路徑在WEB-INF資料夾下的page資料夾下,沒有自己新建
spring-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" 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-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 元件掃描和自動裝配 --> <context:component-scan base-package="ssm"/> <!-- 載入屬性配置檔案 --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 配置資料來源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!-- spring和MyBatis完美整合,不需要mybatis的配置對映檔案 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自動掃描mapping.xml檔案 --> <property name="mapperLocations" value="classpath*:mapper/*.xml"></property> </bean> <!-- DAO介面所在包名,Spring會自動查詢其下的類 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="ssm.dao"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx --> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
配置檔案基本就做好了,現在的資料夾是這個樣子的
現在就可以配置tomcat試著跑一遍了
然後執行就可以了
執行結果
為了方便專案對資料庫表的使用,我們使用MyBatis Generator自動生成程式碼
在resources下建立generatorConfig.xml檔案
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" > <generatorConfiguration> <!--資料庫驅動jar包的真實路徑 --> <classPathEntry location="D:\dataSourceDriver\mysql-connector-java-5.1.47.jar"/> <context id="context" targetRuntime="MyBatis3"> <!-- 是否去除自動生成的註釋 true:是 : false:否 --> <commentGenerator> <property name="suppressAllComments" value="false"/> <property name="suppressDate" value="true"/> </commentGenerator> <!--資料庫連線的資訊:驅動類、連線地址、使用者名稱、密碼 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test" userId="root" password="root"/> <!-- 預設false,把JDBC DECIMAL 和 NUMERIC 型別解析為 Integer,為 true時把JDBC DECIMAL 和 NUMERIC 型別解析為java.math.BigDecimal --> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!--指定包名生成實體類 以及生成的地址 (可以自定義地址,如果路徑不存在會自動建立) --> <javaModelGenerator targetPackage="ssm.model" targetProject=".\src\main\java"> <!-- enableSubPackages:是否讓schema作為包的字尾 --> <property name="enableSubPackages" value="false"/> <!-- 從資料庫返回的值被清理前後的空格 --> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-- !!!! Mapper XML Configurations !!!! --> <sqlMapGenerator targetPackage="mapper" targetProject="F:\ideaProject\MavenTest\src\main\resources"> <property name="enableSubPackages" value="false"/> </sqlMapGenerator> <!-- !!!! Mapper Interface Configurations !!!! --> <javaClientGenerator targetPackage="ssm.dao" targetProject=".\src\main\java" type="XMLMAPPER"> <property name="enableSubPackages" value="false"/> </javaClientGenerator> <!-- 指定資料庫表 --> <!-- tableName是你要生成的表名 --> <table schema="test" tableName="admin" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"/> </context> </generatorConfiguration>
這裡得注意
<classPathEntry
location="D:\dataSourceDriver\mysql-connector-java-5.1.47.jar"/>
這裡寫你自己電腦硬碟上的包的路徑,
<sqlMapGenerator targetPackage="mapper" targetProject="F:\ideaProject\MavenTest\src\main\resources">
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
這裡寫你專案所在工作目錄,設定mapper.xml生成檔案位置
- 在pom.xml中加入
<plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.7</version> <configuration> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> </plugin> </plugins>
-
點選右邊的
右鍵
正常情況應該生成成功,如果失敗根據情況修改 -
這時候我們的專案環境已經全部完成
- 可以寫程式碼實現功能增刪改查了,這裡使用顯示功能
- 在AdminMapper中增加方法
<select id="AdminList" resultMap="BaseResultMap"> select * from admin </select>
2.在dao層寫相應方法List<Admin> AdminList();
3.在service層寫相應方法
先在service資料夾下建立AdminService介面,然後寫上方法List<Admin> AdminList();
4.在impl層實現
@Service("AdminService") public class AdminServiceimpl implements AdminService { @Autowired private AdminMapper adminMapper; @Override public List<Admin> AdminList() { return adminMapper.AdminList(); } }
5.在controller層寫方法
@Controller @RequestMapping("Admin") public class AdminController { @Autowired private AdminService adminService; @RequestMapping("show") public String show(Model model){ List<Admin> list=adminService.AdminList(); model.addAttribute("list",list); return "showAdmin"; } }
然後在page資料夾下新建showAdmin.jsp
先引入
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
然後主要程式碼
<c:forEach items="${list}" var="item">
<tr>
<td height="25" >${item.id}</td>
<td >${item.username}</td>
<td >${item.password}</td>
</tr>
</c:forEach>