码迷,mamicode.com
首页 > 编程语言 > 详细

SSM(springmvc+spring+mybatis)基本框架搭建

时间:2015-03-18 23:02:46      阅读:478      评论:0      收藏:0      [点我收藏+]

标签:

此配置基于3.2版本搭建

此配置不详细解释底层,需要研究自行百度,末尾提供源码包

实际上我采用mybatis的原因在于,对于新手而已,我觉得他容易上手很多。

首先xml配置文件主要有3个,另外两个properties配置文件(log4j打印sql到控制台,方便进行调试,mysql.properties文件则是配置的数据库的一些链接参数),文件全放于src下面即可

技术分享

log4j.properties(作用:sql打印到控制台):

log4j.rootLogger=DEBUG, Console  
  
#Console  
log4j.appender.Console=org.apache.log4j.ConsoleAppender  
log4j.appender.Console.layout=org.apache.log4j.PatternLayout  
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n  
  
log4j.logger.java.sql.ResultSet=INFO  
log4j.logger.org.apache=INFO  
log4j.logger.java.sql.Connection=DEBUG  
log4j.logger.java.sql.Statement=DEBUG  
log4j.logger.java.sql.PreparedStatement=DEBUG

 

mysql.properties(注意validationQuery参数,有些不同的数据库是不一样的)

#driverClassName=com.mysql.jdbc.Driver
#在配置数据库连接池的时候,有一个选项validationQuery,该选项用来验证数据库连接的有效性
validationQuery=SELECT 1
jdbc_url=jdbc:mysql://localhost:3306/boke?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
jdbc_username=root
jdbc_password=123456

 

spring-mvc.xml(对于web.xml如果配置了springmvc拦截全部的话,需要设置静态资源访问权限)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" 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/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">

    <!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 -->
    <context:component-scan base-package="com.bk.controller" />

    <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp" />


    
    
</beans>

 

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" 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
">

    <!-- 配置数据源 -->
    <bean name="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="0" />
        <!-- 连接池最大使用连接数量 -->
        <property name="maxActive" value="20" />
        <!-- 连接池最大空闲 -->
        <property name="maxIdle" 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="${validationQuery}" />
        <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文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 -->
        <property name="mapperLocations" value="classpath:com/bky/mapping/*.xml" />
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.bky.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" /> -->
 
    <!-- 拦截器方式配置事物 -->
    <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="append*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="modify*" propagation="REQUIRED" />
            <tx:method name="edit*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="remove*" propagation="REQUIRED" />
            <tx:method name="repair" propagation="REQUIRED" />
            <tx:method name="delAndRepair" propagation="REQUIRED" />

            <tx:method name="get*" propagation="SUPPORTS" />
            <tx:method name="find*" propagation="SUPPORTS" />
            <tx:method name="load*" propagation="SUPPORTS" />
            <tx:method name="search*" propagation="SUPPORTS" />
            <tx:method name="datagrid*" propagation="SUPPORTS" />

            <tx:method name="*" propagation="SUPPORTS" />
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut id="transactionPointcut" expression="execution(* com.bky.service..*Impl.*(..))" />
        <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />
    </aop:config>


    <!-- 配置druid监控spring jdbc -->
    <bean id="druid-stat-interceptor" class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor">
    </bean>
    <bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut" scope="prototype">
        <property name="patterns">
            <list>
                <value>com.bky.service.*</value>
            </list>
        </property>
    </bean>
    
    <aop:config>
        <aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut" />
    </aop:config>
</beans>

 

spring.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" 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
">
    <!-- 引入属性文件 -->
    <context:property-placeholder location="classpath:config.properties" />
    <!-- 自动扫描(自动注入) -->
    <context:component-scan base-package="com.bky.service..*" />


</beans>

 

 

web.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
    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">
  <display-name></display-name>
  <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring.xml;classpath:spring-mybatis.xml</param-value>
  </context-param>
  
  <filter>
    <description>字符集过滤器</description>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <description>字符集编码</description>
      <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>
  
  <listener>
    <description>spring监听器</description>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <listener>
    <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
  </listener>
  <servlet>
    <description>spring mvc servlet</description>
    <servlet-name>springMvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <description>spring mvc 配置文件</description>
      <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>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <session-config>
    <session-timeout>15</session-timeout>
  </session-config>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 

实例测试:

技术分享

bean:

AdminUser.java

package com.bk.bean;

/**
 * 
 * @author Administrator
 *  登录用户表
 */
public class AdminUser {
    
    //主键id
    private int id;
    
    //登录用户名
    private String loginName;
    
    //登录密码
    private String loginPassword;
    
    //名字
    private String name;
    
    //Integer有空值判断,年龄
    private Integer age;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getLoginName() {
        return loginName;
    }

    public void setLoginName(String loginName) {
        this.loginName = loginName == null ? null : loginName.trim();
        
    }

    public String getLoginPassword() {
        return loginPassword;
    }

