欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Springmvc+Mybatis整合及api接口编写demo

程序员文章站 2024-02-29 12:36:04
...

最近在看java后台,折腾了几天,写了一个springmvc+mybatis的demo,这边提供给初学者一起学习。

首先看下项目结构:
Springmvc+Mybatis整合及api接口编写demo

src下面的entity、mapper都是mybatis自动生成的实体、mapper.java及mapper.xml文件,web下面是service和controller层;resources下面则是一些配置文件,下面会一一讲到。

另外说下mybatis自动生成表实体,mapper文件:
可以在网上下载:mybatis-generator.zip,里面包含了的文件如下:
Springmvc+Mybatis整合及api接口编写demo

我这里用的是1.3.5的版本,下载之后的lib目录里面应该有mybatis-generator-core-1.3.5.jar、mybatis-generator-core-1.3.5-javadoc.jar、mybatis-generator-core-1.3.5-sources.jar、mysql-connector-java-5.1.29.jar、generatorConfig.xml这些东西,然后自己需要修改generatorConfig.xml里面的内容,src文件夹是我新建的,里面用来装生成的package,我修改的generatorConfig.xml内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration>
    <!-- 引入配置文件 -->
    <!-- <properties resource="system.properties" /> -->
    <!-- 指定数据连接驱动jar地址 -->
    <classPathEntry location="D:\Javaweb\eclipse\eclipse\mybatis-generator-core-1.3.5\lib\mysql-connector-java-5.1.29.jar"/>

    <!--数据库驱动-->
    <context id="DB2Tables"    targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!--数据库链接地址账号密码-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/sunshine" userId="root" password="root">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!-- 生成实体类地址 -->
        <javaModelGenerator targetPackage="com.sm.entity" targetProject="src">
            <!-- 是否针对string类型的字段在set的时候进行trim调用 -->
            <property name="trimStrings" value="true" />
            <!-- <property name="rootClass" value="com.sm.entity" /> 继承父类 -->
        </javaModelGenerator>

        <!-- 生成mapxml文件 -->
        <sqlMapGenerator targetPackage="com.sm.mapper" targetProject="src">
        </sqlMapGenerator>

        <!-- 生成mapxml对应client,也就是接口dao -->
        <javaClientGenerator targetPackage="com.sm.mapper" targetProject="src" type="XMLMAPPER">

        </javaClientGenerator>
        <!-- tables -->
        <table tableName="answer_thank" domainObjectName="AnswerThank" >
            <property name="useActualColumnNames" value="true"/>
        </table>
        <table tableName="channel_topic" domainObjectName="ChannelTopic" >
            <property name="useActualColumnNames" value="true"/>
        </table>
        <table tableName="private_chat" domainObjectName="PrivateChat" >
            <property name="useActualColumnNames" value="true"/>
        </table>
        <table tableName="shine_channel" domainObjectName="ShineChannel" >
            <property name="useActualColumnNames" value="true"/>
        </table>
        <table tableName="shine_user" domainObjectName="ShineUser" >
            <property name="useActualColumnNames" value="true"/>
        </table>
        <table tableName="topic_answer" domainObjectName="TopicAnswer" >
            <property name="useActualColumnNames" value="true"/>
            <generatedKey column="spreadId" sqlStatement="MySql"  identity="true" type="post"/>
        </table>
        <table tableName="topic_attention" domainObjectName="TopicAttention" >
            <property name="useActualColumnNames" value="true"/>
        </table>

    </context>
</generatorConfiguration>  

这边注意数据连接驱动包的位置,我把生成的mapper.java和mapper.xml 放在同一个package中,数据库是我在本地随便选择的(因为只是做测试),上面都有注释,需要修改自己的xml也很简单。
生成之后的结构如下:
Springmvc+Mybatis整合及api接口编写demo

