Spring、SpringMVC、MyBatis整合

项目结构:

 新建web项目:File->new->Dynamic Web Project

一、准备所需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

二、数据库创建

user表

 items表

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

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

eclipse中新建properties文件:直接在文件夹上右键->New->other->General->File,新建一个.properties后缀的文件如XXX.properties。即自己写.properties后缀

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);

}

3. Items.java

import java.io.Serializable;
import java.util.Date;

public class Items implements Serializable{
    private Integer id;
    private String name;
    private Double price;
    private String detail;
    private String pic;
    private Date createtime;

    //set/get方法

}

4. ItemsMapper.java

import java.util.List;

import org.apache.ibatis.annotations.Select;

import com.game.domain.Items;

/**
 * ItemsMapper接口
 * */
public interface ItemsMapper {
    /**
     * 查询所有items
     * @return items对象集合
     * */
    @Select(" select * from items ")
    List<Items> findAll();

}

五、服务层实现
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);
    }

}

3. ItemsService.java

import java.util.List;

import com.game.domain.Items;

/**
 * 
 * Items服务层接口
 *
 */
public interface ItemsService {
    /**
     * 查找所有items
     * @return items对象集合
     * */
    List<Items> getAll();

}

4. ItemsServiceImpl.java

import java.util.List;

import com.game.domain.Items;
import com.game.mapper.ItemsMapper;
import com.game.service.ItemsService;
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;

/**
 * Book服务层接口实现类
 * @Service("itemsService")用于将当前类注释为一个Spring的bean,名为itemsService
 * */
@Transactional(propagation=Propagation.REQUIRED,isolation=Isolation.DEFAULT)
@Service("itemsService")
public class ItemsServiceImpl implements ItemsService {
    
    /**
     * 自动注入ItemsMapper
     * */
    @Autowired
    private ItemsMapper itemsMapper;

    /**
     * ItemsService接口getAll方法实现
     * @see { ItemsService }
     * */
    @Transactional(readOnly=true)
    @Override
    public List<Items> getAll() {
        // TODO Auto-generated method stub
        return itemsMapper.findAll();
    }

}

六、控制层实现
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;
    }

}

@Controller用于标记一个类,使用它标记的类就是一个SpringMVC Controller对象,即一个控制器类。
Spring使用扫描机制查找应用程序中所有基于注解的控制器类。
分发处理器扫描使用了该注解的类的方法(即标记了@Controller的类的方法),并检测该方法是否使用了@RequestMapping注解,使用@RequestMapping注解的方法才是真正处理请求的处理器。

配置:<context:component-scan base-package="com.game.controller"/>

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;
    }

}

每个请求方法可以包含多个参数类型。例:如果需要访问HttpServletRequest对象,则可以添加HttpServletRequest作为参数;如果需要访问HttpSession对象,则可以添加HttpSession作为参数。
例:该login方法中添加了HttpSession对象

3. ItemsController.java

import java.util.List;

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

import com.game.domain.Items;
import com.game.service.ItemsService;

/**
 * 处理items请求控制器
 * */
@Controller
public class ItemsController {
    
    /**
     * 自动注入ItemsService
     * */
    @Autowired
    @Qualifier("itemsService")
    private ItemsService itemsService;

    /**
     * 处理/main请求
     * */
    @RequestMapping(value="/main")
     public String main(Model model){
        // 获得所有items集合
        List<Items> items_list = itemsService.getAll();
        // 将items集合添加到model当中
        model.addAttribute("items_list", items_list);
        // 跳转到main页面
        return "main";
    }

}

@RequestMapping注释用来映射一个请求和一种方法,value="/main"表示http://localhost:8080/main的请求由main方法进行处理。
main方法接收一个org.springframework.ui.Model类型的参数,本例在model中添加了一个名为“items_list”的字符串对象,该对象可以在返回的视图中通过request对象获取。最后,方法返回一个字符串“main”作为视图名称。视图名称经过视图解析器后的完整路径:/WEB-INF/content/main.jsp
原因:视图解析器InternalResourceViewResolver来解析视图,视图解析器中配置的prefix属性(/WEB-INF/content/)表示视图的前缀,suffix属性(.jsp)表示视图的后缀,因为返回的视图字符串是main,所以经视图解析器后,视图的完整路径为:
/WEB-INF/content/main.jsp

springMVC中的model:用这个专门的对象来进行模型层的存值和视图层的取值
在MVC框架中,控制器(Controller)执行业务逻辑,用于产生模型数据(Model),而视图(View)则用于渲染模型数据。
SpringMVC提供了多种途径输出模型数据:
Model和ModelMap
ModelAndView
@ModelAttribute
@SessionAttributes

七、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"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>
<table border="1">
    <tr>
        <th>id</th><th>名称</th><th>描述</th><th>价格</th>
    </tr>
    <c:forEach items="${requestScope.items_list }" var="items">
        <tr>
            <td>${items.id }</td>
            <td>${items.name }</td>
            <td>${items.detail }</td>
            <td>${items.price }</td>
        </tr>
    </c:forEach>
</table>
</body>
</html>

流程:
页面发起一个请求-->controller-->controller通过一个service对象调用service的方法-->service中通过mapper对象调用数据库查询方法-->去查询数据库

八、运行结果
在浏览器中输入: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
3. 登录成功后,items表格中没有数据,最后发现是main.xml中的警告原因:unknown tag foreach
原因:添加:<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>,并导入jstl.jar包。如图

 

posted @ 2018-03-27 15:08  zeroingToOne  阅读(278)  评论(0编辑  收藏  举报