    public void setLoginPassword(String loginPassword) {
        this.loginPassword = loginPassword == null ? null : loginPassword.trim();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
    
    
    
    

}

 

其次顺序是dao

AdminUserMapper.java

package com.bk.dao;

import java.util.List;

import com.bk.bean.AdminUser;

/**
 * 
 * @author Administrator
 * 登录用户mapper,实际上是与项目中mapping包中xml文件中的id一一对应
 */
public interface AdminUserMapper {
    
    
    AdminUser selectById(int id);
    
    AdminUser selectByIdOrLoginName(AdminUser adminUser);
    
    int deleteById(int id);
    
     int insert(AdminUser adminUser);
     
     int insert2(AdminUser adminUser);
     
     int updateById(AdminUser adminUser);
     
     List<AdminUser> getAll();

}

 

其次顺序是mapping

由这里的配置,其实可以看出MyBatis的优势是MyBatis可以进行更为细致的SQL优化,可以减少查询字段,并且容易掌握。

AdminUserMapper.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.bk.dao.AdminUserMapper" >
  <resultMap id="BaseResultMap" type="com.bk.bean.AdminUser" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="loginName" property="loginName" jdbcType="VARCHAR" />
    <result column="loginPassword" property="loginPassword" jdbcType="VARCHAR" />
     <result column="name" property="name" jdbcType="VARCHAR" />
     <result column="age" property="age" jdbcType="INTEGER" />
  </resultMap>  
  <!-- 配置基础sql字段 -->
  <sql id="Base_Column_List" >
    id, loginName, loginPassword,name,age
  </sql>
  
  <!-- 单条记录查询 -->
    <select id="selectById" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from admin_user
    where id = #{id,jdbcType=INTEGER}
  </select>
  
  <!-- 多条记录查询 -->
  <select id="selectByIdOrLoginName" resultMap="BaseResultMap" parameterType="com.bk.bean.AdminUser" >
    select 
    <include refid="Base_Column_List" />
    from admin_user
    where
    <if test="id != 0" >
       id = #{id,jdbcType=INTEGER}
     </if>
       <if test="loginName != null" >
       loginName = #{loginName,jdbcType=VARCHAR}
     </if>
   
  </select>
  
  
  <!-- 删除 -->
  <delete id="deleteById" parameterType="java.lang.Integer" >
    delete from admin_user
    where id = #{id,jdbcType=INTEGER}
  </delete>
  
  
  <insert id="insert" parameterType="com.bk.bean.AdminUser" >
    insert into admin_user ( loginName, loginPassword,name,age
      )
    values (#{loginName,jdbcType=VARCHAR}, #{loginPassword,jdbcType=VARCHAR},
     #{name,jdbcType=VARCHAR},#{age,jdbcType=INTEGER}
      )
     
  </insert>
  
  <!-- 条件插入方式 -->
  <insert id="insert2" parameterType="com.bk.bean.AdminUser" >
    insert into admin_user
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="loginName != null" >
           loginName,
      </if>
      <if test="loginPassword != null" >
        loginPassword,
      </if>
      <if test="name != null" >
        name,
      </if>
       <if test="age != null" >
        age,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="loginName != null" >
        #{loginName,jdbcType=VARCHAR},
      </if>
      <if test="loginPassword != null" >
        #{loginPassword,jdbcType=VARCHAR},
      </if>
      <if test="name != null" >
        #{name,jdbcType=VARCHAR},
      </if>
       <if test="age != null" >
        #{age,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  
 

  
  <update id="updateById" parameterType="com.bk.bean.AdminUser" >
    update admin_user
    <set >
      <if test="loginPassword != null" >
        loginPassword = #{loginPassword,jdbcType=VARCHAR},
      </if>
      <if test="name != null" >
        name = #{name,jdbcType=VARCHAR},
      </if>
       <if test="age != null" >
        age = #{age,jdbcType=INTEGER},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
 
  
 <select id="getAll" resultMap="BaseResultMap">
      SELECT * FROM admin_user
  </select>
</mapper>

其次顺序是service

AdminUserService.java

package com.bk.service;

import java.util.List;

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

import com.bk.bean.AdminUser;
import com.bk.dao.AdminUserMapper;


@Service("adminUserService")
public class AdminUserService {
    
    @Autowired
    public AdminUserMapper adminUserMapper;
    
    /**
     * 
     * @return 返回所有数据
     */
    public List<AdminUser> getAll() {
        return adminUserMapper.getAll();
    }
    
    /**
     * 
     * @param id 主键id
     * @return 返回该条数据
     */
    public AdminUser getById(Integer id){
        return adminUserMapper.selectById(id);
    }
    
    /**
     * 
     * @param adminUser (对象赋值loginName或者 id )
     * @return 返回该条查询数据
     */
    public AdminUser selectByIdOrLoginName(AdminUser adminUser){
        return adminUserMapper.selectByIdOrLoginName(adminUser);
    }
    
    
    /**
     * 固定参数传值
     * @param adminUser(必须传入loginName,loginPassword ,name ,age)
     * @return 返回1则表示插入成功
     */
    public int insert(AdminUser adminUser){
        return adminUserMapper.insert(adminUser);
    }
    
    
    /**
     *  如果参数值不为空就插入,直插入不为null的值
     * @param adminUser
     * @return 返回1则表示插入成功
     */
    