讲解项目的提前,需要用到的jar,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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.sm</groupId>
    <artifactId>spring-mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <!-- base setting -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.build.locales>zh_CN</project.build.locales>

        <!-- plugin versions -->
        <plugin.maven-compiler>3.1</plugin.maven-compiler>

        <!-- lib versions -->

        <!-- mybatis版本号 -->
        <mybatis.version>3.2.4</mybatis.version>
        <!-- log4j日志文件管理包版本 -->
        <slf4j.version>1.6.6</slf4j.version>
        <log4j.version>1.2.12</log4j.version>
        <junit.version>4.11</junit.version>
        <spring.version>4.1.2.RELEASE</spring.version>
        <httpclient.version>4.1.2</httpclient.version>
        <jackson.version>2.5.0</jackson.version>
        <tomcat.jdbc.version>7.0.53</tomcat.jdbc.version>
        <jstl.version>1.2</jstl.version>
        <aspectj.version>1.6.12</aspectj.version>
        <maven-dependency-plugin.version>2.1</maven-dependency-plugin.version>
    </properties>

    <dependencies>
        <!-- junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
        </dependency>

        <!-- springframe start -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

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

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

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

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

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

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

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

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

        <!-- springframe end -->

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

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

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

        <!-- log start -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <!-- log end -->

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

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

        <!-- alibaba druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.2</version>
        </dependency>

        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.3</version>
        </dependency>

        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
            <version>1.5.7</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>


        <!--velocity -->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>1.6</version>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.0</version>
        </dependency>

    </dependencies>

    <build>  
    <plugins>  
        <!-- define the project compile level -->  
        <plugin>  
            <groupId>org.apache.maven.plugins</groupId>  
            <artifactId>maven-compiler-plugin</artifactId>  
            <version>2.3.2</version>  
            <configuration>  
                <source>1.8</source>  
                <target>1.8</target>  
            </configuration>  
        </plugin>  
    </plugins>  
</build>
</project>

下面再一起看配置文件:
使用mybatis肯定需要连接本地数据库,配置文件db.properties

jdbc.driverClass = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/sunshine?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true
jdbc.username = root
jdbc.password = root
jdbc.minPoolSize= 1
jdbc.maxPoolSize= 100
jdbc.timeout=60000
jdbc.initialSize=5

removeAbandoned=true
removeAbandonedTimeout=200
connectionProperties=clientEncoding=UTF-8

log4j.properties是日志文件,这边不贴了,网上一大堆。

然后看spring-context.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"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.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
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        ">

    <!-- 加载配置属性文件 -->
    <context:property-placeholder
        ignore-unresolvable="true" location="classpath:/db.properties" />

    <!-- 使用Annotation自动注册Bean,解决事物失效问题:在主容器中不扫描@Controller注解,在SpringMvc中只扫描@Controller注解。 -->
    <!-- base-package 如果多个,用“,”分隔 -->
    <context:component-scan base-package="com.sm.web"/>
    <import resource="spring-mybatis.xml" />
</beans>

加载了db.properties文件,然后 导入了 spring-mybatis.xml文件,可想而知,里面当然是配置数据源,sqlSessionFactory等信息了。一下是 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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    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/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
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util-3.0.xsd">
    <!-- 配置数据库 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
        init-method="init" destroy-method="close">
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="driverClassName" value="${jdbc.driverClass}" />
        <property name="url" value="${jdbc.url}" />

        <!-- 初始化大小连接 -->
        <property name="initialSize" value="${jdbc.initialSize}" />
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="${jdbc.timeout}" />
        <!-- 自动清除无用连接 -->
        <property name="removeAbandoned" value="${removeAbandoned}" />
        <!-- 清除无用连接的等待时间 -->
        <property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" />
        <!-- 连接属性 -->
        <property name="connectionProperties" value="${connectionProperties}" />
    </bean>

    <!-- mybatis文件配置,扫描所有mapper文件 -->
    <bean id="sqlSessionFactory"
          class="org.mybatis.spring.SqlSessionFactoryBean"
              p:dataSource-ref="dataSource"
          p:configLocation="classpath:SqlMapConfig.xml"/>
    <!-- configLocation为mybatis属性 mapperLocations为所有mapper-->
    <!-- spring与mybatis整合配置,扫描所有dao -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
          p:basePackage="com.sm.mapper"
          p:sqlSessionFactoryBeanName="sqlSessionFactory"/>

    <!-- 开启事务注解驱动 -->
    <tx:annotation-driven />
    <!-- 事物管理器 -->
    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
