Spring+SpringMVC+Mybatis实现简单的注册登录功能

由于最开始过于自信,想着一天的时间就能在一个干净的环境内(一个能上网的Windows10即可),从零开始利用Spring+SpringMVC+Mybatis(SSM)实现下简单的注册登录功能,由此基础实现更为复杂的功能。结果由于老眼昏花,中间还是踩了一些坑。其中某个笔误(少敲了一个字母)竟让我在网络上游荡了2天寻医问药还是徒劳而返,最后老老实实重新检查了所有配置文件才发现这个笔误。
提示:为了增加成功率,建议先严格按照我下面的步骤做出来一个成功的演示结果后,再按照自己的喜好修改。

闲话少絮,言归正传。

一、在敲代码之前,下载并安装了下面的软件:

1,JDK 1.8.0 Windows x64 点击打开下载链接(推荐下载最新小版本)
2,Apache Maven 3.5.2  点击打开下载链接
3,Apache Tomcat 7.0.86 64-bit Windows zip 点击打开下载链接
4,MySQL 5.7 Installer 点击打开下载链接 (推荐下载最新小版本)
5,Eclipse IDE for Java EE Oxygen Windows 64 bit 点击打开下载链接 (这里是清华大学镜像,你可以选择其他镜像下载)

二、安装完以上软件,进行了下面的配置:

1,环境变量
变量名 变量值
CATALINA_HOME D:\Programs\apache-tomcat-7.0.86
JAVA_HOME D:\Programs\Java\jdk1.8.0_71
CLASSPATH .;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.jar
M2_HOME D:\Programs\apache-maven-3.5.2
Path 手动添加:%JAVA_HOME%\bin;%M2_HOME%\bin;%CATALINA_HOME%\bin

2,Maven
1) 创建.m2文件夹
运行mvn help:system下载一些必要的依赖包和创建.m2文件夹( C:\Users\<登录用户>文件夹下面)。
2) 创建settings.xml配置文件
将Maven安装目录里的conf目录下的settings.xml配置文件拷贝到.m2目录里。
3) 修改 settings.xml配置文件的mirrors
在settings.xml配置文件的mirrors节点增加Aliyun镜像加快依赖包的下载速度:
  <mirror>
      <id>nexus</id>
      <mirrorOf>*</mirrorOf>
      <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
  </mirror>

3,Eclipse
1) 创建Workspace目录
创建目录D:\development\workspace_eclipse-jee-oxygen-2-win32-x86_64,在Eclipse第一次启动时候选择这个目录。
2) 关联JDK
Eclipse菜单Windows>Preferences,展开Java,选中Installed JREs,Add "Standard VM",选中JDK1.8.0_71的安装目录,返回后勾选为默认JRE环境。
3) 关联Tomcat
Eclipse菜单Windows>Preferences,展开Server,选中Runtime Environments,Add "Apache Tomcat v7.0",选中Tomcat 7.0.86的安装目录,返回后即可看到配好的运行时环境。

4,MySQL
1) 配置好root用户的密码,使用Service方式自动启动MySQL服务。
2) 使用MySQL Workbench创建链接用root用户登录到Hostname:localhost和Port:3306。
3) 运行下面SQL语句创建数据库、用户表,并且插入一些测试数据:
CREATE TABLE tbl_user
(
id int NOT NULL AUTO_INCREMENT,
user_name varchar(32) NOT NULL,
user_alias varchar(32),
passwd varchar(32) NOT NULL,
email varchar(32),
user_role varchar(32),
PRIMARY KEY (id)
);
INSERT INTO tbl_user(user_name, user_alias, passwd, email, user_role)
VALUES('admin', 'admin', 'admin', '[email protected]', 'sysadmin');
INSERT INTO tbl_user(user_name, user_alias, passwd, email, user_role)
VALUES('user01', 'user01', 'user01', '[email protected]', 'guest');

三、等了这么久,终于可以创建Web工程敲SSM代码了:

1,创建Maven Web工程
Ecliplse菜单File>New>Maven Project>Next>选择Artifact Id为maven-archetype-webapp的Archetype,Next(等待一段下载时间,如果这里报错,一般是网络问题或者settings.xml配置问题,修正好重做一遍即可)>Group Id: com.pitt,Artifact Id: ssm-demo,Package: com.pitt.ssm.demo,Finish。
2,添加以下Source Folder
src/main/java
src/main/resources
3,修改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.pitt</groupId>
	<artifactId>ssm-demo</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>ssm-demo Maven Webapp</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<spring.version>4.3.3.RELEASE</spring.version>
		<junit.version>4.12</junit.version>
		<aspectj.version>1.8.9</aspectj.version>
		<jackson.json.version>2.7.4</jackson.json.version>
		<fasterxml.jackson.version>2.7.4</fasterxml.jackson.version>
		<codehaus.woodstox.version>4.4.1</codehaus.woodstox.version>
	</properties>

	<dependencies>

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

		<!-- servlet / jstl / jsp -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>javax.servlet.jsp-api</artifactId>
			<version>2.3.1</version>
			<scope>provided</scope>
		</dependency>

		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.38</version>
		</dependency>

		<!-- spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</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-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-test</artifactId>
			<version>${spring.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>

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

		<!-- jackson xml -->
		<dependency>
			<groupId>com.fasterxml.jackson.dataformat</groupId>
			<artifactId>jackson-dataformat-xml</artifactId>
			<version>${fasterxml.jackson.version}</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.woodstox</groupId>
			<artifactId>woodstox-core-asl</artifactId>
			<version>${codehaus.woodstox.version}</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>5.2.4.Final</version>
		</dependency>

		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.2</version>
		</dependency>

		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>${aspectj.version}</version>
		</dependency>

		<!-- mybatis -->
		<dependency>
			<groupId>com.mchange</groupId>
			<artifactId>c3p0</artifactId>
			<version>0.9.5.2</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.4.1</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.3.0</version>
		</dependency>

		<!-- 日志 -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.7.21</version>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-core</artifactId>
			<version>1.1.7</version>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>1.1.7</version>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-access</artifactId>
			<version>1.1.7</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/commons-dbutils/commons-dbutils -->
		<dependency>
			<groupId>commons-dbutils</groupId>
			<artifactId>commons-dbutils</artifactId>
			<version>1.6</version>
		</dependency>

	</dependencies>

	<build>
		<finalName>ssm-demo</finalName>

		<!-- 这样也可以把所有的xml文件,打包到相应位置。 -->
		<resources>
			<resource>
				<directory>src/main/resources</directory>
				<includes>
					<include>**/*.properties</include>
					<include>**/*.xml</include>
					<include>**/*.tld</include>
				</includes>
				<filtering>false</filtering>
			</resource>
			<resource>
				<directory>src/main/java</directory>
				<includes>
					<include>**/*.properties</include>
					<include>**/*.xml</include>
					<include>**/*.tld</include>
				</includes>
				<filtering>false</filtering>
			</resource>
		</resources>

		<plugins>
			<!-- 利用MyBatis Generator自动创建实体类、映射文件以及DAO接口 -->
			<plugin>
				<groupId>org.mybatis.generator</groupId>
				<artifactId>mybatis-generator-maven-plugin</artifactId>
				<version>1.3.5</version>
				<configuration>
					<configurationFile>src/main/resources/generator.xml</configurationFile>
					<verbose>true</verbose>
					<overwrite>true</overwrite>
				</configuration>
				<dependencies>
					<dependency>
						<groupId>org.mybatis.generator</groupId>
						<artifactId>mybatis-generator-core</artifactId>
						<version>1.3.5</version>
					</dependency>
				</dependencies>
			</plugin>
		</plugins>
	</build>
</project>

4,修改SSM相关配置文件src/main/webapp/web.xml:
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4"
	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">
	<!-- <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 
		2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > -->

	<display-name>SSM Demo</display-name>

	<!-- 1.配置Spring核心监听器 -->
	<!-- 配置Spring上下文监听器,它的作用就是在启动WEB容器时,就会自动装在我们applicationContext.xml(或spring.xml)配置 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- 配置Spring的配置文件路径,好让ContextLoaderListener对其加载与解析 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath*:spring.xml</param-value>
	</context-param>

	<!-- 2.配置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:springmvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<!-- 映射所有请求给DispatcherServlet来处理 -->
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>*.action</url-pattern>
	</servlet-mapping>

	<!-- 配置Spring字符编码过滤器 -->
	<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>

	<!-- 配置欢迎页面 -->
	<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>
</web-app>

5,创建 SSM相关配置文件src/main/resources/spring.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: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/tx 
	http://www.springframework.org/schema/tx/spring-tx.xsd">
	
	<!--1.开启Spring ioc自动扫描注解包 -->
	<context:component-scan base-package="com.pitt.ssm.demo.service" />
	
	<!--2.引入propertise文件  -->
	<!--传统方式引入  -->
	<!-- <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
			<property name="locations" value="classpath:jdbc.properties"></property>
		 </bean> -->
	<!--简化方式  -->
	<context:property-placeholder location="classpath:jdbc.properties"/>	
	
	<!--3.配置数据源:c3p0  -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="${jdbc_driverClassName}" />
		<property name="jdbcUrl" value="${jdbc_url}" />
		<property name="user" value="${jdbc_username}" />
		<property name="password" value="${jdbc_password}" />
	</bean>
	
	<!--4.配置mybatis的SqlSession的工厂: SqlSessionFactoryBean dataSource:引用数据源 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"></property>
		<property name="mapperLocations" value="classpath*:com/pitt/ssm/demo/mapper/**/*.xml" />
		<property name="configLocation" value="classpath:mybatis-config.xml" />
	</bean>
	
	<!--5.自动扫描mybatis接口的包 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.pitt.ssm.demo.dao"></property>
	</bean>
	
	<!--6.配置事务管理器  -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	
	<!--7.开启注解进行事务管理   transaction-manager:引用上面定义的事务管理器-->
	<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
6,创建SSM相关配置文件src/main/resources/jdbc.properties:
jdbc_driverClassName=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/db_ssm_demo?useUnicode=true&characterEncoding=utf-8
jdbc_username=root
jdbc_password=root

7,创建SSM相关配置文件src/main/resources/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>
	<typeAliases>
		<typeAlias alias="User" type="com.pitt.ssm.demo.model.User" />
	</typeAliases>
</configuration>

8,创建SSM相关配置文件src/main/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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
	  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

	<!--1.开启Spring ioc自动扫描注解包 -->
	<context:component-scan base-package="com.pitt.ssm.demo.controller" />

	<!--2.开启注解 -->
	<mvc:annotation-driven />

	<!--3.配置视图解析器 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>

	<!--4.注解映射器(可省) -->
	<!-- <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean> -->

	<!--5.配置适配器(不需时可省) -->
	<!-- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 
		在业务方法的返回值和权限之间使用@ResponseBody注解表示返回值对象需要转成JSON文本 <property name="messageConverters"> 
		<list> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/> 
		</list> </property> </bean> -->
</beans>

9,创建利用MyBatis Generator自动创建实体类、映射文件以及DAO接口的相关配置文件src/main/resources/generator.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>
	<!-- 除了配置pom.xml并在Eclipse中运行maven build(goals填写mybatis-generator:generate),也可以在CMD命令行窗口运行java -jar mybatis-generator-core-1.3.2.jar -configfile generator.xml 
		-overwrite -->
	<!--1.数据库驱动包位置 -->
	<classPathEntry
		location="C:\Users\op051413\.m2\repository\mysql\mysql-connector-java\5.1.38\mysql-connector-java-5.1.38.jar" />
	<context id="DB2Tables" targetRuntime="MyBatis3">
		<commentGenerator>
			<property name="suppressAllComments" value="true" />
		</commentGenerator>
		<!--2.数据库链接URL、用户名、密码 -->
		<jdbcConnection driverClass="com.mysql.jdbc.Driver"
			connectionURL="jdbc:mysql://127.0.0.1:3306/db_ssm_demo" userId="root"
			password="root">
		</jdbcConnection>
		<javaTypeResolver>
			<property name="forceBigDecimals" value="false" />
		</javaTypeResolver>
		<!--3.生成实体类的包名和位置,这里配置将生成的实体类放在com.pitt.ssm.demo.model这个包下 -->
		<javaModelGenerator targetPackage="com.pitt.ssm.demo.model"
			targetProject="D:\development\workspace_eclipse-jee-oxygen-2-win32-x86_64\ssm-demo\src\main\java">
			<property name="enableSubPackages" value="true" />
			<property name="trimStrings" value="true" />
		</javaModelGenerator>
		<!--4.生成的SQL映射文件包名和位置,这里配置将生成的SQL映射文件放在com.pitt.ssm.demo.mapper这个包下 -->
		<sqlMapGenerator targetPackage="com.pitt.ssm.demo.mapper"
			targetProject="D:\development\workspace_eclipse-jee-oxygen-2-win32-x86_64\ssm-demo\src\main\java">
			<property name="enableSubPackages" value="true" />
		</sqlMapGenerator>
		<!--5.生成DAO的包名和位置,这里配置将生成的dao类放在com.pitt.ssm.demo.dao这个包下 -->
		<javaClientGenerator type="XMLMAPPER"
			targetPackage="com.pitt.ssm.demo.dao"
			targetProject="D:\development\workspace_eclipse-jee-oxygen-2-win32-x86_64\ssm-demo\src\main\java">
			<property name="enableSubPackages" value="true" />
		</javaClientGenerator>
		<!--6.要生成那些表(更改tableName和domainObjectName就可以) -->
		<table tableName="tbl_user" domainObjectName="User"
			enableCountByExample="false" enableUpdateByExample="false"
			enableDeleteByExample="false" enableSelectByExample="false"
			selectByExampleQueryId="false" />
	</context>
</generatorConfiguration>
10,在Eclipse菜单Run>Run Configurations>选中Maven Build,新建:
Name:mybatis-generator_generate
Base directory:${workspace_loc:/ssm-demo}
Goals:mybatis-generator:generate
点击Apply以及Run,开始自动生成相关代码。

11,检查src/main/java/com.pitt.ssm.demo.model.User.java:
package com.pitt.ssm.demo.model;

public class User {
    private Integer id;

    private String userName;

    private String userAlias;

    private String passwd;

    private String email;

    private String userRole;

    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 getUserAlias() {
        return userAlias;
    }

    public void setUserAlias(String userAlias) {
        this.userAlias = userAlias == null ? null : userAlias.trim();
    }

    public String getPasswd() {
        return passwd;
    }

    public void setPasswd(String passwd) {
        this.passwd = passwd == null ? null : passwd.trim();
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email == null ? null : email.trim();
    }

    public String getUserRole() {
        return userRole;
    }

    public void setUserRole(String userRole) {
        this.userRole = userRole == null ? null : userRole.trim();
    }
}
12, 检查并修改src/main/java/com.pitt.ssm.demo.dao.UserMapper.java:
package com.pitt.ssm.demo.dao;

import org.apache.ibatis.annotations.Param;

import com.pitt.ssm.demo.model.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);
    
    User findUserByNameAndPwd(@Param("userName")String userName, @Param("passwd")String passwd);
    
    User findByUserName(String userName);
}
13, 检查并修改src/main/java/com.pitt.ssm.demo.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.pitt.ssm.demo.dao.UserMapper">
	<resultMap id="BaseResultMap" type="User">
		<id column="id" jdbcType="INTEGER" property="id" />
		<result column="user_name" jdbcType="VARCHAR" property="userName" />
		<result column="user_alias" jdbcType="VARCHAR" property="userAlias" />
		<result column="passwd" jdbcType="VARCHAR" property="passwd" />
		<result column="email" jdbcType="VARCHAR" property="email" />
		<result column="user_role" jdbcType="VARCHAR" property="userRole" />
	</resultMap>
	<sql id="Base_Column_List">
		id, user_name, user_alias, passwd, email, user_role
	</sql>
	<select id="selectByPrimaryKey" parameterType="java.lang.Integer"
		resultMap="BaseResultMap">
		select
		<include refid="Base_Column_List" />
		from tbl_user
		where id = #{id}
	</select>
	<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
		delete from tbl_user
		where id = #{id}
	</delete>
	<insert id="insert" parameterType="User">
		insert into tbl_user (id, user_name, user_alias, passwd,
		email, user_role)
		values (#{id}, #{userName}, #{userAlias}, #{passwd},
		#{email}, #{userRole})
	</insert>
	<insert id="insertSelective" parameterType="User">
		insert into tbl_user
		<trim prefix="(" suffix=")" suffixOverrides=",">
			<if test="id != null">
				id,
			</if>
			<if test="userName != null">
				user_name,
			</if>
			<if test="userAlias != null">
				user_alias,
			</if>
			<if test="passwd != null">
				passwd,
			</if>
			<if test="email != null">
				email,
			</if>
			<if test="userRole != null">
				user_role,
			</if>
		</trim>
		<trim prefix="values (" suffix=")" suffixOverrides=",">
			<if test="id != null">
				#{id},
			</if>
			<if test="userName != null">
				#{userName},
			</if>
			<if test="userAlias != null">
				#{userAlias},
			</if>
			<if test="passwd != null">
				#{passwd},
			</if>
			<if test="email != null">
				#{email},
			</if>
			<if test="userRole != null">
				#{userRole},
			</if>
		</trim>
	</insert>
	<update id="updateByPrimaryKeySelective" parameterType="User">
		update tbl_user
		<set>
			<if test="userName != null">
				user_name = #{userName},
			</if>
			<if test="userAlias != null">
				user_alias = #{userAlias},
			</if>
			<if test="passwd != null">
				passwd = #{passwd},
			</if>
			<if test="email != null">
				email = #{email},
			</if>
			<if test="userRole != null">
				user_role = #{userRole},
			</if>
		</set>
		where id = #{id,jdbcType=INTEGER}
	</update>
	<update id="updateByPrimaryKey" parameterType="User">
		update tbl_user
		set user_name = #{userName},
		user_alias = #{userAlias},
		passwd = #{passwd},
		email = #{email},
		user_role = #{userRole}
		where id = #{id}
	</update>
	<select id="findUserByNameAndPwd" resultType="User">
		select * from tbl_user
		where user_name=#{userName} and passwd=#{passwd}
	</select>
    <select id="findByUserName" resultType="User">
        select * from tbl_user where user_name=#{userName}
    </select>
</mapper>
14,新建 src/main/java/com.pitt.ssm.demo.service.UserService.java:
package com.pitt.ssm.demo.service;

import com.pitt.ssm.demo.model.User;

public interface UserService {
	// 用户注册
	void register(User user);
	
	// 用户登录
	User login(String userName, String passwd);
	 
	// 根据用户名查询
	User findByUserName(String userName);
}

15, 新建 src/main/java/com.pitt.ssm.demo.service.impl.UserServiceImpl.java:
package com.pitt.ssm.demo.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.pitt.ssm.demo.dao.UserMapper;
import com.pitt.ssm.demo.model.User;
import com.pitt.ssm.demo.service.UserService;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;
	
	// @Override
	public void register(User user) {
		userMapper.insert(user);
	}

	// @Override
	public User login(String userName, String passwd) {
		User user = userMapper.findUserByNameAndPwd(userName, passwd);
		if (user != null) {
            return user;
        }
        return null;
	}
	
	// @Override
	public User findByUserName(String userName) {
		return userMapper.findByUserName(userName);
	}
}

