Spring MVC 4 - MyBatis使用

本文详细介绍了如何将Spring MVC与MyBatis进行整合,从项目结构到配置文件,再到数据设计和运行结果,包括pom.xml配置、Controller、DAO、Model、Service层的实现,以及mapper映射和数据库操作。
摘要由CSDN通过智能技术生成

1.返回json
2.Ajax请求
3.多视图输出
4.MyBatis使用

这里写图片描述

1.项目结构

这里写图片描述

2.pom.xml文件

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.jeiker.demo</groupId>
  <artifactId>spring-mybatis</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>spring-mybatis Maven Webapp</name>
  <url>http://maven.apache.org</url>

    <properties>
        <jdk.version>1.8</jdk.version>
        <spring.version>4.2.2.RELEASE</spring.version>
        <jackson.version>2.8.5</jackson.version>
        <logback.version>1.1.7</logback.version>
        <jcl.slf4j.version>1.7.21</jcl.slf4j.version>
        <jstl.version>1.2</jstl.version>
        <servletapi.version>3.1.0</servletapi.version>
        <junit.version>3.8.1</junit.version>
        <!-- mybatis版本号 -->
        <mybatis.version>3.2.8</mybatis.version>
    </properties>

    <dependencies>
        <!-- 单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- spring-webmvc 排除日志依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- mysql驱动包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.34</version>
        </dependency>

        <!--mybatis依赖 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>

        <!-- mybatis/spring包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.2</version>
        </dependency>

        <!-- json转对象 ,对象转json -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson.version}</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>

        <!-- view层的 jsp标准函数库 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl.version}</version>
        </dependency>

        <!-- 日志 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${jcl.slf4j.version}</version>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
        </dependency>

        <!-- 仅在编译时使用, 布署不用,布署时容器会提供 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${servletapi.version}</version>
            <scope>provided</scope>
        </dependency>

  </dependencies>
  <build>
    <finalName>spring-mybatis</finalName>

    <plugins>
      <!--编译插件-->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>${jdk.version}</source>
          <target>${jdk.version}</target>
        </configuration>
      </plugin>

      <!-- 部署至本机 -->
      <plugin>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-maven-plugin</artifactId>
        <version>9.3.9.v20160517</version>
        <configuration>
          <httpConnector>
            <port>8080</port>
          </httpConnector>
          <webAppConfig>
            <contextPath>/</contextPath>
          </webAppConfig>
        </configuration>
      </plugin>
    </plugins>

  </build>
</project>

3.controller

UserController.java

package com.jeiker.controller;

import com.jeiker.model.User;
import com.jeiker.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

/**
 * @Author : xiao
 * @Date : 16/12/24 上午11:54
 */
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/userInfo/{userId}", method = RequestMethod.GET)
    public ModelAndView getIndex(ModelMap modelMap, @PathVariable int userId) {
        ModelAndView modelAndView = new ModelAndView("index");
        User user = userService.selectUserById(userId);
        modelAndView.addObject("user", user);
        return modelAndView;
    }
}

4.dao

UserDao.java

package com.jeiker.dao;

import com.jeiker.model.User;

/**
 * @Author : xiao
 * @Date : 16/12/24 上午11:48
 */
public interface UserDao {
    public User selectUserById(Integer userId);
}

5.model

User.java

package com.jeiker.model;

/**
 * @Author : xiao
 * @Date : 16/12/24 上午11:47
 */
public class User {
    private Integer userId;
    private String userName;
    private String userPassword;

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserPassword() {
        return userPassword;
    }

    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }
}

6.service

UserService.java

package com.jeiker.service;

import com.jeiker.model.User;

/**
 * @Author : xiao
 * @Date : 16/12/24 上午11:50
 */
public interface UserService {
    User selectUserById(Integer userId);
}

UserServiceImpl.java

package com.jeiker.service;

import com.jeiker.dao.UserDao;
import com.jeiker.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author : xiao
 * @Date : 16/12/24 上午11:51
 */
@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserDao userDao;

    @Override
    public User selectUserById(Integer userId) {
        return userDao.selectUserById(userId);
    }
}

7.wiews

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<html>
<head>
    <link rel="stylesheet" href="https://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<table class="table">
    <caption>User Info</caption>
    <thead>
    <tr>
        <th>编号</th>
        <th>用户名</th>
        <th>密码</th>
    </tr>
    </thead>
    <tbody>
    <tr class="success">
        <td>${user.userId}</td>
        <td>${user.userName}</td>
        <td>${user.userPassword}</td>
    </tr>
    </tbody>
</table>
</body>
</html>

8.配置文件

8.1.mapper映射文件

