spring mvc mybatis 搭建 配置文件信息
参考地址:http://blog.csdn.net/fox_lht/article/details/16952683
shiro集成:http://www.cnblogs.com/miskis/p/5573710.html
pom.xml文件配置 引入需要的依赖包
<properties> <springVersion>4.2.1.RELEASE</springVersion> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${springVersion}</version> </dependency> <!-- tomcat 依赖包 --> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-core</artifactId> <version>7.0.39</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-logging-juli</artifactId> <version>7.0.39</version> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <version>7.0.39</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity</artifactId> <version>1.7</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-tools-view</artifactId> <version>2.1.0-SNAPSHOT</version> </dependency> <!-- mybatis 依赖包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.1</version> </dependency> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <!-- 分页包 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>4.0.1</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.17</version> </dependency> <!-- list转json字符串 --> <dependency> <groupId>com.google.http-client</groupId> <artifactId>google-http-client-gson</artifactId> <version>1.13.1-beta</version> </dependency> <!-- fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.7</version> </dependency>
</dependencies>
web.xml 文件配置
<web-app 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_3_0.xsd" version="3.0"> <servlet> <servlet-name>spring-mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-mvc-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring-mvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
spring-mvc-servlet.xml 文件配置
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" 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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- 自动扫描的包名 ,使Spring支持自动检测组件,如注解的Controller--> <context:component-scan base-package="com.xyz.*" /> <!-- mvc全注解 --> <mvc:annotation-driven /> <!-- 静态资源加载 --> <mvc:default-servlet-handler /> <!-- shiro注解支持 --> <bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer"> <property name="resourceLoaderPath" value="/WEB-INF/view/" /> <property name="velocityProperties"> <props> <prop key="input.encoding">UTF-8</prop> <prop key="output.encoding">UTF-8</prop> </props> </property> </bean> <bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver"> <!-- 加载 toolbox配置文件 --> <!-- <property name="toolboxConfigLocation" value="/WEB-INF/config/velocity-config.xml" /> --> <property name="exposeSpringMacroHelpers" value="true" /> <!-- 配置后页面 可以使用 ${rc.contextPath}来添加js css <link rel="stylesheet" href=" ${rc.contextPath}/assets/login/css/style.css"> --> <property name="requestContextAttribute" value="rc" /> <property name="cache" value="true" /> <property name="contentType" value="text/html;charset=UTF-8" /> <property name="prefix" value="" /> <property name="suffix" value=".htm" /> </bean> </beans>
使用Tomcat 启动项目
在src/test/java下创建包 bootstrap, 在 bootstrap 下创建 GztpayJettyBootStrap 类。 在 bootstrap 创建包 tomcat ,在tomcat 下创建类TomcatBootstrapHelper
GztpayJettyBootStrap 类代码如下 注:这两个类的包在pom.xml 中已引入
/** * created since 2012-5-23 */ package bootstrap; import bootstrap.tomcat.TomcatBootstrapHelper; /** * @author jlcon * @version $Id: GztpayJettyBootStrap.java,v 2.0 2015-6-23 下午6:12:16 JLCON Exp $ */ public class GztpayJettyBootStrap { public static void main(String[] args) throws Exception {
//8082 为启动端口 new TomcatBootstrapHelper(8082,false, "dev").start(); } }
TomcatBootstrapHelper 类型代码:
package bootstrap.tomcat; import javax.servlet.ServletException; import org.apache.catalina.Context; import org.apache.catalina.connector.Connector; import org.apache.catalina.startup.Tomcat; import org.apache.tomcat.util.scan.StandardJarScanner; /** * 嵌入式tomcat web应用启动类,为了避免测试时和线上的容器差别导致的问题,请优先使用此类。 * <p> * 目录结构请参照标准的maven目录结构 * </p> * <p> * 设置环境变量spring.profiles.active=dev * </p> * <h3>Usage Examples</h3> * <p/> * <li>1.maven增加依赖</li> * * <pre> * {@code * <dependency> * <groupId>org.apache.tomcat.embed</groupId> * <artifactId>tomcat-embed-logging-juli</artifactId> * <version>7.0.39</version> * <scope>test</scope> * </dependency> * <dependency> * <groupId>org.apache.tomcat.embed</groupId> * <artifactId>tomcat-embed-jasper</artifactId> * <version>7.0.39</version> * <scope>test</scope> * </dependency> * } * </pre> * <li>2.编写启动类</li> * * <pre> * public static void main(final String[] args) { * //传入监听端口 * new TomcatBootstrapHelper(11111).start(); * * } * </pre> * * @author jlcon <jianglu@gzt.gov.cn> */ public class TomcatBootstrapHelper { private static final char ENTER_CHAR = '\n'; /** * 默认端口 */ private static final int DEFAULT_PORT = 8080; private static final String DEFULT_ENV = "dev"; private int port = DEFAULT_PORT; /** * 是否启用servlet 3.0 支持,如果启用的话,就需要扫描jar包中是否有Servlet等annotation,这个会影响启动时间,默认不开启 */ private boolean isServlet3Enable = false; /** * 构建一个<code>TomcatBootstrapHelper.java</code> * * @param port 端口 * @param isServlet3Enable 是否启用servlet 3.0 * 支持,如果启用的话,就需要扫描jar包中是否有Servlet等annotation,这个会影响启动时间,默认不开启 * @param env 设置环境变量 spring.profiles.active */ public TomcatBootstrapHelper(int port, boolean isServlet3Enable, String env) { System.setProperty("spring.profiles.active", env); this.port = port; this.isServlet3Enable = isServlet3Enable; } /** * 构建一个<code>TomcatBootstrapHelper.java</code><br> * 环境变量spring.profiles.active=dev * * @param port 端口 * @param isServlet3Enable 是否启用servlet 3.0 * 支持,如果启用的话,就需要扫描jar包中是否有Servlet等annotation,这个会影响启动时间,默认不开启 */ public TomcatBootstrapHelper(int port, boolean isServlet3Enable) { this(port, isServlet3Enable, DEFULT_ENV); } /** * 构建一个<code>TomcatBootstrapHelper.java</code><br> * 不启用servlet 3.0 支持、环境变量spring.profiles.active=dev * * @param port 端口 */ public TomcatBootstrapHelper(int port) { this(port, false); } /** * 构建一个<code>TomcatBootstrapHelper.java</code><br> * 端口:8080、不启用servlet 3.0 支持、环境变量spring.profiles.active=dev */ public TomcatBootstrapHelper() { this(DEFAULT_PORT); } public void start() { try { long begin = System.currentTimeMillis(); Tomcat tomcat = new Tomcat(); configTomcat(tomcat); tomcat.start(); long end = System.currentTimeMillis(); log(end - begin); //在控制台回车就可以重启,提高效率 while (true) { char c = (char) System.in.read(); if (c == ENTER_CHAR) { begin = System.currentTimeMillis(); System.out.println("重启tomcat..."); tomcat.stop(); tomcat.start(); end = System.currentTimeMillis(); log(end - begin); } } } catch (Exception e) { System.err.println("非常抱歉,貌似启动挂了...,请联系bohr"); e.printStackTrace(); } } private void configTomcat(final Tomcat tomcat) throws ServletException { //设置tomcat工作目录,maven工程里面就放到target目录下,看起来爽点,注意,这行代码不要随便移动位置,不然你可以have a try。 tomcat.setBaseDir("target"); tomcat.setPort(port); Connector connector = new Connector("HTTP/1.1"); connector.setPort(port); connector.setURIEncoding("utf-8"); tomcat.setConnector(connector); tomcat.getService().addConnector(connector); String webappPath = getWebappsPath(); System.out.println("webapp目录:" + webappPath); Context ctx = tomcat.addWebapp("/", webappPath); StandardJarScanner scanner = (StandardJarScanner) ctx.getJarScanner(); if (!isServlet3Enable) { scanner.setScanAllDirectories(false); scanner.setScanClassPath(false); } tomcat.setSilent(true); System.setProperty("org.apache.catalina.SESSION_COOKIE_NAME", "JSESSIONID" + port); } private void log(long time) { System.out.println("********************************************************"); System.out.println("启动成功: http://127.0.0.1:" + port + " in:" + time + "ms"); System.out.println("您可以直接在console里敲回车,重启tomcat,just have a try"); System.out.println("********************************************************"); } public String getWebappsPath() { String file = getClass().getClassLoader().getResource(".").getFile(); return file.substring(1, file.indexOf("target")) + "src/main/webapp"; } }
使用 mybatis 需要在web.xml中加入文件配置 路径
<!--指定文件加载路径 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath*:spring/*.xml </param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener </listener-class> </listener>
在pom.xml 加入mybatis依赖包 注:在上面的pom.xml 已引入
<!-- mybatis 依赖包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.1</version> </dependency> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency>
在src/main/resources下创建文件夹 spring 在spring 下创建 spring-mybatis.xml文件
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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" 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.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd "> <!-- 获取数据库地址 --> <!-- <context:property-placeholder location="classpath*:spring/userHome-dev.properties" /> --> <!-- JNDI方式配置数据源 --> <!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="${jndiName}"></property> </bean> --> <!-- ========================================配置数据源========================================= --> <!-- 配置数据源,使用的是alibaba的Druid(德鲁伊)数据源 --> <!-- 配置数据源--> <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="jdbc:mysql://127.0.0.1:3306/user" /> <property name="username" value="root" /> <property name="password" value="123456" /> <!-- 初始化连接大小 --> <property name="initialSize" value="1" /> <!-- 连接池最大使用连接数量 --> <property name="maxActive" value="20" /> <!-- 连接池最小空闲 --> <property name="minIdle" value="0" /> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="60000" /> <!-- <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="33" /> --> <property name="validationQuery" value="SELECT 1" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <property name="testWhileIdle" value="true" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="25200000" /> <!-- 打开removeAbandoned功能 --> <property name="removeAbandoned" value="true" /> <!-- 1800秒,也就是30分钟 --> <property name="removeAbandonedTimeout" value="1800" /> <!-- 关闭abanded连接时输出错误日志 --> <property name="logAbandoned" value="true" /> <!-- 监控数据库 --> <!-- <property name="filters" value="stat" /> --> <property name="filters" value="mergeStat" /> </bean> <!-- ========================================分隔线========================================= --> <!-- ========================================针对myBatis的配置项============================== --> <!-- 配置sqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 实例化sqlSessionFactory时需要使用上述配置好的数据源以及SQL映射文件 --> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描me/gacl/mapping/目录下的所有SQL映射的xml文件, 省掉Configuration.xml里的手工配置 value="classpath:me/gacl/mapping/*.xml"指的是classpath(类路径)下me.gacl.mapping包中的所有xml文件 UserMapper.xml位于me.gacl.mapping包下,这样UserMapper.xml就可以被自动扫描 --> <property name="mapperLocations" value="classpath:mybatis/xml/*.xml" /> <property name="plugins"> <array> <!-- 配置分页插件 --> <bean class="com.github.pagehelper.PageHelper"> <property name="properties"> <value> dialect=mysql pageSizeZero=true rowBoundsWithCount=true offsetAsPageNum=true reasonable=true </value> </property> </bean> </array> </property> </bean> <!-- 配置扫描器 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 扫描me.gacl.dao这个包以及它的子包下的所有映射接口类 --> <property name="basePackage" value="com.xyz.dal.mybatis.maps" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans>
在src/main/resources下创建文件generatorConfig.xml 注:generatorConfig文件中需要
mysql-connector-java文件路径
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> <classPathEntry location="d:\mysql-connector-java-5.1.31.jar" /> <context id="easyexchange" targetRuntime="MyBatis3"> <property name="javaFileEncoding" value="utf-8" /> <plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin> <plugin type="org.mybatis.generator.plugins.ToStringPlugin"></plugin> <plugin type="org.mybatis.generator.plugins.RowBoundsPlugin"></plugin> <plugin type="com.xyz.dal.mybatis.plugin.CustomModelPlugin"></plugin> <!-- 关闭注解信息 --> <commentGenerator> <property name="suppressAllComments" value="false" /> </commentGenerator> <!-- connectionURL="jdbc:mysql://localhost:3306/xyz_councli?characterEncoding=UTF8" --> <!-- userId="root" password="admin"> --> <!-- 连数据库地址 用户名 密码 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/xyz_easyhome?characterEncoding=UTF8" userId="root" password="123456"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- 注意修改你的项目文件路径 --> <javaModelGenerator targetPackage="com.xyz.dal.mybatis.model" targetProject="你的项目名称\src\main\java"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- 注意修改你的项目文件路径 --> <sqlMapGenerator targetPackage="mybatis.xml" targetProject="你的项目名称\src\main\resources"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- 注意修改你的项目文件路径 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.xyz.dal.mybatis.maps" targetProject="你的项目名称\src\main\java"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- 数据库对应表名 --> <!--设置为一般模式 表名 取消生成例子 --> <table schema="general" tableName="user_info"> <generatedKey column="id" sqlStatement="SELECT UUID()" /> <!-- <ignoreColumn column="row_update_time" /> --> </table> </context> </generatorConfiguration>
这里是自定义获取数据库注释 需要的可自行创建 不需要的在generatorConfig.xml 文件中注销
在generatorConfig.xml文件中<plugin type="com.xyz.dal.mybatis.plugin.CustomModelPlugin"></plugin>
package com.xyz.easyhome.dal.mybatis.plugin; import org.mybatis.generator.api.IntrospectedColumn; import org.mybatis.generator.api.IntrospectedTable; import org.mybatis.generator.api.PluginAdapter; import org.mybatis.generator.api.dom.java.Field; import org.mybatis.generator.api.dom.java.Method; import org.mybatis.generator.api.dom.java.TopLevelClass; import java.util.List; public class CustomModelPlugin extends PluginAdapter{ public boolean validate(List<String> arg0) { return true; } @Override public boolean modelFieldGenerated(Field field, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) { List<String> doclist = field.getJavaDocLines(); doclist.clear(); doclist.add("/**"); doclist.add(" * "+introspectedColumn.getRemarks()); doclist.add(" * @mbggenerated"); doclist.add(" */"); return true; } @Override public boolean modelGetterMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) { List<String> doclist = method.getJavaDocLines(); doclist.clear(); doclist.add("/**"); doclist.add(" * "+introspectedColumn.getRemarks()); doclist.add(" * @mbggenerated"); doclist.add(" */"); return true; } @Override public boolean modelSetterMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) { List<String> doclist = method.getJavaDocLines(); String paranName = method.getParameters().get(0).getName(); doclist.clear(); doclist.add("/**"); doclist.add(" * "+introspectedColumn.getRemarks()); doclist.add(" * @param "+paranName+" "+introspectedColumn.getRemarks()); doclist.add(" * @mbggenerated"); doclist.add(" */"); return true; } }