16, 新建 src/main/java/com.pitt.ssm.demo.controller.UserController.java:
package com.pitt.ssm.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
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 com.pitt.ssm.demo.model.User;
import com.pitt.ssm.demo.service.UserService;

/**
 * 控制层
 * 
 * @author Pitt
 *
 */
@Controller
@Scope("prototype")
@RequestMapping("/user")
public class UserController {
	// 注入Service
	@Autowired
	private UserService userService;

	@RequestMapping(value = "/register.action", method = RequestMethod.POST)
	public String register(User user, Model model) {
		String username = user.getUserName();
		// 如果数据库中没有该用户,可以注册,否则跳转页面
		if (userService.findByUserName(username) == null) {
			// 添加用户
			userService.register(user);
			model.addAttribute("msg", "注册成功");
			// 注册成功跳转到主页面
			return "register_success";
		} else {
			model.addAttribute("msg", "注册失败");
			// 注册失败跳转到错误页面
			return "register_failure";
		}

	}

	@RequestMapping(value = "/login.action", method = RequestMethod.POST)
	public String login(String userName, String passwd, Model model) {
		System.out.println("用户登录:" + userName + "," + passwd);

		String page = "";

		User user2 = userService.login(userName, passwd);
		if (user2 != null) {
			model.addAttribute("msg", "登录成功");
			page = "login_success";
		} else {
			model.addAttribute("msg", "登录失败");
			page = "login_failure";
		}

		return page;
	}
}
17,修改 src/main/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>SSM Demo</title>
	</head>
	<body>
		<h2>SSM(Spring+SpringMVC+MyBatis)框架项目实例演示!</h2>
		<a href="${pageContext.request.contextPath}/register.jsp">注册</a>
		<a href="${pageContext.request.contextPath}/login.jsp">登录</a>
	</body>
