Spring+Spring mvc+Mybatis整合教程(基于Maven)
Posted husencd
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring+Spring mvc+Mybatis整合教程(基于Maven)相关的知识,希望对你有一定的参考价值。
1. 概述
1.1 Spring
- 轻量级:Spring是非侵入性的,基于Spring开发的应用中的对象可以不依赖于 Spring 的 API
- 依赖注入(DI:dependency injection、IOC)
- 面向切面编程(AOP:aspect oriented programming)
- 容器:Spring是一个容器,包含并且管理应用对象的生命周期
- 框架:Spring 实现了使用简单的组件配置组合成一个复杂的应用.,在Spring中可以使用XML和Java注解组合这些对象
- 一站式:在IOC和AOP的基础上可以整合各种企业应用的开源框架和优秀的第三方类库(实际上Spring自身也提供了展现层的Spring MVC和持久层的Spring JDBC)
1.2 Spring MVC
- Spring为展现层提供的基于MVC设计理念的优秀的Web框架,是目前最主流的MVC框架之一
- Spring3.0后全面超越Struts2,成为最优秀的MVC框架
- Spring MVC通过一套MVC注解,让POJO成为处理请求的控制器,而无须实现任何接口
- 支持RESTful风格的URL请求
- 采用了松散耦合可插拔组件结构,比其他MVC框架更具扩展性和灵活性
1.3 MyBatis
MyBatis是支持普通SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装。MyBatis可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。
2. 项目结构
3. 整合过程
3.1 配置文件
3.1.1 使用Maven管理jar包
pom.xml配置如下:
<build>
<finalName>ssm</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<!--统一源代码和编译输出的JDK版本-->
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<!--统一源代码的编码方式-->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- spring版本号 -->
<spring.version>4.2.2.RELEASE</spring.version>
<!-- mybatis版本号 -->
<mybatis.version>3.2.8</mybatis.version>
<!-- log4j日志文件管理包版本 -->
<slf4j.version>1.7.7</slf4j.version>
<log4j.version>1.2.17</log4j.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<!--表示开发的时候引入,发布的时候不会加载此包 -->
<scope>test</scope>
</dependency>
<!-- spring核心包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</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-webmvc</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-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</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>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</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>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
</dependency>
<!-- 导入java ee jar包 -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<!--只参与编译,无需参与打包-->
<scope>provided</scope>
</dependency>
<!-- JSTL标签类 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<!--运行时需要,无需参与编译-->
<scope>runtime</scope>
</dependency>
<!-- 导入mysql数据库链接jar包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
<!-- 导入dbcp的jar包,用来在spring-mybatis.xml中配置数据库 -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<!-- 日志文件管理包 -->
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<!-- 格式化对象,方便输出日志 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.41</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 -->
<!-- 映入JSON -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<!-- 上传组件包 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-plugin-api</artifactId>
<version>3.3.3</version>
</dependency>
<!--druid连接池-->
<!--<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.16</version>
</dependency>
-->
<!--beetl模板引擎-->
<dependency>
<groupId>org.beetl</groupId>
<artifactId>beetl-core</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.6.0</version>
</dependency>
</dependencies>
3.1.2 建立JDBC属性文件:jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1/ssmdemo
jdbc.username=root
jdbc.password=123456
#定义初始连接数
jdbc.initialSize=0
#定义最大连接数
jdbc.maxActive=20
#定义最大空闲
jdbc.maxIdle=20
#定义最小空闲
jdbc.minIdle=1
#定义最长等待时间
jdbc.maxWait=60000
3.1.3 Log4j的配置:log4j.properties
#定义LOG输出级别
log4j.rootLogger=INFO,Console,File
#定义日志输出目的地为控制台
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#可以灵活地指定日志输出格式,下面一行是指定具体的格式
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
#文件大小到达指定尺寸的时候产生一个新的文件
log4j.appender.File = org.apache.log4j.RollingFileAppender
#指定输出目录
log4j.appender.File.File = logs/ssm.log
#定义文件最大大小
log4j.appender.File.MaxFileSize = 10MB
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH:mm:ss}][%c]%m%n
3.1.4 建立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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.shihusen.ssm"/>
<!--1. 引入配置文件 -->
<bean id="placeholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:/properties/jdbc.properties"/>
</bean>
<!--2.<context:property-placeholder location="classpath:/properties/jdbc.properties"/>-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- 初始化连接大小 -->
<property name="initialSize" value="${jdbc.initialSize}"></property>
<!-- 连接池最大数量 -->
<property name="maxActive" value="${jdbc.maxActive}"></property>
<!-- 连接池最大空闲 -->
<property name="maxIdle" value="${jdbc.maxIdle}"></property>
<!-- 连接池最小空闲 -->
<property name="minIdle" value="${jdbc.minIdle}"></property>
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="${jdbc.maxWait}"></property>
</bean>
<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- 自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="classpath:mapper/*Mapper.xml"/>
<property name="typeAliasesPackage" value="com.shihusen.ssm.entity"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.shihusen.ssm.dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<!-- 4. 事务管理 : DataSourceTransactionManager -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 5. 使用声明式事务 -->
<tx:annotation-driven transaction-manager="txManager"/>
<!--
事物的具体内容
-->
<!--<tx:advice id="transactionAdvice" transaction-manager="transactionManager">-->
<!--<tx:attributes>-->
<!--<tx:method name="add*" propagation="REQUIRED" />-->
<!--<tx:method name="insert*" propagation="REQUIRED" />-->
<!--<tx:method name="save*" propagation="REQUIRED" />-->
<!--<tx:method name="update*" propagation="REQUIRED" />-->
<!--<tx:method name="edit*" propagation="REQUIRED" />-->
<!--<tx:method name="delete*" propagation="REQUIRED" />-->
<!--<tx:method name="get*" propagation="SUPPORTS" />-->
<!--<tx:method name="find*" propagation="SUPPORTS" />-->
<!--<tx:method name="search*" propagation="SUPPORTS" />-->
<!--<tx:method name="*" propagation="SUPPORTS" />-->
<!--</tx:attributes>-->
<!--</tx:advice>-->
<!--定义一个切面,在定义的切面上加入事物-->
<!--<aop:config>-->
<!--<aop:pointcut id="transactionPointcut" expression="execution(* com.shihusen.ssm.service..*Impl.*(..))" />-->
<!--<aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />-->
<!--</aop:config>-->
</beans>
3.1.5 建立springmvc.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"
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-3.2.xsd">
<context:component-scan base-package="com.shihusen.ssm.controller"/>
<mvc:annotation-driven/>
<!--配置beetl-->
<!--
<bean id="beetlGroupUtilConfiguration" class="org.beetl.ext.spring.BeetlGroupUtilConfiguration" init-method="init">
</bean>
<bean id="beetlSpringViewResolver" class="org.beetl.ext.spring.BeetlSpringViewResolver">
<property name="prefix" value="/page/"/>
<property name="suffix" value=".html"/>
<property name="contentType" value="text/html;charset=UTF-8"/>
-->
<!-- order指定优先使用BeetlSpringViewResolver-->
<!--
<property name="order" value="100"/>
</bean>
-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/page/"/>
<property name="suffix" value=".html"/>
<!--order无穷大-->
</bean>
<!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 默认编码 -->
<property name="defaultEncoding" value="utf-8"/>
<!-- 文件大小最大值 -->
<property name="maxUploadSize" value="10485760"/>
<!-- 内存中的最大值 -->
<property name="maxInMemorySize" value="40960"/>
</bean>
<!-- 1.对静态资源文件的访问 -->
<mvc:default-servlet-handler/>
<!--2.对静态资源文件的访问-->
<!--<mvc:resources location="/page/" mapping="/page/**"/>-->
<!--<mvc:resources location="/image/" mapping="/image/**"/>-->
<!--<mvc:resources location="/js/" mapping="/js/**"/>-->
<!--<mvc:resources location="/css/" mapping="/css/**"/>-->
<!--配置自定义拦截器-->
<!--
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/user/**"/>
<mvc:exclude-mapping path="/user/checkLogin"/>
<bean class="com.shihusen.ssm.interceptor.UserPreInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
-->
<!--定义异常处理页面-->
<!--
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="java.sql.SQLException">outException</prop>
<prop key="java.io.IOException">outException</prop>
<prop key="java.lang.Throwable">Exception</prop>
</props>
</property>
</bean>
-->
</beans>
3.1.6 建立web.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<!--防止中文乱码-->
<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>
<!-- Spring和mybatis的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/spring-mybatis.xml</param-value>
</context-param>
<!-- Spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 防止Spring内存溢出监听器 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<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:config/springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<!--
<error-page>
<error-code>404</error-code>
<location>/page/error_page1.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/page/error_page2.jsp</location>
</error-page>
-->
</web-app>
3.2 Java代码
3.2.1 建立数据库和表
DROP DATABASE IF EXISTS `ssmdemo`;
CREATE DATABASE ssmdemo;
use ssmdemo;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int PRIMARY KEY AUTO_INCREMENT,
`user_name` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES (1, ‘root‘, ‘root‘);
INSERT INTO `user` VALUES (2,‘shihusen‘, ‘shihusen‘);
3.2.2 建立generatorConfig.xml配置文件,使用mybatis-generator自动生成代码
<?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="jdbc.properties"></properties>-->
<classPathEntry location="F:\MyEclipse2015\workspace\ssm\mysql-connector-java-5.1.7-bin.jar" />
<context id="testTables" targetRuntime="MyBatis3">
<commentGenerator>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://127.0.0.1:3306/ssmdemo" userId="root"
password="123456">
</jdbcConnection>
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- targetProject:生成PO类的位置 -->
<javaModelGenerator targetPackage="com.shihusen.ssm.entity"
targetProject="F:\MyEclipse2015\workspace\ssm\src\main\java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- targetProject:mapper映射文件生成的位置 -->
<sqlMapGenerator targetPackage="mapper"
targetProject="F:\MyEclipse2015\workspace\ssm\src\main\resources">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- targetPackage:mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.shihusen.ssm.dao"
targetProject="F:\MyEclipse2015\workspace\ssm\src\main\java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
<table tableName="user" domainObjectName="User"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>
在Idea下,使用mybatis-generator的方法如下图所示:
运行之后,自动为我们生成pojo、mapper接口和mapper配置文件。
3.2.3 entity类(自动生成)
package com.shihusen.ssm.entity;
public class User {
private Integer id;
private String userName;
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 == null ? null : userName.trim();
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
}
3.2.4 dao接口层(自动生成)
package com.shihusen.ssm.dao;
import com.shihusen.ssm.entity.User;
import org.springframework.stereotype.Repository;
@Repository
public interface UserMapper {
int checkLogin(User user);
}
3.2.5 mapper.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.shihusen.ssm.dao.UserMapper" >
<select id="checkLogin" parameterType="User" resultType="int">
SELECT COUNT(*) from `user` where user_name = #{userName} and password = #{password}
</select>
</mapper>
3.2.6 service接口层
package com.shihusen.ssm.service;
import com.shihusen.ssm.entity.User;
/**
* Created by shihusen on 16-6-2.
*/
public interface UserService {
int checkLogin(User user);
}
service接口实现层
package com.shihusen.ssm.service.impl;
import com.shihusen.ssm.dao.UserMapper;
import com.shihusen.ssm.entity.User;
import com.shihusen.ssm.service.UserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* Created by shihusen on 16-6-2.
*/
@Service("userService")
public class UserServiceImpl implements UserService{
@Resource
private UserMapper userMapper;
@Override
public int checkLogin(User user) {
return userMapper.checkLogin(user);
}
}
3.2.7 controller控制层
package com.shihusen.ssm.controller;
import com.shihusen.ssm.entity.User;
import com.shihusen.ssm.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.annotation.Resource;
/**
* Created by shihusen on 2016/6/2.
*/
@Controller
public class UserController {
@Resource
private UserService userService;
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login() {
return "login";
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String checkLogin(User user,Model model) {
int result = userService.checkLogin(user);
if (1 == result) {
model.addAttribute("userName",user.getUserName());
return "success";
} else {
return "login";
}
}
}
3.2.8 视图层
index.jsp
<html>
<head>
<meta charset="UTF-8">
<title>Index Page</title>
</head>
<body align="center">
<h2>Hello World!</h2>
<a href="login"><h3>Click to login</h3></a>
</body>
</html>
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login Page</title>
</head>
<body align="center">
<form action="login" method="post">
<br><br>
<input type="text" name="userName" placeholder="Please input your name..."><br><br>
<input type="password" name="password" placeholder="Please input your password..."><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
welcome.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login Success Page</title>
</head>
<body align="center">
<% try{ %>
<h2>Welcome, <em>${userName}</em>!</h2>
<% }catch(error){} %>
</body>
</html>
4. 结果测试
浏览器搜索栏输入:http://localhost:8080/ssm/
点击登录,如下:
输入userName以及password,如果和数据库匹配,跳转到欢迎页面,如下:
以上是关于Spring+Spring mvc+Mybatis整合教程(基于Maven)的主要内容,如果未能解决你的问题,请参考以下文章
ssm(spring,spring mvc,mybatis)框架