创建好maven项目后,开始搭建框架。
项目结构如下:
resource文件夹下创建了三个文件夹mybatis,spring,它们分别用来放相关的配置文件,mapper 文件夹则是用来放查询数据库的xml文件。generatorConfjg.xml是用于代码生成的,在这里可以去掉,且不做讲述。taglib.xml文件也可以去掉,与本文无关。
1.引入包
在pom.xml文件中添加相关依赖包。我这里引入了一些代理包,可以自行去掉。
<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文件
<!-- 加载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文件
<?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.properties
注:我所使用的数据库是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.properties
#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 的记录。与是否有输入并无关系。只是懒得写而已。