</html>
18,新建 src/main/webapp/register.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>
	<form action="${pageContext.request.contextPath}/user/register.action" method="post">
		<table border="1">
			<tr>
				<td>用户名</td>
				<td><input type="text" name="userName"></td>
			</tr>
			<tr>
				<td>昵称</td>
				<td><input type="text" name="userAlias"></td>
			</tr>
			<tr>
				<td>密码</td>
				<td><input type="text" name="passwd"></td>
			</tr>
			<tr>
				<td>邮件地址</td>
				<td><input type="text" name="email"></td>
			</tr>
			<tr>
				<td>角色</td>
				<td><input type="text" name="userRole"></td>
			</tr>
			<tr>
				<td><input type="submit" value="注册"></td>
			</tr>
		</table>
	</form>
</body>
</html>

19,新建 src/main/webapp/register_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">
		<title>注册成功</title>
	</head>
	<body>
		${msg}<br/>
		<a href="${pageContext.request.contextPath}/register.jsp">再注册一个新用户</a>
	</body>
</html>

20 ,新建 src/main/webapp/register_failure.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>
		${msg}<br/>
		<a href="${pageContext.request.contextPath}/register.jsp">不放弃,再去尝试注册</a>
	</body>
</html>

21 ,新建 src/main/webapp/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">
	<title>用户登录</title>