</beans>

内容很简单,有注释,这里说下: p:configLocation=”classpath:SqlMapConfig.xml”,SqlMapConfig.xml文件时空的,本应该是mybatis配置数据源的资源文件,然后提供给sqlSessionFactory去引用,我嫌文件配置多,然后就把配置数据源挪到spring-mybatis.xml文件中,而引用的SqlMapConfig.xml则是一个空文件,可以删除。

下面还有spring-servlet.xml文件:

<?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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="com.sm.web" />

    <!-- 配置Spring视图容器 -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="contentType" value="text/html;charset=UTF-8" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>


    <bean
        class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>

    <bean
        class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter" />
            </list>
        </property>
    </bean>

    <bean id="mappingJacksonHttpMessageConverter"
        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    </bean>
</beans>

用于显示前端页面的配置,注意:这里的mappingJacksonHttpMessageConverter必须要配置,否则在编写接口的时候会无法映射,@ResponseBody注解会无效,甚至会报错。

最后配置的web.xml也比较简单:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
  <display-name>spring-mybatis</display-name>
  <welcome-file-list>
    <welcome-file>/WEB-INF/jsp/index.jsp</welcome-file>
  </welcome-file-list>

  <!-- **Tomcat的defaultServlet来处理静态文件 -->
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.jpg</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.gif</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.png</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.js</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.css</url-pattern>
    </servlet-mapping>

    <!-- 配置日志文件 -->
    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>classpath:/log4j.properties</param-value>
    </context-param>

    <!--spring容器初始化-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:/spring-context.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <filter>
        <filter-name>encodingFilter</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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- 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>classpath:/spring-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

加载spring容器文件spring-context.xml,还有前端视图容器文件spring-servlet.xml。完成这些,算是整合成功了,下面可以开始写service,controller。

目前在controller层随便写了几种接口调用方式的方法,下面都会贴源码:
service层接口:

package com.sm.web.service.userservice;

import java.util.List;

import org.springframework.stereotype.Service;

import com.sm.entity.ShineUser;

public interface UserService {
    /**
     * 获取所有的用户数据
     * @return
     * @throws Exception
     */
    List<ShineUser> getUsers() throws Exception;

    /**
     * 根据用户名称查询单个用户
     */
    ShineUser findUserById(ShineUser shineUser) throws Exception;

    /**
     * 模糊查询用户数据
     */
    List<ShineUser> findUsers(String param) throws Exception;

    /**
     * 根据用户id更新某个用户的信息
     */
    void updateUser(ShineUser shineUser) throws Exception;

    /**
     * 删除某条用户记录
     */
    void deleteUser(ShineUser shineUser) throws Exception;

    /**
     * 登录操作
     */
    ShineUser login(ShineUser shineUser) throws Exception;

}

service实现类 UserServiceImpl:

package com.sm.web.service.userservice.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sm.entity.ShineUser;
import com.sm.entity.ShineUserExample;
import com.sm.mapper.ShineUserMapper;
import com.sm.utils.ApiConfig;
import com.sm.web.service.userservice.UserService;

@Service
public class UserServiceImpl implements UserService {

    private Logger logger = Logger.getLogger(getClass());

    @Autowired
    private ShineUserMapper shineUserMapper;

    /**
     * 获取用户数据
     */
    public List<ShineUser> getUsers() throws Exception {
        return shineUserMapper.selectByExample(null);
    }

    /**
     * 根据id查询单个用户
     */
    @Override
    public ShineUser findUserById(ShineUser shineUser) throws Exception {
        ShineUser user = new ShineUser();
        if (shineUser != null) {
            user = shineUserMapper.selectByPrimaryKey(shineUser.getUser_id());
        } else {
            logger.debug("用户信息为空!");
        }
        return user;
    }

