建立好maven項目後,開始搭建框架。html
項目結構以下:前端
resource文件夾下建立了三個文件夾mybatis,spring,它們分別用來放相關的配置文件,mapper 文件夾則是用來放查詢數據庫的xml文件。generatorConfjg.xml是用於代碼生成的,在這裏能夠去掉,且不作講述。taglib.xml文件也能夠去掉,與本文無關。java
1.引入包mysql
在pom.xml文件中添加相關依賴包。我這裏引入了一些代理包,能夠自行去掉。web
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <mybatis.version>3.2.8</mybatis.version> <mybatis-spring.version>1.2.1</mybatis-spring.version> <mybatis-ehcache.version>1.0.2</mybatis-ehcache.version> <mysql-connector.version>5.0.5</mysql-connector.version> <druid.version>1.0.4</druid.version> <spring.version>4.1.6.RELEASE</spring.version> <log4j.version>1.2.17</log4j.version> <slf4j.version>1.7.5</slf4j.version> <junit.version>4.11</junit.version> <dom4j.version>1.6.1</dom4j.version> <jaxen.version>1.1.6</jaxen.version> <ehcache.version>2.6.9</ehcache.version> <ehcache-web.version>2.0.4</ehcache-web.version> <cglib.version>3.1</cglib.version> <jackson.version>2.2.3</jackson.version> </properties> <dependencies> <!-- Spring dependencies--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${spring.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${spring.version}</version> </dependency> <!-- Spring Dependencies end --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> </dependency> <!-- mybatis dependencies--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis-spring.version}</version> </dependency> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>org.mybatis.caches</groupId> <artifactId>mybatis-ehcache</artifactId> <version>${mybatis-ehcache.version}</version> </dependency> <!-- mybatis end--> <!-- Log Dependencies --> <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> <!-- Log Dependencies end --> <!-- Test Dependencies --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <!-- Test Dependencies end --> <!--mysql dependencies--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql-connector.version}</version> </dependency> <!--mysql end--> <!-- dataSource dependencies--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <!--datasource end--> <!-- CACHE begin --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>${ehcache.version}</version> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-web</artifactId> <version>${ehcache-web.version}</version> </dependency> <!-- 配置redis data 和client jar--> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.7.2.RELEASE</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.5.1</version> </dependency> <!-- CACHE end --> <dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.7</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--file--> <dependency> <groupId>org.apache.maven.shared</groupId> <artifactId>file-management</artifactId> <version>1.2.1</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> </dependencies> <!--file end-->
2.修改web.xml文件redis
<!-- 加載spring容器--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:config/spring/springContext.xml</param-value> </context-param> <!-- 配置Spring字符編碼過濾器 --> <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> <!-- 配置監聽器--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 配置前端控制器--> <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:config/spring-mvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
3.修改springmvc.xml文件spring
<?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:mvc="http://www.springframework.org/schema/mvc" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="cn.youye.mvc.controller"/> <context:component-scan base-package="cn.youye.mvc.service"/> <mvc:annotation-driven></mvc:annotation-driven> <!--視圖解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
4.添加數據庫配置文件db.propertiessql
注:我所使用的數據庫是testuser,須要根據本身的狀況修改數據庫以及用戶名和鏈接密碼。數據庫
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/testuser?useUnicode=true&characterEncoding=utf8 jdbc.username=root jdbc.password=123456 #pool settings jdbc.initialSize=1 jdbc.minIdle=3 jdbc.maxActive=20
5.添加日誌文件配置文件log4j.propertiesexpress
#console log log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c - %m%n #logger #log4j.logger.org.springframework=DEBUG,CONSOLE #log4j.logger.org.hibernate=INFO,CONSOLE #log4j.logger.org.apache=INFO,CONSOLE log4j.rootLogger=DEBUG,CONSOLE
6.修改springConfig-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" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <context:component-scan base-package="cn.youye.mvc"/> <context:property-placeholder location="classpath:/db.properties"/> <!-- 配置數據源 使用的是alibaba的數據源 也可使用 dbcp--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- 配置基本的參數--> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <!-- 配置初始化大小--> <property name="initialSize" value="${jdbc.initialSize}"/> <property name="maxActive" value="${jdbc.maxActive}"/> <property name="minIdle" value="${jdbc.minIdle}"/> </bean> <!-- 配置SqlSessionFactory mybatis文件配置 掃描全部的mapper文件--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 數據源--> <property name="dataSource" ref="dataSource"/> <!-- 加載mybatis的配置文件--> <property name="configLocation" value="classpath:/config/mybatis/mybatisContext.xml"/> <!--<property name="mapperLocations" value="classpath:config/mapper/*.xml"/>--> <property name="mapperLocations" value="classpath:config/mapper/*.xml"/> </bean> <!-- mapper掃描器 spring 與mybatis整合配置--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cn.youye.mvc.dao"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> <!-- 定義事務管理器 對mybatis操做數據庫的控制,spring使用jdbc的事務控制--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 數據源 dataSource在applicationContext-dao.xml文件中配置--> <property name="dataSource" ref="dataSource"/> </bean> <!-- 通知 配置傳播行爲--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="save*" propagation="REQUIRED"/> <tx:method name="delete*" propagation="REQUIRED"/> <tx:method name="add*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="get*" propagation="SUPPORTS" read-only="true"/> <tx:method name="select*" propagation="SUPPORTS" read-only="true"/> <tx:method name="count*" read-only="true"/> <!-- 對其餘方法 使用默認的事務管理 --> <tx:method name="*"/> </tx:attributes> </tx:advice> <!-- aop配置--> <aop:config> <!-- pointcut:執行service下impl下的全部類的全部方法無論什麼參數--> <aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.youye.mvc.service.*.*(..))"/> </aop:config> <!-- 採用CGLIB代理--> <aop:aspectj-autoproxy proxy-target-class="true"/> <!-- 啓用對事物的註解支持--> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
7.修改mybatisConfig.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> <typeAliases> <package name="cn.youye.mvc.entity"/> </typeAliases> </configuration>
就此環境搭建完成
測試以下:
1.user.class
package cn.youye.mvc.entity; /** * Created by pc on 2016/7/12. */ public class User { private String id; private String name; private String password; private String icon; public User(String id, String name, String password, String icon) { this.id = id; this.name = name; this.password = password; this.icon = icon; } public User() { super(); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } }
2.userDao.java
@Repository("userDao") public interface UserDao { User get(User user); }
3.userService.java
@Service public class UserService { @Autowired UserDao userDao; public User get(User user) { user.setId("b41f12fd-4807-11e6-ba31-408d5cc10d3b"); return userDao.get(user); } }
4.userController.java
@Controller public class UserController { @Autowired UserService userService; @RequestMapping(value = "/login") public String login(@RequestParam String name, @RequestParam String password, HttpServletRequest request) { try { User user = new User(); user.setName(name); user.setPassword(password); user = userService.get(user); if (user != null) { request.setAttribute("msg", "登錄成功"); return "modules/sys/success"; } else { request.setAttribute("msg", "登陸失敗"); return "modules/sys/login"; } } catch (Exception e) { e.printStackTrace(); } return null; } @RequestMapping(value = "/toLogin") public String toLogin() { return "modules/sys/login"; } }
5.login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%--<%@include file="/WEB-INF/views/include/taglib.jsp" %>--%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <c:set var="ctx" value="${pageContext.request.contextPath}"/> <html> <head> <title>登陸</title> </head> <body> ${msg} <form action="${ctx}/login" method="post"> <p>帳戶:<input type="text" id="name" name="name"/></p> <p>密碼:<input type="password" id="password" name="password"/></p> <input type="submit" value="登陸"/> </form> </body> </html>
6.success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%--<%@include file="/WEB-INF/views/include/taglib.jsp" %>--%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <c:set var="ctx" value="${pageContext.request.contextPath}"/> <html> <head> <title>Title</title> </head> <body> <h3>哈哈哈哈哈</h3> ${msg} </body> </html>
7.userDao.xml文件
<?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="cn.youye.mvc.dao.UserDao"> <sql id="Base_Column_List"> id, name, password, icon </sql> <select id="get" parameterType="user" resultType="user"> SELECT <include refid="Base_Column_List"/> FROM USER WHERE id=#{id} </select> </mapper>
效果展現:
注:我在service方法中寫死了userID,因此是根據數據庫中是否存在該ID 的記錄。與是否有輸入並沒有關係。只是懶得寫而已。