    public int insert2(AdminUser adminUser){
        return adminUserMapper.insert2(adminUser);
    }
    
    
    /**
     * 
     * @param id
     * @return 回1则表示删除成功
     */
    public int delete(Integer id){
        return adminUserMapper.deleteById(id);
    }
    
    /**
     * 
     * @param adminUser
     * @return 返回1表示更改成功
     */
    public int update(AdminUser adminUser){
        return adminUserMapper.updateById(adminUser);
    }

}

controller(其实理解为servlet就好)

TestController.java

package com.bk.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.bk.bean.AdminUser;
import com.bk.service.AdminUserService;



@Controller
public class TestController {
    
    @Autowired                                                
    private AdminUserService  adminUserService;

    @RequestMapping("getAll")
    public String getAdInfoAll(HttpServletRequest request){
        try {            
            List<AdminUser> list = adminUserService.getAll();
            request.setAttribute("adminUserLists", list);
            return "index";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("InfoMessage", "信息载入失败!具体异常信息:" + e.getMessage());
            return "result";
        }
    }
    
    @RequestMapping("modify")
    public String ToModify(Integer id,HttpServletRequest request){
        try{
            AdminUser adminUser  = adminUserService.getById(id);
            request.setAttribute("user", adminUser);
            return "modify";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("InfoMessage", "信息载入失败!具体异常信息:" + e.getMessage());
            return "result";
        }
        
    }
    

    @RequestMapping("modify2")
    public String ToModify2(AdminUser adminUser,HttpServletRequest request){
        try{
            AdminUser adminUser2  = adminUserService.selectByIdOrLoginName(adminUser);
            request.setAttribute("user", adminUser2);
            return "modify";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("InfoMessage", "信息载入失败!具体异常信息:" + e.getMessage());
            return "result";
        }
        
    }
    
    
    @RequestMapping("add")
    public String ToAdd(AdminUser adminUser,HttpServletRequest request){    
        if(adminUser.getLoginName().equals("") && adminUser.getLoginPassword().equals("") &&
                adminUser.getName().equals("") && adminUser.getAge() == null){
            request.setAttribute("InfoMessage", "填写参数不完整");
            return "result";    
        }else{
        try{
            if(adminUserService.insert(adminUser) == 1){
                return "redirect:getAll.do";
            }else{
                request.setAttribute("InfoMessage", "数据插入失败");
                return "result";
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("InfoMessage", "信息载入失败!具体异常信息:" + e.getMessage());
            return "result";
        }
        
        }
    }
    
    
    
    @RequestMapping("add2")
    public String ToAdd2(AdminUser adminUser,HttpServletRequest request){    
        try{
            if(adminUserService.insert2(adminUser) == 1){
                return "redirect:getAll.do";
            }else{
                request.setAttribute("InfoMessage", "数据插入失败");
                return "result";
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("InfoMessage", "信息载入失败!具体异常信息:" + e.getMessage());
            return "result";
        }
        
    }
    
    
    @RequestMapping("del")
    public void  del(Integer id,HttpServletRequest request,HttpServletResponse response){
        
        String result = "{\"result\":\"error\"}";
        if(adminUserService.delete(id)==1){
            result = "{\"result\":\"success\"}";
        }
        PrintWriter out = null;
        response.setContentType("application/json");
        try {
            out = response.getWriter();
            out.write(result);
            
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        
    }
    
    
    
    
    
    @RequestMapping("update")
    public String  ToUpdate(AdminUser adminUser,HttpServletRequest request,HttpServletResponse response){
        try{
            if(adminUserService.update(adminUser) == 1){
                return "redirect:getAll.do";
            }else{
                request.setAttribute("InfoMessage", "数据插入失败");
                return "result";
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("InfoMessage", "信息载入失败!具体异常信息:" + e.getMessage());
            return "result";
        }
        
        
    }
    
    


}

数据库建表语句:

CREATE TABLE `admin_user` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `LoginName` varchar(255) NOT NULL DEFAULT ‘‘ COMMENT ‘登录帐号‘,
  `LoginPassword` varchar(255) NOT NULL DEFAULT ‘‘ COMMENT ‘登录密码‘,
  `Name` varchar(255) NOT NULL DEFAULT ‘‘ COMMENT ‘名字‘,
  `Age` int(11) DEFAULT NULL COMMENT ‘年龄‘,
  PRIMARY KEY (`Id`),
  UNIQUE KEY `LoginName` (`LoginName`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

测试方法:浏览器输入地址,由于web.xml配置了拦截.do 因此实际运行需要在方法后都加上.do

技术分享

技术分享

 

源码包:(jar包我也进行了分离,不需要源码的时候可以单独下)

百度云盘:http://yun.baidu.com/s/1eQeWFaq

SSM(springmvc+spring+mybatis)基本框架搭建

标签:

原文地址:http://www.cnblogs.com/codekey/p/4348695.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!