userMapper.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.jeiker.dao.UserDao">
    <!--设置model类和数据库中表的字段一一对应,注意数据库字段和model类中的字段名称不致,此处一定要!-->
    <resultMap id="BaseResultMap" type="com.jeiker.model.User">
        <id column="user_id" property="userId" jdbcType="INTEGER" />
        <result column="user_name" property="userName" jdbcType="CHAR" />
        <result column="user_password" property="userPassword" jdbcType="CHAR" />
    </resultMap>
    <!-- 查询单条记录 -->
    <select id="selectUserById" parameterType="int" resultMap="BaseResultMap">
        SELECT * FROM t_user WHERE USER_ID = #{userId}
    </select>
</mapper>

8.2.mybatis配置文件

mybatis-config.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>

8.3.properties-jdbc连接的属性文件

jdbc.properties

##jdbc配置文件
jdbc_driverClassname=com.mysql.jdbc.Driver
jdbc_url=jdbc:mydql://localhost:3306/user
jdbc_username=root
jdbc_password=123456

8.4.Spring MVC配置文件

spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <mvc:annotation-driven />

    <!-- 扫描controller (controller层注解)-->
    <context:component-scan base-package="com.jeiker.controller" />

    <!-- 对模型视图添加前后缀 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/views/"
          p:suffix=".jsp"/>

</beans>

8.5.Spring Application Context配置文件

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

    <!-- 引入jdbc配置文件-->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:properties/*.properties</value>
                <!-- 要是有多个配置文件,只需要在这里添加即可 -->
            </list>
        </property>
    </bean>

    <!-- 配置jdbc的数据源 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName">
            <value>com.mysql.jdbc.Driver</value>
        </property>
        <property name="url">
            <value>jdbc:mysql://localhost:3306/user</value>
        </property>
        <property name="username">
            <value>root</value>
        </property>
        <property name="password">
            <value>123456</value>
        </property>
    </bean>

    <!-- MyBatis配置,自动扫描**Mapper.xml对应的dao层接口文件,这样就不需要手动配置映射了 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.jeiker.dao"/>
    </bean>

    <!-- 配置MyBatis的文件,mapperLocations配置**Mapper.xml文件的位置,configLocation配置mybatis-config文件的位置 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 对应jdbc的数据源 -->
        <property name="dataSource" ref="dataSource" />
        <!-- **Mapper.xml文件的位置 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml" />
        <!-- MyBtis 自身配置文件的位置 -->
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
    </bean>

    <!-- 自动扫描service层的注解bean -->
    <context:component-scan base-package="com.jeiker.service" />
</beans>

8.6.web配置文件

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/XQ"
         id="WebApp_ID" version="3.1">
  <display-name>spring-mybatis</display-name>

  <!-- 读取spring配置文件 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:application.xml</param-value>
  </context-param>

  <context-param>
    <param-name>spring.profiles.active</param-name>
    <param-value>dev</param-value>
  </context-param>

  <context-param>
    <param-name>spring.profiles.default</param-name>
    <param-value>dev</param-value>
  </context-param>

  <context-param>
    <param-name>spring.liveBeansView.mbeanDomain</param-name>
    <param-value>dev</param-value>
  </context-param>

  <!-- 监听器的作用:就是启动Web容器时,自动装配ApplicationContext的配置信息 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!-- SpringMVC核心配置-->
  <!-- DispatcherServlet是前端控制器设计模式的实现,提供Spring Web MVC的集中访问点,而且负责职责的分派 -->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc/spring-mvc.xml</param-value>
    </init-param>
  </servlet>

  <!--<servlet>-->
    <!--<servlet-name>DruidStatView</servlet-name>-->
    <!--<servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>-->
  <!--</servlet>-->
  <!--<servlet-mapping>-->
    <!--<servlet-name>DruidStatView</servlet-name>-->
    <!--<url-pattern>/druid/*</url-pattern>-->
  <!--</servlet-mapping>-->

  <!-- 拦截器设置 -->
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>

9.数据设计

9.1 建立一个名为user的数据库

9.2 创建表t_user

CREATE TABLE `t_user` ( `user_id` int(11) NOT NULL AUTO_INCREMENT, `user_name` char(30) NOT NULL, `user_password` char(10) NOT NULL, PRIMARY KEY (`user_id`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8

9.3 插入测试数据

INSERT INTO t_user (user_id, user_name, user_password) VALUES (1, 'jeikerxiao', '123456');

INSERT INTO t_user (user_id, user_name, user_password) VALUES (2, 'xiao', '456123');

数库的数据:

这里写图片描述

10.运行结果

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值