使用Idea搭建基於Maven的單模塊(即Dao,service,controller以及webapp均在一個父模塊中)css
1.File->New project建立基於Maven的web項目html
2.填寫基本的項目信息:java
3.選擇Maven所在的本地目錄,以及配置文件setting.xml的位置mysql
ps:在maven的配置文件setting.xml文件中mirrors節點下配置阿里雲的遠程倉庫鏡像地址,可讓項目的目錄結構生成以及jar包的下載速度變快.web
<mirror> <id>alimaven</id> <name>aliyun maven</name> <url>http://maven.aliyun.com/nexus/content/groups/public/</url> <mirrorOf>central</mirrorOf> </mirror>
4.項目信息填寫spring
5.完成後 ,等待idea生成相應的目錄結構sql
因爲該目錄結構並不完整,在File->Project Structure上補充完整的目錄,同時將目錄標記成相應的顏色數據庫
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.chuyu.web</groupId> <artifactId>web-ssm</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>web-ssm Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <!-- spring 版本號 --> <spring.version>4.0.2.RELEASE</spring.version> <!-- mybatis版本號 --> <mybatis-version>3.2.6</mybatis-version> <!-- 日誌版本 --> <slf4j-version>1.7.7</slf4j-version> <log4j-version>1.2.17</log4j-version> <!-- Junit版本號--> <Junit-version>4.5</Junit-version> <!-- mysql驅動版本號 --> <mysql-driver.version>5.1.29</mysql-driver.version> </properties> <dependencies> <!--導入spring依賴的jar包--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- mybatis核心包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis-version}</version> </dependency> <dependency> <!-- mybatis-spring --> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- 添加mysql驅動依賴 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql-driver.version}</version> </dependency> <!-- 添加數據庫鏈接池依賴 --> <!--<dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.2</version> </dependency>--> <!--druids數據鏈接池--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.18</version> </dependency> <!-- 添加fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.41</version> </dependency> <!-- 添加日誌相關jar包 --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j-version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j-version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j-version}</version> </dependency> <!-- 其餘JSON,在springmvc配置文件中json綁定可能會用到 --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.0</version> </dependency> <!--其餘工具包--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.9</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${Junit-version}</version> <scope>test</scope> </dependency> <!-- jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> </dependencies> <build> <plugins> <!-- mybatis的自動生成dao.xml的插件 --> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> </plugin> </plugins> <!--配置Maven 對resource文件 過濾 --> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> <finalName>web-ssm</finalName> </build> </project>
<?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-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"> <!--配置包掃描的完整包名--> <context:component-scan base-package="com.chuyu.ssm"/> <!--導入其餘的配置文件--> <import resource="spring-mybatis.xml"/> </beans>
driverClasss=com.mysql.jdbc.Driver jdbcUrl=jdbc:mysql://localhost:3306/quick4j?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull username=root password=123456 #定義初始鏈接數 initialSize=0 #定義最大鏈接數 maxActive=20 #定義最小空閒 minIdle=1 #定義最長等待時間 maxWait=60000 timeBetweenEvictionRunsMillis=28800
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=E:/IdeaProjects/web-ssm/src/main/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
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx" 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"> <!-- 引入配置文件 --> <bean id="propertityConfigure" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties"/> </bean> <!-- 第二種方式:加載多個properties文件--> <!--<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="locations"> <list> <value>classpath:jdbc.properties</value> <value>classpath:common.properties</value> </list> </property> <property name="fileEncoding" value="UTF-8"/> </bean> --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName" value="${driverClasss}"/> <property name="url" value="${jdbcUrl}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> <!-- 初始化鏈接大小 --> <property name="initialSize" value="${initialSize}"></property> <!-- 鏈接池最大數量 --> <property name="maxActive" value="${maxActive}"></property> <!-- 鏈接池最小空閒 --> <property name="minIdle" value="${minIdle}"></property> <!-- 獲取鏈接最大等待時間 --> <property name="maxWait" value="${maxWait}"></property> <!-- 配置間隔多久才進行一次檢測,檢測須要關閉的空閒鏈接,單位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" /> <property name="validationQuery" value="SELECT 'x'" /> <property name="testWhileIdle" value="true" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <!-- 打開PSCache,而且指定每一個鏈接上PSCache的大小 --> <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> <!-- 配置監控統計攔截的filters,去掉後監控界面sql沒法統計 --> <property name="filters" value="stat" /> </bean> <!-- mybatis和spring完美整合,不須要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 自動掃描mapping.xml文件 --> <property name="mapperLocations" value="classpath:com/chuyu/ssm/dao/*-Mapper.xml"/> </bean> <!-- Dao藉口所在的包名 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.chuyu.ssm.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <!-- 事物管理 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!--註解驅動--> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
處處spring整合mybatis的部分完成,若是爲了測試是否整合成功,能夠在src/main/test 包中新建測試類 ,驗證是否連通數據庫再整合springMvc.apache
測試類以下json
import com.alibaba.fastjson.JSON; import com.chuyu.ssm.model.User_Dao; import com.chuyu.ssm.service.inte.User_loginServices; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations ="classpath*:application.xml") public class TestUser_loginservice { @Autowired private User_loginServices user_loginServices; @Test public void test1(){ User_Dao user=user_loginServices.selectUser("admin", "123456"); System.out.println(JSON.toJSON(user)); } }
這裏採用的是Junit4.5的測試方法.其中的service部分的代碼能夠參考後面章節.
PS:若是比較熟練能夠省掉此處測試步驟<?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 http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--註解驅動 --> <!-- 會自動註冊RequestMappingHandlerMapping與RequestMappingHandlerAdapter兩個Bean(spring3.0之後的版本), 這是Spring MVC爲@Controller分發請求所必需的,而且提供了數據綁定支持, @NumberFormatannotation支持,@DateTimeFormat支持, @Valid支持讀寫XML的支持(JAXB)和讀寫JSON的支持(默認Jackson)等功能。 --> <mvc:annotation-driven/> <!-- 自動掃描 @Controller--> <context:component-scan base-package="com.chuyu.ssm.controller"/> <!--避免IE執行AJAX時,返回JSON出現下載文件 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <!-- 解釋JSON --> <list> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>text/json;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> </bean> </list> </property> </bean> <!-- 定義跳轉的文件的先後綴 ,視圖模式配置 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp"/> </bean> <!-- 文件上傳配置 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 默認編碼 --> <property name="defaultEncoding" value="UTF-8"/> <!-- 上傳文件大小限制爲31M,31*1024*1024 --> <property name="maxUploadSize" value="32505856"/> <!-- 內存中的最大值 --> <property name="maxInMemorySize" value="4096"/> </bean> </beans>
<?xml version="1.0" encoding="utf-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Archetype Created Web Application</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:application.xml</param-value> </context-param> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 防止spring內存溢出監聽器,好比quartz --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</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> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--druid過濾器filter--> <filter> <filter-name>DruidWebstateFilter</filter-name> <filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class> <init-param> <param-name>exclusions</param-name> <param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value> </init-param> </filter> <filter-mapping> <filter-name>DruidWebstateFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- spring mvc servlet--> <servlet> <servlet-name>SpringMVC</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>SpringMVC</servlet-name> <!-- 此處也能夠配置成 *.do 形式 --> <url-pattern>*.action</url-pattern> </servlet-mapping> <!--servlet for Druid--> <servlet> <servlet-name>DruidStatView</servlet-name> <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class> <!-- 配置訪問權限: deny優先於allow,若是在deny列表中,就算在allow列表中,也會被拒絕。 若是allow沒有配置或者爲空,則容許全部訪問 --> <!-- <init-param> <param-name>allow</param-name> <param-value>128.242.127.1/24,127.0.0.1</param-value> </init-param> <init-param> <param-name>deny</param-name> <param-value>192.168.1.118</param-value> </init-param> --> <!-- 在StatViewSerlvet輸出的html頁面中,有一個功能是Reset All,執行這個操做以後,會致使全部計數器清零,從新計數 --> <init-param> <param-name>resetEnable</param-name> <param-value>false</param-value> </init-param> <init-param> <param-name>loginUsername</param-name> <param-value>admin</param-value> </init-param> <init-param> <param-name>loginPassword</param-name> <param-value>123456</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>DruidStatView</servlet-name> <url-pattern>/druid/*</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> </web-app>
1.Dao層以及接口文件:
利用mybatis的插件Mybatis-generaotr-plugin生成實體類,Dao文件以及*Mapper.xml
映射文件:(具體步驟見:http://www.javashuo.com/article/p-pakvmorc-et.html)
2.service層代碼清單
@Service public class User_loginServiceImpl implements User_loginServices { @Autowired private User_DaoMapper user_dao; @Override public User_Dao selectUser(String userName, String userPassword) { User_DaoExample example=new User_DaoExample(); User_DaoExample.Criteria condition=example.createCriteria(); condition.andUsernameEqualTo(userName); condition.andPasswordEqualTo(userPassword); List<User_Dao> user_list=user_dao.selectByExample(example); if(!CollectionUtils.isEmpty(user_list)){ return user_list.get(0); } return null; } }
3.Action層代碼清單
以簡單的登陸邏輯演示
@Controller @RequestMapping("/userLogin") public class UserLoginAction { @Autowired private User_loginServices user_loginServices; @RequestMapping("/authentication") public String userLogin(User_Dao paramDao){ User_Dao user=user_loginServices.selectUser(paramDao.getUsername(), paramDao.getPassword()); if (user!=null){ System.out.println(JSON.toJSON(user)); return "success"; } return "fail"; } }
4.前臺頁面
以簡單的登陸界面來演示整合的SSM,登陸成功則跳轉到成功頁面,失敗則跳轉到失敗頁面
因爲在配置文件中指定的前綴爲/web-inf/jsp/ ,全部在web/info下新建jsp文件夾
index.jsp代碼:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <base href="<%=basePath%>"> </head> <br> <h2>登陸界面!</h2> <form action="<%=basePath%>userLogin/authentication.action" method="post"> <label>用戶名:</label><input type="text" name="username"></br> <label> 密碼:</label><input type="text" name="password"/></br> <button type="submit">提交</button> </form> </body> </html>
其餘登陸成功和失敗跳轉的頁面即在body裏面添加內容以做區分便可.
5:數據庫
本例以Mysql爲例,創建一個簡單的表包含id,username,password 便可做爲測試用
對應Maven的各個生命週期,包括插件的知識詳見:http://www.javashuo.com/article/p-qzqijvtt-hm.html
(打包過程當中可能會出現:
[WARNING] Warning: selected war files include a WEB-INF/web.xml which will be ignored
(webxml attribute is missing from war task, or ignoreWebxml attribute is specified as 'true')
解決辦法:
pom文件添加一下內容:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.1.1</version> <configuration> <packagingExcludes>WEB-INF/web.xml</packagingExcludes> </configuration> </plugin>
)
6:運行部署
點擊Tomcat7旁邊的運行按鈕啓動項目,若是沒有啓動異常,打開瀏覽器訪問http://localhost:8080/web-ssm
訪問:
至此,做爲一個簡單的整合SSM結束,後續也會在這個基礎上做進一步的優化,包括數據的緩存,模塊的劃分(Maven 繼承與聚合),分佈式框架的集羣搭建,以及Nginx的負載均衡等