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

Spring、SpringMVC、MyBatis整合

时间:2018-03-27 15:24:34      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:ping   社区   ssi   libs   框架   查询   label   htm   version   

项目结构:

技术分享图片

一、准备所需jar包
1. Spring框架的jar包
  spring-framework-5.0.4.RELEASE文件夹下libs目录下的所有jar包
  Spring的核心容器必须依赖的common-logging的jar包,这里使用的是commons-logging-1.2.jar
2. MyBatis框架的jar包
  mybatis-3.4.6.jar和lib文件夹下的所有jar包
3. MyBatis整合Spring中间件jar包
  该中间件有两个作用:
  (1)在Spring中配置MyBatis工厂类
  (2)在DAO层使用Spring注入的工具Bean对数据进行操作。
  这里使用的是commons-logging-1
4. Spring的AOP事务jar包
5. aspect框架的jar包
  aspectjrt.jar 、 aspectjrtools.jar 、aspectjweaver.jar 、 org.aspectj.matcher.jar
6. aop联盟jar包
  org.aspectj.matcher.jar
7. 数据库驱动jar包
  mysql-connector-java-5.1.46-bin.jar
8. 数据源c3p0所需jar包
  c3p0-0.9.5.2.jar、hibernate-c3p0-5.2.10.Final.jar、mchange-commons-java-0.2.14.jar
9. JSTL标签库jar包
  javax.servlet.jsp.jstl-1.2.1.jar、 javax.servlet.jsp.jstl-api-1.2.1.jar
以上jar包可在CSDN直接下载:https://download.csdn.net/download/sinat_14910693/10311298

二、数据库创建

技术分享图片

 

三、配置文件
1. 在src下新建db.properties

dataSource.driverClass=com.mysql.jdbc.Driver
dataSource.jdbcUrl=jdbc:mysql://localhost:3306/login
dataSource.user=root
dataSource.password=root

2. 在WEB-INF下新建applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
    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"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
                        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-4.2.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
                        http://www.springframework.org/schema/tx
                        http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
                        http://mybatis.org/schema/mybatis-spring 
                        http://mybatis.org/schema/mybatis-spring.xsd ">
                  
     <!-- mybatis:scan会将com.game.mapper包里的所有接口当作mapper配置,之后可以自动引入mapper类-->  
    <mybatis:scan base-package="com.game.mapper"/>   
       
     <!-- 扫描com.game包下面的java文件,有Spring的相关注解的类,则把这些类注册为Spring的bean -->
    <context:component-scan base-package="com.game"/>
    
    <!-- 使用PropertyOverrideConfigurer后处理器加载数据源参数 -->
    <context:property-override location="classpath:db.properties"/>

    <!-- 配置c3p0数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"/>
    
    <!-- 配置SqlSessionFactory,org.mybatis.spring.SqlSessionFactoryBean是Mybatis社区开发用于整合Spring的bean -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
        p:dataSource-ref="dataSource"/>
    
    <!-- JDBC事务管理器 -->
    <bean id="transactionManager" 
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
         p:dataSource-ref="dataSource"/>
    
    <!-- 启用支持annotation注解方式事务管理 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
    
</beans>

3. 在WEB-INF下新建springmvc-config.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-4.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd     
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.2.xsd">
        
    <!-- 自动扫描该包,SpringMVC会将包下用了@controller注解的类注册为Spring的controller -->
    <context:component-scan base-package="com.game.controller"/>
    <!-- 设置默认配置方案 -->
    <mvc:annotation-driven/>
    <!-- 使用默认的Servlet来响应静态文件 -->
    <mvc:default-servlet-handler/>
    <!-- 视图解析器  -->
     <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
        <!-- 前缀 -->
        <property name="prefix">
            <value>/WEB-INF/content/</value>
        </property>
        <!-- 后缀 -->
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
    
</beans>

4. 在WEB-INF下新建web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
    http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" 
    id="WebApp_ID" version="3.1">
    
    <!-- 配置spring核心监听器,默认会以 /WEB-INF/applicationContext.xml作为配置文件 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- contextConfigLocation参数用来指定Spring的配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext*.xml</param-value>
    </context-param>
    
    <!-- 定义Spring MVC的前端控制器 -->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/springmvc-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  
  <!-- 让Spring MVC的前端控制器拦截所有请求 -->
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  
  <!-- 编码过滤器 -->
  <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>
    
</web-app>

5. log4j.properties配置

# Global logging configuration
# developer-->DEBUG  productor-->INFO or ERROR
log4j.rootLogger=DEBUG, stdout
# MyBatis logging configuration...
log4j.logger.com.game.mapper.UserMapper=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

四、持久层实现
1. User.java