</head>
<body>
	<form action="${pageContext.request.contextPath}/user/login.action" method="post">
		<table border="1">
			<tr>
				<td>用户名</td>
				<td><input type="text" name="userName"></td>
			</tr>
			<tr>
				<td>密码</td>
				<td><input type="text" name="passwd"></td>
			</tr>
			<tr>
				<td><input type="submit" value="登录"></td>
			</tr>
		</table>
	</form>
</body>
</html>

22 ,新建 src/main/webapp/login_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">
		<title>登录成功</title>
	</head>
	<body>
		${msg}<br/>
		<a href="${pageContext.request.contextPath}/login.jsp">换个用户登录</a>
	</body>
</html>

23 ,新建 src/main/webapp/login_failure.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>
		${msg}<br/>
		<a href="${pageContext.request.contextPath}/login.jsp">登录失败,再去登录</a>
	</body>
</html>
24,在Eclipse菜单Run>Run Configurations>选中Maven Build,新建:
Name:ssm-demo_package
Base directory:${workspace_loc:/ssm-demo}
Goals:clean package
点击Apply以及Run,开始生成ssm-demo.ware在D:\development\workspace_eclipse-jee-oxygen-2-win32-x86_64\ssm-demo\target目录。

25,启动Tomcat,将ssm-demo.war拷贝到D:\Programs\apache-tomcat-7.0.86\webapps目录。

26,启动浏览器,在地址栏输入http://localhost:8080/ssm-demo,开始享受成功的喜悦吧~

发布了22 篇原创文章 · 获赞 8 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/csdn_zf/article/details/80234936