    /**
     * 根据用户id,更新用户信息
     */
    @Override
    public void updateUser(ShineUser shineUser) {
        if (shineUser != null) {
            shineUserMapper.updateByPrimaryKey(shineUser);
        } else {
            logger.debug("更新-->用户id为空!");
        }
    }

    /**
     * 根据用户id,删除某条用户信息
     */
    @Override
    public void deleteUser(ShineUser shineUser) {
        if (shineUser != null) {
            shineUserMapper.deleteByPrimaryKey(shineUser.getUser_id());
        } else {
            logger.debug("删除-->用户id为空!");
        }

    }

    /**
     * 模糊查询 这边主要是用户名和邮箱的模糊搜索
     * 
     */
    @Override
    public List<ShineUser> findUsers(String param) throws Exception {
        List<ShineUser> list = new ArrayList<>();
        if (!param.isEmpty() && !param.equals("null")) {
            ShineUserExample shineUserExample = new ShineUserExample();
            shineUserExample.or().andNicknameLike("%" + param + "%");
            shineUserExample.or().andEmailLike("%" + param + "%");
            list = shineUserMapper.selectByExample(shineUserExample);
        } else {
            logger.debug("模糊查询-->参数为空!");
        }
        return list;
    }

    /**
     * 登录
     */
    @Override
    public ShineUser login(ShineUser shineUser) throws Exception {
        List<ShineUser> users = new ArrayList<>();
        if (shineUser != null) {
            ShineUserExample shineUserExample = new ShineUserExample();
            shineUserExample.or().andNicknameEqualTo(shineUser.getNickname());
            users = shineUserMapper.selectByExample(shineUserExample);
            // 用户名是否存在
            // if (users.size() == 0) {
            // throw new Exception(ApiConfig.loginMsg[0]);
            // }
            // // 密码错误
            // if (!users.get(0).getPassword().equals(shineUser.getPassword()))
            // {
            // throw new Exception(ApiConfig.loginMsg[1]);
            // }
        } else {
            logger.debug("用户登录-->" + shineUser);
        }
        return users != null && users.size() > 0 ? users.get(0) : null;
    }

}

然后再到controller层的UserController:

package com.sm.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sm.entity.ShineUser;
import com.sm.utils.ApiConfig;
import com.sm.web.service.userservice.UserService;

@Controller
public class UserController {
    private Logger logger = Logger.getLogger(getClass());
    @Autowired
    private UserService userService;

    /**
     * 获取用户数据
     * 
     * @throws Exception
     */
    @RequestMapping(value = "/users", method = RequestMethod.GET)
    @ResponseBody
    public List<ShineUser> getUsers() {
        List<ShineUser> list = new ArrayList<>();
        try {
            list = userService.getUsers();
        } catch (Exception e) {
            logger.debug(e.getMessage());
        }
        return list;
    }

    /**
     * 模糊查询 用户名或者邮箱
     */
    @RequestMapping(value = "/queryusers", method = RequestMethod.POST, consumes = "application/json")
    @ResponseBody
    public List<ShineUser> queryUserData(@RequestParam(value = "data") String param) {
        logger.debug("先打印下参数:" + param);
        List<ShineUser> list = new ArrayList<>();
        try {
            list = userService.findUsers(param);
        } catch (Exception e) {
            logger.debug(e.getMessage());
        }
        return list;
    }

    /**
     * Map方式
     * 
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/usersList", consumes = "application/json")
    @ResponseBody
    public Map queryMapUser(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();
        try {
            String nickName = request.getParameter("data");
            logger.debug("http-->" + nickName);
            if (!nickName.isEmpty() && !nickName.equals("null")) {
                map.put("list", userService.findUsers(nickName));
            }
        } catch (Exception e) {
            logger.debug(e.getMessage());
        }
        return map;
    }

    /**
     * 查询单个用户
     */
    @RequestMapping(value = "/queryUser", method = RequestMethod.POST, consumes = "application/json")
    @ResponseBody
    public ShineUser getUser(@RequestParam(value = "userid") String userId) {
        ShineUser user = new ShineUser();
        user.setUser_id(Integer.parseInt(userId));
        try {
            user = userService.findUserById(user);
        } catch (Exception e) {
            logger.debug(e.getMessage());
        }
        return user;
    }

