Mybatis3+Spring4+SpringMVC4 整合

 

 首先在整合这个框架的时候,想想其一般的步骤是怎样的,先有个步骤之后,不至于在后面的搞混了,这样在整合的时候也比较清晰些。

然后我们就细细的一步一步来整合。

1  创建一个Web项目。

    

2  导入Mybatis3、Spring4、SpringMVC4、连接数据库(我使用的数据库是mysql)的jar包。

 我所用的包:

  

 spring-websocket-4.2.0.RELEASE.jar

 

3  创建Mybatis3、Spring4、SpringMVC4、连接数据库的配置文件。

    

 

 

4  配置web.xml 

 

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app version="2.5" 
 3     xmlns="http://java.sun.com/xml/ns/javaee" 
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 5     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
 6     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 7     
 8     <!-- 告知javaEE容器,有哪些内容需要添加到上下文中去 -->
 9     <context-param>
10         <param-name>contextConfigLocation</param-name>
11         <param-value>
12         /WEB-INF/classes/applicationContext.xml,
13         <!-- /WEB-INF/classes/mvc-servlet.xml -->
14         </param-value>
15     </context-param> 
16     
17     
18     <!-- 加载LOG4J -->
19     <context-param>
20         <param-name>log4jConfigLocation</param-name>
21         <param-value>/WEB-INF/log4j.xml</param-value>
22     </context-param>
23     
24     <context-param>
25         <param-name>log4jRefreshInterval</param-name>
26         <param-value>60000</param-value>
27     </context-param>
28     
29     <!-- 动态设置项目的运行路径 -->
30     <context-param>
31         <param-name>webAppRootKey</param-name>
32         <param-value>ssm.root</param-value>
33     </context-param>
34     
35     <!-- 配置静态资源 -->
36     <servlet-mapping>
37         <servlet-name>default</servlet-name>
38         <url-pattern>/static/*</url-pattern>
39     </servlet-mapping>
40     
41     
42     <!-- 配置springmvc的前端控制器 -->
43     <servlet>
44         <servlet-name>mvc</servlet-name>
45         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
46          <!-- 默认情况下:DispatcherServlet会寻找WEB-INF下,命名规范为[servlet-name]-servlet.xml文件。如:在上例中,它就会找/WEB-INF/spring-servlet.xml
47                                                     如果需要修改,需要在web.xml中的<servlet>标记中增加 <init-param>。。。  </init-param>:-->
48     <init-param>
49        <param-name>contextConfigLocation</param-name>
50        <param-value>/WEB-INF/classes/mvc-servlet.xml</param-value>
51     </init-param>
52     </servlet>
53     <servlet-mapping>
54         <servlet-name>mvc</servlet-name>
55         <url-pattern>/</url-pattern>
56     </servlet-mapping>
57     
58     <!-- spring框架提供的字符集过滤器 -->
59     <!-- spring Web MVC框架提供了org.springframework.web.filter.CharacterEncodingFilter用于解决POST方式造成的中文乱码问题  -->
60     <filter>
61         <filter-name>encodingFilter</filter-name>
62         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
63         <init-param>
64             <param-name>encoding</param-name>
65             <param-value>UTF-8</param-value>
66         </init-param>
67         <!-- force强制,促使 -->
68         <init-param>
69             <param-name>forceEncoding</param-name>
70             <param-value>true</param-value>
71         </init-param>
72     </filter>
73     <filter-mapping>
74         <filter-name>encodingFilter</filter-name>
75         <url-pattern>/*</url-pattern>
76     </filter-mapping>
77     
78     <!-- 登录过滤器-->
79     <filter>
80         <filter-name>loginFilter</filter-name>
81         <filter-class>com.cy.ssm.filter.LoginFilter</filter-class>
82     </filter>
83     <filter-mapping>
84         <filter-name>loginFilter</filter-name>
85         <url-pattern>/*</url-pattern>
86     </filter-mapping>
87     <!-- 监听器 -->
88     <listener>
89         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
90     </listener>
91     
92     <listener>
93         <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
94     </listener>
95     
96   <welcome-file-list>
97     <welcome-file>index.jsp</welcome-file>
98   </welcome-file-list>
99 </web-app>

 

 

5 datasource.properties 连接数据库

1 jdbc.driver=com.mysql.jdbc.Driver
2 jdbc.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8
3 jdbc.username=root
4 jdbc.password=root

 

6 mybatis.cfg.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>
    
</configuration>

 

7  mvc-servlet.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 4     xmlns:mvc="http://www.springframework.org/schema/mvc"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans
 6 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 7 http://www.springframework.org/schema/context   http://www.springframework.org/schema/context/spring-context-3.0.xsd
 8 http://www.springframework.org/schema/mvc   
 9 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
10 
11     <!-- 启动注解,注册服务,如验证框架、全局类型转换器-->
12     <mvc:annotation-driven/>
13     
14     
15     <!-- 启动自动扫描 -->
16     <context:component-scan base-package="com.cy.ssm">
17     <!-- 制定扫包规则 ,只扫描使用@Controller注解的JAVA类 -->
18         <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
19     </context:component-scan>
20     
21     
22     <!-- 配置视图解析器 -->
23     <!--
24        prefix和suffix:查找视图页面的前缀和后缀(前缀[逻辑视图名]后缀),
25        比如传进来的逻辑视图名为WEB-INF/jsp/hello,则该该jsp视图页面应该存放在“WEB-INF/jsp/hello.jsp”; -->
26     <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
27         <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
28         <property name="prefix" value="/"></property> <!-- 我这里的视图直接放在WebRoot下的 -->
29         <property name="suffix" value=".jsp"></property>
30     </bean>
31 </beans>

 

 8 applicationContext.xml

  

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 4     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans
 6     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
 7     http://www.springframework.org/schema/aop 
 8     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
 9     http://www.springframework.org/schema/tx
10     http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
11     http://www.springframework.org/schema/context
12     http://www.springframework.org/schema/context/spring-context-4.2.xsd">
13     
14     
15      <!-- 开启自动扫包 -->
16      <context:component-scan base-package="com.cy.ssm">
17        <!--制定扫包规则,不扫描@Controller注解的JAVA类,其他的还是要扫描  -->
18          <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
19      </context:component-scan>
20     
21     <!-- 启动AOP支持 -->
22     <aop:aspectj-autoproxy/>
23     
24     <!-- 引入外部数据源配置信息 -->
25     <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
26         <property name="locations">
27             <value>classpath:datasource.properties</value>
28         </property>
29     </bean>
30     
31     <!-- 配置数据源 -->
32     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
33         <property name="driverClassName" value="${jdbc.driver}"></property>
34         <property name="url" value="${jdbc.url}"></property>
35         <property name="username" value="${jdbc.username}"></property>
36         <property name="password" value="${jdbc.password}"></property>
37     </bean>
38     
39     
40     <!-- 配置Session工厂 -->
41     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
42         <property name="dataSource" ref="dataSource"></property>
43         <!-- 加载mybatis.cfg.xml文件 -->
44         <property name="configLocation" value="classpath:mybatis.cfg.xml"></property>
45         <!-- 自动扫描需要定义类别名的包,将包内的JAVA类的类名作为类别名 -->
46         <property name="typeAliasesPackage" value="com.cy.ssm.beans"></property>
47     </bean>
48     
49     <!-- 自动扫描所有的Mapper接口与文件 -->
50     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
51         <property name="basePackage" value="com.cy.ssm.mapper"></property>
52     </bean>
53     
54     <!-- 配置事务管理器 -->
55     <bean id="txManager"
56         class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
57         <property name="dataSource" ref="dataSource"></property>
58     </bean>
59     
60     <!-- 定义个通知,指定事务管理器 -->
61     <tx:advice id="txAdvice" transaction-manager="txManager">
62         <tx:attributes>
63             <tx:method name="delete*" propagation="REQUIRED" read-only="false"
64                 rollback-for="java.lang.Exception" />
65             <tx:method name="save*" propagation="REQUIRED" read-only="false"
66                 rollback-for="java.lang.Exception" />
67             <tx:method name="insert*" propagation="REQUIRED" read-only="false"
68                 rollback-for="java.lang.Exception" />
69             <tx:method name="update*" propagation="REQUIRED" read-only="false"
70                 rollback-for="java.lang.Exception" />
71             <tx:method name="load*" propagation="SUPPORTS" read-only="true"/>
72             <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
73             <tx:method name="search*" propagation="SUPPORTS" read-only="true"/>
74             <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
75             <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
76         </tx:attributes>
77     </tx:advice>
78     
79     <aop:config>
80         <!-- 配置一个切入点 -->
81         <aop:pointcut id="serviceMethods" expression="execution(* com.cy.ssm.service.impl.*ServiceImpl.*(..))" />
82         <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods" />
83     </aop:config>
84     
85 </beans>

 

 

 9  配置文件都差不多配置好了,接下来就写个测试的。

 

 UserBean.java

 1 package com.cy.ssm.beans;
 2 
 3 import java.io.Serializable;
 4 
 5 public class UserBean implements Serializable {
 6 
 7     
 8     private static final long serialVersionUID = -2682305557890221059L;
 9     private Integer id;
10     private String username;
11     private String password;
12     private Double account;
13     public UserBean() {
14         super();
15         // TODO Auto-generated constructor stub
16     }
17     public UserBean(Integer id, String username, String password, Double account) {
18         super();
19         this.id = id;
20         this.username = username;
21         this.password = password;
22         this.account = account;
23     }
24     public Integer getId() {
25         return id;
26     }
27     public void setId(Integer id) {
28         this.id = id;
29     }
30     
31     public String getUsername() {
32         return username;
33     }
34     public void setUsername(String username) {
35         this.username = username;
36     }
37     public String getPassword() {
38         return password;
39     }
40     public void setPassword(String password) {
41         this.password = password;
42     }
43     public Double getAccount() {
44         return account;
45     }
46     public void setAccount(Double account) {
47         this.account = account;
48     }
49     @Override
50     public String toString() {
51         return "UserBean [account=" + account + ", id=" + id + ", password="
52                 + password + ", username=" + username + "]";
53     }
54 }
View Code

 

 

 UserMapper.java

  1 package com.cy.ssm.mapper;
  2 
  3 import java.util.List;
  4 import java.util.Map;
  5 
  6 
  7 import org.apache.ibatis.annotations.Delete;
  8 import org.apache.ibatis.annotations.Insert;
  9 import org.apache.ibatis.annotations.Options;
 10 import org.apache.ibatis.annotations.Param;
 11 import org.apache.ibatis.annotations.Result;
 12 import org.apache.ibatis.annotations.ResultMap;
 13 import org.apache.ibatis.annotations.Results;
 14 import org.apache.ibatis.annotations.Select;
 15 import org.apache.ibatis.annotations.Update;
 16 
 17 import com.cy.ssm.beans.UserBean;
 18 
 19 
 20 public interface UserMapper {
 21     
 22     
 23     /**
 24      * 登录
 25      * @param userName
 26      * @param password
 27      * @return
 28      * @throws Exception
 29      */
 30     @Select("select * from t_user where username=#{un} and password=#{pw}")
 31     @Results({
 32         
 33         @Result(id=true,property="id",column="id",javaType=Integer.class),
 34         @Result(property="username",column="username",javaType=String.class),
 35         @Result(property="password",column="password",javaType=String.class),
 36         @Result(property="account",column="account",javaType=Double.class)
 37     })
 38     public UserBean login(@Param("un")String username,@Param("pw")String password);
 39     /**
 40      * 新增用戶
 41      * @param user
 42      * @return
 43      * @throws Exception
 44      */
 45     @Insert("insert into t_user value (null,user.username,user.password,user.account)")
 46     @Options(useGeneratedKeys=true,keyProperty="user.id")
 47     public int insertUser(@Param("user")UserBean user) throws Exception;
 48     
 49     
 50     /**
 51      * 修改用戶
 52      * @param user
 53      * @param id
 54      * @return
 55      * @throws Exception
 56      */
 57     @Update(" update t_user set username=#{u.username},password=#{u.password},account=#{u.account} where id=#{id}")
 58     public int updateUser (@Param("u")UserBean user,@Param("id")int id) throws Exception;
 59     
 60      /**
 61       * 刪除用戶
 62       * @param id
 63       * @return
 64       * @throws Exception
 65       */
 66     @Delete(" delete from t_user where id=#{id}  ")
 67     public int deleteUser(int id) throws Exception;
 68     
 69     
 70     /**
 71      * 根据id查询用户信息
 72      * @param id
 73      * @return
 74      * @throws Exception
 75      */
 76     
 77     @Select(" select * from t_user where id=#{id}")
 78     @Results({
 79         
 80         @Result(id=true,property="id",column="id",javaType=Integer.class),
 81         @Result(property="username",column="username",javaType=String.class),
 82         @Result(property="password",column="password",javaType=String.class),
 83         @Result(property="account",column="account",javaType=Double.class)
 84     })
 85     public UserBean selectUserById(int id) throws Exception;
 86      /**
 87       * 查询所有的用户信息
 88       * @return
 89       * @throws Exception
 90       */
 91     
 92     @Select(" select * from t_user")
 93     @ResultMap("userMap")
 94     public List<UserBean> selectAllUser() throws Exception;
 95     
 96     
 97     /**
 98      * 批量增加
 99      * @param user
100      * @return
101      * @throws Exception
102      */
103    public int batchInsertUser(@Param("users")List<UserBean> user) throws Exception;
104    
105    /**
106     * 批量删除
107     * @param list
108     * @return
109     * @throws Exception
110     */
111    public int batchDeleteUser(@Param("list")List<Integer> list) throws Exception;
112    
113    
114    /**
115     * 分页查询数据
116     * @param parma
117     * @return
118     * @throws Exception
119     */
120    public List<UserBean> pagerUser(Map<String, Object> parmas) throws Exception;
121    
122    /**
123     * 
124     * 分页统计数据
125     * @param parma
126     * @return
127     * @throws Exception
128     */
129     public int countUser(Map<String, Object> parmas) throws Exception;
130     
131   
132     
133     
134 }
View Code

 

 

