SpringMVC+Spring+Mybatis实现登录注册Demo

Posted 明金同学

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringMVC+Spring+Mybatis实现登录注册Demo相关的知识,希望对你有一定的参考价值。

使用环境:MyEclipse/Eclipse + Tomcat + mysql

使用技术:SpringMVC + Spring + Mybatis。

实现效果

登录页面:

密码错误提示

登录成功后

注册

注册成功

目录结构

一、配置文件

beans.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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jee="http://www.springframework.org/schema/jee"
    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/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee
        http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
    
    <!-- 自动扫描 -->
    <context:component-scan base-package="com.java.dao"></context:component-scan>  
    <context:component-scan base-package="com.java.service"></context:component-scan>  
    <context:component-scan base-package="com.java.serviceimpl"></context:component-scan>
    
  <!-- 配置mysql连接 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <context:property-placeholder location="classpath:/jdbc.properties"/>
    
   <!-- 配置mybatis的SQLSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    	<property name="dataSource" ref="dataSource"></property>
    	<!-- 自动扫描mappers.xml文件 -->
    	<property name="mapperLocations" value="classpath:com/java/mappers/*.xml"></property>
    	<!-- mybatis配置文件 -->
    	<property name="configLocation" value="classpath:mybatis-config.xml "></property>
    </bean>
	
	<!-- spring自动查找其下的类 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.java.dao"></property>
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
	</bean>  
	
</beans>

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>
		<!-- 对entity下的实体类起个别名,起到简化的作用 -->
		<typeAliases>
			<package name="com.java.entity"></package>
		</typeAliases>
</configuration>

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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jee="http://www.springframework.org/schema/jee"
    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/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee
        http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
        
    	<!-- 使用注解的包,包括子集    --> 
	<context:component-scan base-package="com.java.controller"/>
	
		<!-- 视图解析器 -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
	</bean>
	
</beans>

jdbc.properties

jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_student?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC
jdbc.username=root
jdbc.password=root

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
					http://www.springmodules.org/schema/cache/springmodules-cache.xsd
					http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd" 
		 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"
		 id="WebApp_ID" version="2.5">
		 
	<display-name>mybatis06-spring-springmvc</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

<!-- 对spring的支持   -->
  <context-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>classpath:beans.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> 
       <init-param> 
           <param-name>forceEncoding</param-name> 
           <param-value>true</param-value> 
       </init-param> 
   </filter> 
   <filter-mapping> 
       <filter-name>characterEncodingFilter</filter-name> 
       <url-pattern>/*</url-pattern> 
   </filter-mapping> 
   
  	<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
  
<!-- 对springmvc的支持   -->
    <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>
  	<async-supported>true</async-supported>
  </servlet>
  <servlet-mapping>
  	<servlet-name>springmvc</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  

</web-app>

二、Java代码

1、com.java.entity

User.java

package com.java.entity;

public class User {

	private Integer id;
	private String userName;
	private String passWord;
	
	// 无参构造
	public User() {
		super();
	}
	
	// 全参构造
	public User(String userName, String passWord) {
		super();
		this.userName = userName;
		this.passWord = passWord;
	}
	
	//get、set方法
	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;
	}
	public String getPassWord() {
		return passWord;
	}
	public void setPassWord(String passWord) {
		this.passWord = passWord;
	}
	
	// toString方法
	@Override
	public String toString() {
		return "User [id=" + id + ", userName=" + userName + ", passWord=" + passWord + "]";
	}
	
	
}

2、com.java.dao

UserDao.java

package com.java.dao;

import com.java.entity.User;

public interface UserDao {

	public User login(User user);
	
	public User add(User user);
	
}

3、com.java.mappers

user.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.java.dao.UserDao">
	
 	<resultMap type="com.java.entity.User" id="UserResult">
 		<id property="id" column="id"></id>
 		<result property="userName" column="userName"></result>
 		<result property="passWord" column="passWord"></result>
 	</resultMap>
 	
 	<select id="login" parameterType="com.java.entity.User" resultMap="UserResult">
 		select * from user where userName=#{userName} and passWord=#{passWord}
 	</select>
 	
 	<select id="add" parameterType="com.java.entity.User" resultMap="UserResult">
 		insert into user (userName,passWord) values(#{userName},#{passWord})
 	</select>

</mapper>  

4、com.java.controller

UserController.java

package com.java.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.java.entity.User;
import com.java.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {

	@Resource
	private UserService userService;
	
	@RequestMapping("/login")
	public String login(User user,HttpServletRequest request) {
		User resultUser=userService.login(user);
		System.out.println(resultUser);
		if(resultUser==null) {
			request.setAttribute("user", user);
			request.setAttribute("errorMsg", "用户名或密码错误!");
			return "index";
		}else {
			HttpSession session=request.getSession();
			session.setAttribute("currentUser", resultUser);
			return "welcome";
		}
	}
	
	@RequestMapping("/add")
	public String add(HttpServletRequest request,HttpServletResponse response){
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		String username=request.getParameter("userName");
		String password=request.getParameter("passWord");
		User users=new User(username, password);
		userService.add(users);
		return "reback";
	}
		
}

5、com.java.service

UserService.java

package com.java.service;

import com.java.entity.User;

public interface UserService {

	public User login(User user);
	
	public User add(User user);
}

6、com.java.serviceimpl

ServiceImpl.java

package com.java.serviceimpl;

import javax.annotation.Resource;

import org以上是关于SpringMVC+Spring+Mybatis实现登录注册Demo的主要内容,如果未能解决你的问题,请参考以下文章

Spring+SpringMVC+Mybatis+Mysql整合实例

Spring+SpringMVC+Mybatis+Mysql整合实例

Spring+SpringMVC+Mybatis+Mysql整合实例

SpringMVC——Spring整合Mybatis和SpringMVC

SpringMVC学习--springmvc和mybatis整合

Spring+SpringMVC+MybatisSpring+SpringMVC+Mybatis实现前端到后台完整项目