    /**
     * 使用body体方式的json请求
     * 
     * @param user
     * @return
     */
    @RequestMapping(value = "/getuser", method = RequestMethod.POST)
    @ResponseBody
    public Map getUserToBody(@RequestBody ShineUser user) {
        Map<String, String> map = new HashMap<>();
        ShineUser shineUser = new ShineUser();
        shineUser.setNickname(user.getNickname());
        shineUser.setPassword(user.getPassword());
        try {
            shineUser = userService.login(shineUser);
            if (shineUser != null) {
                if (user.getNickname().equals(shineUser.getNickname())
                        && user.getPassword().equals(shineUser.getPassword())) {
                    map.put(ApiConfig.config[0], ApiConfig.code[0]);
                    map.put(ApiConfig.config[1], ApiConfig.msg[0]);
                    map.put("username", shineUser.getNickname());
                    map.put("password", shineUser.getPassword());
                } else if (!user.getNickname().equals(shineUser.getNickname())) {
                    map.put(ApiConfig.config[0], ApiConfig.loginCode[0]);
                    map.put(ApiConfig.config[1], ApiConfig.loginMsg[0]);
                } else if (!user.getPassword().equals(shineUser.getPassword())) {
                    map.put(ApiConfig.config[0], ApiConfig.loginCode[1]);
                    map.put(ApiConfig.config[1], ApiConfig.loginMsg[1]);
                }
            } else {
                map.put(ApiConfig.config[0], ApiConfig.loginCode[0]);
                map.put(ApiConfig.config[1], ApiConfig.loginMsg[0]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 用户登录
     * 
     * @param userName
     * @param password
     * @return
     */
    @RequestMapping(value = "/userlogin", method = RequestMethod.POST, consumes = "application/json")
    @ResponseBody
    public Map userLogin(@RequestParam(value = "username", required = true) String userName,
            @RequestParam(value = "password", required = true) String password) {
        Map<String, String> map = new HashMap<>();
        if (!userName.isEmpty() && !password.isEmpty()) {
            ShineUser shineUser = new ShineUser();
            shineUser.setNickname(userName);
            shineUser.setPassword(password);
            try {
                shineUser = userService.login(shineUser);
                if (shineUser != null) {
                    if (userName.equals(shineUser.getNickname()) && password.equals(shineUser.getPassword())) {
                        map.put(ApiConfig.config[0], ApiConfig.code[0]);
                        map.put(ApiConfig.config[1], ApiConfig.msg[0]);
                        map.put("username", shineUser.getNickname());
                        map.put("password", shineUser.getPassword());
                    } else if (!userName.equals(shineUser.getNickname())) {
                        map.put(ApiConfig.config[0], ApiConfig.loginCode[0]);
                        map.put(ApiConfig.config[1], ApiConfig.loginMsg[0]);
                    } else if (!password.equals(shineUser.getPassword())) {
                        map.put(ApiConfig.config[0], ApiConfig.loginCode[1]);
                        map.put(ApiConfig.config[1], ApiConfig.loginMsg[1]);
                    }
                } else {
                    map.put(ApiConfig.config[0], ApiConfig.loginCode[0]);
                    map.put(ApiConfig.config[1], ApiConfig.loginMsg[0]);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return map;
    }
}

到这里,哎呀,so easy。

最后谈谈我遇到的坑:
①.spring-servlet.xml中的 <context:component-scan base-package="com.sm.web" /> 扫描包没写。
②.spring-servlet.xml中的mappingJacksonHttpMessageConverter 没有配置
③.spring-context.xml中的<context:component-scan base-package="com.sm.web"/>没写,导致@Controller不生效。
④.spring-context.xml中的 sqlSessionFactory配置写错,原来是这样:<property name="sqlSessionFactoryBeanName" ref="sqlSessionFactory"/> 实际是这样:<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>,注意ref和value 的区别,后来写成:p:sqlSessionFactoryBeanName="sqlSessionFactory"这种方式。