UserMapper.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 3 <mapper namespace="com.cy.ssm.mapper.UserMapper">
 4 <!-- 自定义返回结果集 -->
 5    <resultMap id="userMap" type="UserBean">
 6         <id property="id" column="id" javaType="java.lang.Integer"></id>
 7         <result property="username" column="username" javaType="java.lang.String"></result>
 8         <result property="password" column="password" javaType="java.lang.String"></result>
 9         <result property="account" column="account" javaType="java.lang.Double"></result>
10     </resultMap>
11     
12     <!-- 批量操作和foreach标签 -->
13     
14     <insert id="batchInsertUser" parameterType="java.util.List">
15        insert into t_user values 
16         <foreach collection="users" item="users" separator=",">
17          (null,#{users.username},#{users.password},#{users.account})
18         </foreach>
19     </insert>
20     
21     
22     <delete id="batchDeleteUser">
23        delete from t_user where id in (
24          <foreach collection="list" item="list" separator=",">
25           #{id}
26          </foreach>
27        )
28     </delete>
29     
30     <!--collection 为用于遍历的元素(必选),支持数组、List、Set  -->
31     <!-- item 表示集合中每一个元素进行迭代时的别名. -->
32     <!--separator表示在每次进行迭代之间以什么符号作为分隔 符.  -->
33     
34     <!--#在生成SQL时,对于字符类型参数,会拼装引号
35          $在生成SQL时,不会拼装引号,可用于order by之类的参数拼装
36       -->
37     <select id="pagerUser" parameterType="java.util.Map" resultMap="userMap">
38       select * from t_user where 1=1
39       <if test="username!=null">
40        and username like '%${username}%'
41       </if>
42        limit ${index},${pageSize} 
43     </select>
44     
45     <select id="countUser" parameterType="java.util.Map" resultType="int">
46         select count(*) from t_user where 1=1 
47         <if test="username != null">
48             and username like '%${username}%'    
49         </if>
50     </select>
51         
52 </mapper>    
View Code

 

 

ILoginService.java

 1 package com.cy.ssm.service;
 2 
 3 
 4 import com.cy.ssm.beans.UserBean;
 5 
 6 public interface ILoginService {
 7 
 8     public UserBean Login(String username,String password);
 9     
10     
11 }
View Code

 

 

LoginServiceImpl.java

 1 package com.cy.ssm.service.impl;
 2 
 3 import javax.annotation.Resource;
 4 
 5 import org.springframework.stereotype.Service;
 6 
 7 import com.cy.ssm.mapper.UserMapper;
 8 import com.cy.ssm.beans.UserBean;
 9 import com.cy.ssm.service.ILoginService;
10 @Service
11 public class LoginServiceImpl implements ILoginService{
12     
13     @Resource
14     private UserMapper um;
15 
16 
17     @Override
18     public UserBean Login(String username, String password) {
19         return um.login(username, password);
20     }
21 
22 }
View Code

 

 

LoginController .java
 1 package com.cy.ssm.controller;
 2 
 3 
 4 import javax.annotation.Resource;
 5 import javax.servlet.http.HttpServletRequest;
 6 
 7 import org.apache.log4j.Logger;
 8 import org.springframework.stereotype.Controller;
 9 import org.springframework.web.bind.annotation.RequestMapping;
10 import org.springframework.web.servlet.ModelAndView;
11 
12 import com.cy.ssm.beans.UserBean;
13 import com.cy.ssm.service.ILoginService;
14 
15 
16 
17 @Controller
18 public class LoginController {
19     private Logger log = Logger.getLogger(this.getClass());
20     
21     @Resource
22     private ILoginService loginServiceImpl;
23     
24     @RequestMapping("/login")
25     public ModelAndView login(HttpServletRequest req,UserBean user){
26         log.info(user);
27         
28         ModelAndView mv = new ModelAndView();
29         UserBean u=loginServiceImpl.Login(user.getUsername(), user.getPassword());
30     
31         if(u != null){
32                     
33             req.getSession().setAttribute("user", u);
34             mv.addObject("password", u.getPassword());
35             System.out.println(u.getPassword());
36         }
37         mv.setViewName("index");
38         return mv;
39     }
40     
41     
42     
43 }

 

 jsp页面;

login.jsp

1  <body>
2     <form action="<%=basePath%>login" method="post">
3         <input type="text" name="username"/>
4         <input type="text" name="password"/>
5         <input type="submit" value="提交"/>
6     </form>

 

 index.jsp

<body>
   ${password }
</body>

 

测试:

点击提交

整体大概就这样了!

 

我把整个文件上传到:http://pan.baidu.com/s/1hrB1guo

继续我的作业了!

 

posted @ 2016-03-01 21:59  NAYNEHC  阅读(51612)  评论(61编辑  收藏  举报