SpringMVC+Spring+Mybatis实现登录注册Demo「建议收藏」

SpringMVC+Spring+Mybatis实现登录注册Demo「建议收藏」使用环境:MyEclipse/Eclipse+Tomcat+MySql。使用技术:SpringMVC+Spring+Mybatis。实现效果登录页面:密码错误提示登录成功后注册注册成功目录结构一、配置文件beans.xml<?xmlversion=”1.0″encoding=”UTF-8″?><beansxmlns=”http://www.springframework.org/schema/beans”xmlns:x.

大家好,又见面了,我是你们的朋友全栈君。

使用环境: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.springframework.stereotype.Service;

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

@Service("userService")
public class ServiceImpl implements UserService{ 
   

	@Resource
	private UserDao userDao;
	
	public User login(User user) { 
   
		return userDao.login(user);
	}

	public User add(User user) { 
   
		return userDao.add(user);
	}

}

三、Jsp页面代码

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="add.jsp">注册</a>&nbsp;<br/>
<form action="${pageContext.request.contextPath}/user/login.do" method="post">
	userName:<input type="text" name="userName" value="${userName}"/><br/>
	passWord:<input type="password" name="passWord" value="${passWord}"/><br/>
	<input type="submit" value="登录"/><br/>
	<font color="red">${errorMsg}</font>
</form>
</body>
</html>

welcome.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>
欢迎   ${currentUser.userName} 来到我们的世界!
</body>
</html>

reback.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>
<script> function fun(){ 
      alert("确认返回登录页面"); /* location.href ="http://localhost:8080/mybatis06-spring-springmvc/index.jsp"; */ window.history.go(-2); } </script>
</head>
<body>
<input type="button" value="注册成功,返回登录页面" onclick="fun()"/>

</body>
</html>

add.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>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user/add.do" method="post">
	userName:<input type="text" name="userName"/>
	passWord:<input type="password" name="passWord"><br/>
	<input type="submit" value="注册" />
</form>
</body>
</html>
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/132534.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • hdu 4861 Couple doubi(数论)

    hdu 4861 Couple doubi(数论)

  • Java常见设计模式总结

    Java常见设计模式总结

  • Python中lambda表达式学习

    Python中lambda表达式学习lambda只是一个表达式,函数体比def简单很多。lambda的主体是一个表达式,而不是一个代码块。仅仅能在lambda表达式中封装有限的逻辑进去。lambda表达式是起到一个函数速写的作用。允许在代码内嵌入一个函数的定义。如下例子:定义了一个lambda表达式,求三个数的和。再看一个例子:用lambda表达式求n的阶乘。——————-

    2022年10月18日
  • C++类和对象数组[通俗易懂]

    C++类和对象数组[通俗易懂]C++类和对象数组【1】对象数组1:对象数组的定义:类名数组名[元素个数]Eg:studentasa[10];//有10个元素的学生类对象数组2:对象数组的访问形式:数组名[下标].成员名;Eg:asa[j].print();3:对象数组的初始化:对象数组的初始化通常也是由构造函数来完成的。Eg:#include”student.h”intmain{…

  • IDEA快捷键设置-设置成和Eclipse一样「建议收藏」

    IDEA快捷键设置-设置成和Eclipse一样「建议收藏」用惯了eclipse的同学可能会对IDEA的快捷键不习惯,所以这里打包了一份eclipse中快捷键的设置。直接导入IDEA就可以使用。链接:https://pan.baidu.com/s/1FmXOQeqy6RxfD05mKdq3dQ提取码:c0px…

  • Python 生成随机数_python 随机字符串

    Python 生成随机数_python 随机字符串python中生成随机数主要使用random模块和numpy库中的random函数。前者主要用于生成随机数和实现序列中随机数和随机数列的挑选,后者用来生成a*b维的随机矩阵。一、random模块random模块中将近有7个函数都是可以用来生成随机数,列举如下:1.random.random()功能:随机生成一个[0,1)的浮点数示例:importrandomnumber=random.random()print(number)print(‘%.2f’%num

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号