public class User {
    private Integer id;
    private String username;
    private Character sex;
    private String address;
    private String loginname;
    private String password;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public Character getSex() {
        return sex;
    }
    public void setSex(Character sex) {
        this.sex = sex;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getLoginname() {
        return loginname;
    }
    public void setLoginname(String loginname) {
        this.loginname = loginname;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

}

2. UserMapper.java

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import com.game.domain.User;

/**
 * UserMapper接口
 * */
public interface UserMapper {
    /**
     * 根据登录名和密码查询用户
     * @param String loginname
     * @param String password
     * @return 找到返回User对象,没有找到返回null
     * */
    @Select("select * from user where loginname = #{loginname} and password = #{password}")
    User findWithLoginnameAndPassword(@Param("loginname")String loginname,
            @Param("password") String password);

}

五、服务层实现
1. UserService.java

import com.game.domain.User;

/**
 * User服务层接口
 * */
public interface UserService {
    /**
     * 判断用户登录
     * @param String loginname
     * @param String password
     * @return 找到返回User对象,没有找到返回null
     * */
    User login(String loginname,String password);

}

2. UserServiceImplement.java

import com.game.domain.User;
import com.game.mapper.UserMapper;
import com.game.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * User服务层接口实现类
 * @Service("userService")用于将当前类注释为一个Spring的bean,名为userService
 * */
@Transactional(propagation=Propagation.REQUIRED,isolation=Isolation.DEFAULT)
@Service("userService")
public class UserServiceImpl implements UserService {

    /**
     * 自动注入UserMapper
     * */
    @Autowired
    private UserMapper userMapper;

    /**
     * UserService接口login方法实现
     * @see { UserService }
     * */
    @Transactional(readOnly=true)
    @Override
    public User login(String loginname, String password) {
        // TODO Auto-generated method stub
        return userMapper.findWithLoginnameAndPassword(loginname, password);
    }

}

六、控制层实现
1. FormController.java

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 动态页面跳转控制器
 * */
@Controller
public class FormController {
    @RequestMapping(value="/{formName}")
     public String loginForm(@PathVariable String formName){
        // 动态跳转页面
        return formName;
    }

}

2. UserController.java

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.game.domain.User;
import com.game.service.UserService;

/**
 * 处理用户请求控制器
 * */
@Controller
public class UserController {
    /**
     * 自动注入UserService
     * */
    @Autowired
    @Qualifier("userService")
    private UserService userService;

    /**
     * 处理/login请求
     * */
    @RequestMapping(value="/login")
     public ModelAndView login(
             String loginname,String password,
             ModelAndView mv,
             HttpSession session){
        // 根据登录名和密码查找用户,判断用户登录
        User user = userService.login(loginname, password);
        if(user != null){
            // 登录成功,将user对象设置到HttpSession作用范围域
            session.setAttribute("user", user);
            // 转发到main请求
            mv.setView(new RedirectView("/SpringDemo/main"));
        }else{
            // 登录失败,设置失败提示信息,并跳转到登录页面
            mv.addObject("message", "登录名或密码错误,请重新输入!");
            mv.setViewName("loginForm");
        }
        return mv;
    }

}

七、jsp页面
1. loginForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登录页面</title>
</head>
<body>
<h3>登录页面</h3>
<form action="login" method="post">
    <font color="red">${requestScope.message }</font>
     <table>
         <tr>
             <td><label>登录名: </label></td>
             <td><input type="text" id="loginname" name="loginname" ></td>
         </tr>
         <tr>
             <td><label>密码: </label></td>
             <td><input type="password" id="password" name="password" ></td>
         </tr>
         <tr>
             <td><input type="submit" value="登录"></td>
         </tr>
     </table>
</form>
</body>
</html>

2. main.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>首页</title>
<style type="text/css">
    table{border-collapse:collapse;border-spacing:0;border-left:1px solid #888;border-top:1px solid #888;background:#efefef;}
    th,td{border-right:1px solid #888;border-bottom:1px solid #888;padding:5px 15px;}
    th{font-weight:bold;background:#ccc;}
</style>
</head>
<body>
欢迎[${sessionScope.user.username }]访问
<br>

</body>
</html>

 

八、运行结果
在浏览器中输入:http://localhost:8080/SpringDemo/loginForm  结果如图

技术分享图片

技术分享图片

参考:《Spring+MyBatis企业应用实战》

--------------------------------------------分割线-----------------------------------------------
出现的错误:
1. 报错:CLIENT_PLUGIN_AUTH is required
原因:mysql-connector-java版本为6.0.6,版本太高。将版本改为5.1.46
2. 报错:eclipse Multiple annotations found at this line
解决:将<?xml version="1.0" encoding="UTF-8>重新写一遍(剪切+粘贴)
参考:https://blog.csdn.net/z_youarethebest/article/details/52997832

 

Spring、SpringMVC、MyBatis整合

标签:ping   社区   ssi   libs   框架   查询   label   htm   version   

原文地址:https://www.cnblogs.com/zeroingToOne/p/8657546.html

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