首页 > 代码库 > SpringMVC+Spring+Mybatis+Mysql项目搭建

SpringMVC+Spring+Mybatis+Mysql项目搭建

眼下俺在搭建一个自己的个人站点玩玩。一边练习。一边把用到的技术总结一下,日后好复习。
站点框架大致例如以下图所看到的:
技术分享
眼下仅仅用到了SpringMVC+Spring+Mybatis+Mysql。把它弄到了自己的server上来玩耍。

后台结构图:

技术分享
眼下主要分为:

  • view–controller层与前台交互,登陆拦截器
  • utils–工具类。一些经常使用的工具类。
  • interceptor–拦截器。页面请求地址拦截和预防XSS漏洞拦截。

  • impl–接口类,Service层-进行业务处理。

  • exception–异常处理器。自己定义异常处理,拦截。

  • entity–实体类,存放部分数据库相关实体。
  • dao–与数据库进行交互,获取数据。
  • 眼下缺少一个封装类包。

具体演示样例代码:

  • TestController.java插入和依据ID获取数据
package com.YouXu.view;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.YouXu.entity.Test;
import com.YouXu.impl.TestImpl;
import com.YouXu.utils.IpAddr;

/**
 * 
 * @Title: TestController.java
 * @Package: com.YouXu.view
 * @author you.xu
 * @date 2015年12月21日下午4:38:04
 * @version 1.0
 */
@Controller
public class TestController {

    private static final Logger log = Logger.getLogger(TestController.class);

    @Autowired
    private TestImpl testImpl;

    @RequestMapping("test")
    @ResponseBody
    public Test test(@RequestParam("id") Integer id) {
        Test test = new Test();
        try {
            test = testImpl.getTest(id);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e, e);
        }
        return test;
    }

    @RequestMapping("getIndex")
    @ResponseBody
    public void index(HttpServletRequest request) {
        String iip = null;
        try {
            iip = IpAddr.getIpAddr(request);
        } catch (Exception e) {
            log.error(e, e);
            e.printStackTrace();
        }
        testImpl.addTest(iip);
    }
}
  • TestImpl.java
package com.YouXu.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.YouXu.dao.TestDao;
import com.YouXu.entity.Test;

/**
 * 
 * @Title: TestImpl.java
 * @Package: com.YouXu.impl
 * @author you.xu
 * @date 2015年12月21日下午4:40:46
 * @version 1.0
 */
@Service
public class TestImpl {

    @Autowired
    private TestDao testDao;

    public Test getTest(Integer id) {

        Test test = testDao.getTest(id);
        return test;
    }

    public void addTest(String iip) {
        testDao.addTest(iip);
    }

}
  • TestDao.java
package com.YouXu.dao;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.YouXu.entity.Test;

/**
 * 
 * @Title: TestDao.java
 * @Package: com.YouXu.dao
 * @author you.xu
 * @date 2015年12月21日下午4:40:56
 * @version 1.0
 */
@Repository
public class TestDao extends SqlSessionDaoSupport {

    @Autowired
    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        super.setSqlSessionFactory(sqlSessionFactory);
    }

    String ns = "com.YouXu.sqlMap.TestMapper.";

    public Test getTest(Integer id) {
        Test test = this.getSqlSession().selectOne(ns + "getTestbyId", id);
        return test;
    }

    public void addTest(String iip) {

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = formatter.format(new Date());
        Test test = new Test();
        test.setIip(iip);
        test.setTtime(time);
        this.getSqlSession().insert(ns + "insertTest", test);
    }

}
  • Test.java
package com.YouXu.entity;

/**
 * 
 * @Title: Test.java
 * @Package: com.YouXu.entity
 * @author you.xu
 * @date 2015年12月21日下午4:39:00
 * @version 1.0
 */
public class Test {

    private Integer iid;
    private String iip;
    private String ttime;

    public Integer getIid() {
        return iid;
    }

    public void setIid(Integer iid) {
        this.iid = iid;
    }

    public String getIip() {
        return iip;
    }

    public void setIip(String iip) {
        this.iip = iip;
    }

    public String getTtime() {
        return ttime;
    }

    public void setTtime(String ttime) {
        this.ttime = ttime;
    }

    public String toString() {
        return "Test [iid=" + iid + ", iip=" + iip + ", ttime=" + ttime + "]";
    }

    public Test(Integer iid, String iip, String ttime) {
        super();
        this.iid = iid;
        this.iip = iip;
        this.ttime = ttime;
    }

    public Test() {
        super();
    }

}

配置文件配置:
技术分享

  • springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
    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-3.0.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-3.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-2.5.xsd 
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    <context:annotation-config />
    <mvc:annotation-driven />
    <aop:aspectj-autoproxy />
    <context:component-scan base-package="com.YouXu" />

    <!-- 配置过滤静态文件 -->
    <mvc:resources mapping="/images/**" location="/WEB-INF/images/" />
    <mvc:resources mapping="/css/**" location="/WEB-INF/css/" />
    <mvc:resources mapping="/js/**" location="/WEB-INF/js/" />
    <mvc:resources mapping="/audio/**" location="/WEB-INF/audio/" />
    <mvc:resources mapping="/fonts/**" location="/WEB-INF/fonts/" />
    <mvc:resources mapping="/**" location="/index.html" />
    <!-- 启动JSON格式的配置 -->
    <bean id="jacksonMessageConverter"
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <!-- 解决 HttpMediaTypeNotAcceptableException: Could not find acceptable 
            representation -->
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    <!-- 上传文件时须要这一段代码 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="104857600" />
        <property name="maxInMemorySize" value="4096" />
    </bean>
    <!-- 定义统一异常处理器 -->
    <bean class="com.YouXu.exception.CustomExceptionResolver"></bean>

    <!-- 注解处理器映射器 -->
    <bean
        class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
    </bean>
    <!-- 注解适配器 -->
    <bean
        class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    </bean>

    <!-- 返回视图 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

