以下针对于Spring + SpringMVC + MyBatis(SSM)框架的整合,只是个人简单的理解介绍,简单记录提供参考
Eclipse、Maven 3.5.0、MySQL 8.0.18、JDK 1.8、Tomcat 8、Spring4X、MyBatis 3.4.5
在MySQL中运行:
CREATE DATABASE innerssm;
USE innerssm;
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user_t
-- ----------------------------
DROP TABLE IF EXISTS `user_t`;
CREATE TABLE `user_t` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`age` int(4) NOT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user_t
-- ----------------------------
INSERT INTO `user_t` VALUES (1, '测试用户', '123', 24);
SET FOREIGN_KEY_CHECKS = 1;
创建Maven工程,具体创建Maven工程可以查看其他博主教程
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.sslt</groupId>
<artifactId>innersystem</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- spring版本号 -->
<spring.version>4.3.10.RELEASE</spring.version>
<!-- mybatis版本号 -->
<mybatis.version>3.4.5</mybatis.version>
<!-- log4j日志文件管理包版本 -->
<slf4j.version>1.7.7</slf4j.version>
<log4j.version>2.9.0</log4j.version>
<!-- mysql版本号 -->
<mysql.version>8.0.15</mysql.version>
</properties>
<dependencies>
<!-- junit依赖 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- JavaEE依赖 -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<!-- 配置servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- jsp依赖 -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
<!-- jstl依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Spring核心依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<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-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</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-expression</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>
<!-- mybatis框架依赖包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- spring mybatis依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- mysql数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- c3p0连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- log4j依赖 -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</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>
<!-- 文件上传依赖 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
</dependencies>
<!-- 配置使用的JDK版本 -->
<profiles>
<profile>
<id>jdk-1.8</id>
<activation>
<activeByDefault>true</activeByDefault>
<jdk>1.8</jdk>
</activation>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
</properties>
</profile>
</profiles>
</project>
1、Spring:Spring框架是一个开放源代码的J2EE应用程序框架,是针对bean的生命周期进行管理的轻量级容器。提供了功能强大IOC、AOP及Web MVC等功能。Spring框架主要由七部分组成,分别是 Spring Core、 Spring AOP、 Spring ORM、 Spring DAO、Spring Context、 Spring Web和 Spring Web MVC。我们平时开发接触最多的估计就是IOC容器,可装载bean,另外Spring的AOP,事务管理等等都是我们经常用到的。Spring框架比较强大,并不能三言两语来概括,具体深入学习大家可以自己去了解学习—Spring官网
2、SpringMVC:SpringMVC是在Spring框架内置的MVC的实现。应用于web层,相当于Controller,用来处理用户请求。简单理解就是用户通过地址栏输入如:http://网站域名/login。SpringMVC就会拦截到这个请求,并且调用Controller层中相应的方法,经过一系列的业务逻辑等操作(其中这些都不是SpringMVC的职责),最终把结果返回给用户,并且返回相应的页面。就是处理前后过程表现,方便前后端数据的传输。
3、MyBatis:MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。可以对配置和原生Map使用简单的 XML 或注解,将接口和 Java 的 POJOs映射成数据库中的记录。个人通俗理解就是能自由控制SQL,提升数据库访问的效率。可以使用 XML 的方式来组织管理我们的SQL,方便管理和后续优化。
在resources的资源文件目录管理XML配置文件
创建applicationContext.xml的配置文件,其中包括:
(1.1)Spring框架注解扫描配置;
(1.2)数据源c3p0连接池配置;
(1.3)Spring和MyBatis整合配置;
(1.4)事务管理配置;
编写具体的配置信息:
<?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:aop="http://www.springframework.org/schema/aop"
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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 开启spring的注解扫描 -->
<context:component-scan base-package="com.sslt.service"></context:component-scan>
<!-- 引入配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 配置数据源c3p0连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- 连接池中保留的最小连接数,默认为:3-->
<property name="minPoolSize" value="1" />
<!--连接池中保留的最大连接数。默认值: 15 -->
<property name="maxPoolSize" value="5" />
<!-- 初始化连接池中的连接数,取值应在minPoolSize与maxPoolSize之间,默认为3-->
<property name="initialPoolSize" value="1" />
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。默认值: 3 -->
<property name="acquireIncrement" value="1" />
</bean>
<!-- spring和MyBatis整合,不需要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource" />
<!-- 扫描entity包 使用别名 -->
<property name="typeAliasesPackage" value="com.sslt.entity" />
<!-- 自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="classpath:com/sslt/mapper/*.xml"></property>
</bean>
<!-- mapper扫描 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.sslt.mapper" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 开启注解事务管理器 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
其中jdbc.properties数据源链接具体信息配置:
#数据库驱动
jdbc.driver=com.mysql.cj.jdbc.Driver
#数据库连接
jdbc.url=jdbc:mysql://localhost:3306/innerssm?characterEncoding=utf8&&serverTimezone=UTC
#用户名
jdbc.username=root
#用户密码
jdbc.password=123456
在resources的资源文件目录创建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:aop="http://www.springframework.org/schema/aop"
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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 自动扫描该包 @controller注解的类-->
<context:component-scan base-package="com.sslt.controller"/>
<!-- 开启springMVC的处理器映射器和处理器适配器的扫描 -->
<mvc:annotation-driven/>
<!-- 配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 默认编码 -->
<property name="defaultEncoding" value="UTF-8" />
<!-- 文件大小最大值 -->
<property name="maxUploadSize" value="10485760000" />
<!-- 内存中的最大值 -->
<property name="maxInMemorySize" value="40960" />
</bean>
</beans>
(2.1)在web.xml中配置DispatcherServlet前端控制器
<!--配置前端控制器 -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 加载SpringMVC的配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC.xml</param-value>
</init-param>
<!--启动服务器,创建该servlet -->
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
(2.2)在web.xml中配置解决中文乱码过滤器
<!--解决中文乱码的过滤器-->
<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>
(2.3)在web.xml中配置ContextLoaderListener监听器
Spring监听器,默认只加载WEB-INF目录下的Spring核心配置文件,为了方便配置文件管理,我们自定义配置加载,方便维护和管理。
ContextLoaderListener监听器配置:
<!-- Spring监听器,默认只加载WEB-INF目录下的applicationContext.xml配置文件 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--加载Spring核心配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
(2.4)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"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>innersystem</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- Spring监听器,默认只加载WEB-INF目录下的applicationContext.xml配置文件 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--加载Spring核心配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--解决中文乱码的过滤器-->
<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>
<!--配置前端控制器 -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 加载SpringMVC的配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC.xml</param-value>
</init-param>
<!--启动服务器,创建该servlet -->
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
在resources的资源文件目录创建log4j.properties配置文件
log4j.properties具体配置信息:
log4j.rootLogger=INFO,fileout,stdout
#如果有特殊的包需要不同于根日志级别,在此配置
log4j.logger.com.ielpm.pay.df.tfb = INFO
# 控制台输出,上线时注释该段落
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d (%F:%L) %-5p %c - %m%n
#文件输出
log4j.appender.fileout.File=${catalina.home}/logs/innersystem/innersystem.log
log4j.appender.fileout.ImmediateFlush = false
log4j.appender.fileout.layout=org.apache.log4j.PatternLayout
log4j.appender.fileout.layout.ConversionPattern=%d [%t] (%F:%L) %-5p %c - %m%n
#Buffer size 8K
log4j.appender.fileout.BufferSize=8192
log4j.appender.file.encoding=UTF-8
在webapp下编写index.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>
<a href="user/test">初始测试</a>
</body>
</html>
在WEB-INF/pages下编写user.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>
<h1>测试成功...</h1>
</body>
</html>
在controller层中编写代码UserController.java类
package com.sslt.controller;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping(value = "/user")
public class UserController {
/**
* 日志对象
*/
private final static Logger logger = Logger.getLogger(UserController.class);
@RequestMapping(value = "/test")
public String Index(HttpServletRequest request, Model model){
System.out.println("请求成功......");
logger.info("日志打印......");
return "user";
}
}
tomcat运行innersystem项目,在浏览器访问地址:http://127.0.0.1:8080/innersystem/
点击 初始测试 后台处理结果:
点击 初始测试 前端响应页面:
在pom.xml中添加:
<build>
<plugins>
<!-- Mybatis Generator 代码自动生成插件 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<configuration>
<configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
</plugin>
</plugins>
</build>
在resources的资源文件目录创建目录generator和generatorConfig.xml配置文件
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>
<!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
<classPathEntry location="D:/mysql-connector-java-8.0.18/mysql-connector-java-8.0.18.jar"/>
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true"/>
<!-- 是否去除自动生成的注释 true:是 ; false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据库连接驱动类,URL,用户名、密码 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/innerssm?serverTimezone=UTC" userId="root" password="123456">
<property name="nullCatalogMeansCurrent" value="true" />
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成(实体)模型的包名和位置-->
<javaModelGenerator targetPackage="com.sslt.entity" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成XML映射文件的包名和位置-->
<sqlMapGenerator targetPackage="com.sslt.mapper" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成DAO接口的包名和位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.sslt.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
<table tableName="user_t" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>
其中数据库驱动包下载:
(1)在CSDN下载地址:驱动下载(https://download.csdn.net/download/u013526643/12566043)
(2)百度云盘下载:
链接:https://pan.baidu.com/s/1xLNb1LD1rcNbkkgUSJYEXw
提取码:rriq
(3)官网下载:https://dev.mysql.com/downloads/connector/j/
根据需求选择下载的Select Operating System下载最新的版本,这里选择–Platform Independent
历史版本选择–Archives
MyBatis自动生成代码流程:
选择系统右击选择–Run AS -->Maven build
在Goals框中输入:mybatis-generator:generate,点击:Run
再次自动生成代码时:
package com.sslt.entity;
public class User {
private Integer id;
private String username;
private String password;
private Integer age;
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();
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
UserMapper.java
package com.sslt.mapper;
import com.sslt.entity.User;
public interface UserMapper {
int deleteByPrimaryKey(Integer id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
}
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.sslt.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.sslt.entity.User">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="username" jdbcType="VARCHAR" property="username" />
<result column="password" jdbcType="VARCHAR" property="password" />
<result column="age" jdbcType="INTEGER" property="age" />
</resultMap>
<sql id="Base_Column_List">
id, username, password, age
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer"
resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user_t
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from user_t
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.sslt.entity.User">
insert into user_t (id, username, password,
age)
values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR},
#{password,jdbcType=VARCHAR},
#{age,jdbcType=INTEGER})
</insert>
<insert id="insertSelective" parameterType="com.sslt.entity.User">
insert into user_t
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="username != null">
username,
</if>
<if test="password != null">
password,
</if>
<if test="age != null">
age,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
</if>
<if test="username != null">
#{username,jdbcType=VARCHAR},
</if>
<if test="password != null">
#{password,jdbcType=VARCHAR},
</if>
<if test="age != null">
#{age,jdbcType=INTEGER},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.sslt.entity.User">
update user_t
<set>
<if test="username != null">
username = #{username,jdbcType=VARCHAR},
</if>
<if test="password != null">
password = #{password,jdbcType=VARCHAR},
</if>
<if test="age != null">
age = #{age,jdbcType=INTEGER},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.sslt.entity.User">
update user_t
set username = #{username,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR},
age = #{age,jdbcType=INTEGER}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
创建接口UserService.java类
package com.sslt.service;
import com.sslt.entity.User;
public interface UserService {
/**
* 用户信息查询
* @param user
* @return
*/
public User selectParma(User user);
}
创建Service实现类UserServiceImpl.java,实现UserService.java的接口,注入数据访问层接口UserMapper
实现类UserServiceImpl.java
package com.sslt.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sslt.entity.User;
import com.sslt.mapper.UserMapper;
import com.sslt.service.UserService;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
/**
* 用户信息查询
*/
public User selectParma(User user) {
return userMapper.selectParma(user);
}
}
在UserMapper.java类中添加接口selectParma()
User selectParma(User user);
在UserMapper.xnl配置文件中添加接口**selectParma()**实现方法
<select id="selectParma" parameterType="com.sslt.entity.User"resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user_t
where username = #{username,jdbcType=VARCHAR} and password = #{password,jdbcType=VARCHAR}
</select>
在controller中的UserController.java添加:
/**
* 跳转登录页面
* @param request
* @param model
* @return
*/
@RequestMapping(value = "/login")
public String login(HttpServletRequest request, Model model){
logger.info("跳转登录页面......");
return "login";
}
/**
* 用户登录处理
* @param request
* @param model
* @return
*/
@RequestMapping(value = "/userLogin")
public String userLogin(HttpServletRequest request, Model model){
String view = "";
User user = new User();
user.setUsername(request.getParameter("username"));
user.setPassword(request.getParameter("password"));
logger.info("登录请求成功......");
User userParma = userService.selectParma(user);
if (userParma != null) {
model.addAttribute("user", userParma);
model.addAttribute("message", "登录成功");
view = "success";
logger.info("用户登录成功数据:" + userParma);
} else {
model.addAttribute("message", "登录失败");
view = "error";
logger.info("登录失败......");
}
return view;
}
创建login.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">
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<title>登录</title>
</head>
<body>
<div class="col-md-6 col-md-offset-3">
<form role="form" action="userLogin" method="post">
<div class="form-group"></div>
<div class="form-group">
<label for="username">用户名</label>
<input type="text" class="form-control" name="username" id="username" value="" required />
</div>
<div class="form-group">
<label for="amount">密码</label>
<input type="password" class="form-control" name="password" id="password" value="" required />
</div>
<button type="submit" class="btn btn-primary ">登录</button>
</form>
</div>
</body>
</html>
创建成功页面success.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">
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<title>登录成功</title>
</head>
<body>
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-info">
<div class="panel-heading">操作结果</div>
<div class="panel-body">
<p style="word-break: break-word;">${message}</p>
</div>
</div>
<div class="panel panel-info">
<div class="panel-heading">返回具体参数</div>
<div class="panel-body">
<p style="word-break: break-word;">用户:${user.username}</p>
<p style="word-break: break-word;">年龄:${user.age}</p>
</div>
</div>
</div>
</body>
</html>
创建失败页面error.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">
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<title>登录失败</title>
</head>
<body>
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-info">
<div class="panel-heading">操作结果</div>
<div class="panel-body">
<p style="word-break: break-word;">${message}</p>
</div>
</div>
</div>
</body>
</html>
tomcat运行innersystem项目,在浏览器访问地址:http://127.0.0.1:8080/innersystem/user/login
输入用户名和密码,登录成功页面:
输入用户名和密码,登录失败页面:
(1)在CSDN下载地址:SSM框架整合源码下载(https://download.csdn.net/download/u013526643/12567084)
(2)百度云盘下载:
链接:https://pan.baidu.com/s/13BIJstfgQmO3oYIipidQeQ
提取码:1s02