<!-- 配置有须要登录的请求进行拦截 -->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/login/*" />
            <bean class="com.YouXu.view.LoginInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>
</beans> 
  • applicationContext.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:aop="http://www.springframework.org/schema/aop" 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.0.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-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">

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://************:3306/******" />
        <property name="username" value="****" />
        <property name="password" value="****" />
        <property name="maxActive" value="10" />
        <property name="maxIdle" value="5" />
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:sqlMapConfig.xml"></property>
    </bean>
    <bean id="txManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <tx:advice id="txAdive" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="get*" read-only="true" />
        </tx:attributes>
    </tx:advice>

    <aop:config>
        <aop:advisor advice-ref="txAdive"
            pointcut="execution(* com.YouXu.impl..*.*(..))" />
    </aop:config>
</beans>
  • sqlMapConfig.xml
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <mappers>
        <mapper resource="com/YouXu/sqlMap/TestMapper.xml" />
    </mappers>
</configuration>
  • log4j.properties
# 设定logger的root level为INFO,指定的输出目的地(appender)为file,并在控制台输出stdout(Console)
log4j.rootLogger=info, file, stdout
# 设定stdout控制台 
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%d{HH\:mm\:ss}] %5p %F\:%L "%m"%n
# 设定输出位置。此处设定tomcat文件夹的logs下,文件名称为projectLogs.log。 
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.append = true
log4j.appender.file.encoding=UTF-8
log4j.appender.file.File=${catalina.home}/logs/youxu.log
log4j.appender.file.datePattern=‘.‘yyyy-MM-dd
log4j.appender.file.BufferedIO=true
log4j.appender.file.BufferSize=8192
# 设定制定的file使用的PatternLayout. 
# 有关ConversionPattern中的转意字符的含义參考说明 
log4j.appender.file.layout=org.apache.log4j.PatternLayout 
log4j.appender.file.layout.ConversionPattern=%d{yyyy/MM/dd HH:mm:ss} %-5p [%C:%M:%L] %m%n
  • TestMapper.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="com.YouXu.sqlMap.TestMapper"> <resultMap id="BaseResultMap" type="com.YouXu.entity.Test"> <id column="iid" property="iid" /> <result column="iip" property="iip" /> <result column="ttime" property="ttime" /> </resultMap> <sql id="Base_Column_List"> iid,iip,ttime </sql> <select id="getTestbyId" parameterType="Integer" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from Test where iid = #{iid} </select> <insert id="insertTest" parameterType="com.YouXu.entity.Test"> <selectKey keyProperty="iid" order="AFTER" resultType="java.lang.Integer"> select LAST_INSERT_ID() </selectKey> insert into test(iid,iip,ttime) values(null,#{iip},#{ttime}) </insert> </mapper>

  • web.xml
<?

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_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>YouXu</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/classes/applicationContext.xml</param-value> </context-param> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/classes/log4j.properties</param-value> </context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>60000</param-value> </context-param> <!-- 配置spring容器监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <filter> <filter-name>XSSFilter</filter-name> <filter-class>com.YouXu.interceptor.XSSFilter</filter-class> </filter> <filter-mapping> <filter-name>XSSFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 前端控制器 --> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 载入spring配置 --> <init-param> <param-name>contextConfigLocation</param-name> <!-- 配置文件的地址 假设不配置contextConfigLocation, 默认查找的配置文件名称称classpath下的:servlet名称+"-serlvet.xml"即:springmvc-serlvet.xml --> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <!-- 能够配置/ 。此工程 全部请求全部由springmvc解析,此种方式能够实现 RESTful方式,须要特殊处理对静态文件的解析不能由springmvc解析 能够配置*.do或*.action,全部请求的url扩展名为.do或.action由springmvc解析,此种方法经常使用 不能够/*,假设配置/*,返回jsp也由springmvc解析,这是不正确的。 --> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 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> <error-page> <error-code>404</error-code> <location>/404.jsp</location> </error-page> <error-page> <error-code>500</error-code> <location>/error.jsp</location> </error-page> <session-config> <session-timeout>15</session-timeout> </session-config> <welcome-file-list> <welcome-file>index-h5.html</welcome-file> </welcome-file-list> </web-app>

所需用到的lib包:点击此处

眼下应该就是这些。日后有补充的在进行加入。

我是一个小菜鸟,大家如有更简单高效的配置搭建。欢迎在评论中指出,一起分享。谢谢

<script type="text/javascript"> $(function () { $(‘pre.prettyprint code‘).each(function () { var lines = $(this).text().split(‘\n‘).length; var $numbering = $(‘
    ‘).addClass(‘pre-numbering‘).hide(); $(this).addClass(‘has-numbering‘).parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($(‘
  • ‘).text(i)); }; $numbering.fadeIn(1700); }); }); </script>

SpringMVC+Spring+Mybatis+Mysql项目搭建