利用SpringMVC+hibernate实现注册登录功能

1 篇文章 1 订阅

如何利用SpringMVC+Hibernate实现注册于登录
首先创建maven项目选择war包
(1)项目结构大体
在这里插入图片描述
项目所需的jar包

1.2.17
1.3.1
1.16.10

<dependencies>

	<dependency>
		<groupId>junit</groupId>
		<artifactId>junit</artifactId>
		<version>4.12</version>
		<scope>test</scope>
	</dependency>

	<!-- 引入Servlet的依赖 -->
	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>javax.servlet-api</artifactId>
		<version>4.0.0</version>
		<scope>provided</scope>
	</dependency>
	<!-- spring -->
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-beans</artifactId>
		<version>4.3.10.RELEASE</version>
	</dependency>

	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-core</artifactId>
		<version>4.3.10.RELEASE</version>
	</dependency>


	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-context</artifactId>
		<version>4.3.10.RELEASE</version>
	</dependency>

	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-orm</artifactId>
		<version>4.3.10.RELEASE</version>
	</dependency>

	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-web</artifactId>
		<version>4.3.10.RELEASE</version>
	</dependency>
	<!-- spring mvc -->
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-webmvc</artifactId>
		<version>4.3.3.RELEASE</version>
	</dependency>
	<!-- 引入c3p0数据库连接池 -->
	<dependency>
		<groupId>com.mchange</groupId>
		<artifactId>c3p0</artifactId>
		<version>0.9.5.2</version>
	</dependency>
	<!-- 引入 Mysql依赖 -->
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>5.1.43</version>
	</dependency>
	<!-- 引入Hibernate依赖 -->
	<dependency>
		<groupId>org.hibernate</groupId>
		<artifactId>hibernate-core</artifactId>
		<version>5.2.10.Final</version>
	</dependency>

	<!-- 引入Sprig-orm依赖 -->
	<!-- Spring整合Hibernate依赖 -->
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-orm</artifactId>
		<version>4.3.10.RELEASE</version>
	</dependency>
	<!-- spring 的AspectJ依赖,解析事务切点 -->
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-aspects</artifactId>
		<version>4.3.10.RELEASE</version>
	</dependency>
	<!-- 日志依赖 -->
	<dependency>
		<groupId>org.apache.logging.log4j</groupId>
		<artifactId>log4j-core</artifactId>
		<version>2.2</version>
	</dependency>

	<!--jackson依赖 -->
	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-databind</artifactId>
		<version>2.9.1</version>
	</dependency>
	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-core</artifactId>
		<version>2.9.1</version>
	</dependency>
	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-annotations</artifactId>
		<version>2.9.1</version>
	</dependency>

	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>jstl</artifactId>
		<version>1.2</version>
		<scope>runtime</scope>
	</dependency>


</dependencies>

(2)首先看下web.xml
Book_ssh

/index.jsp


contextConfigLocation

classpath:META-INF/applicationContext.xml



spring
org.springframework.web.servlet.DispatcherServlet

contextConfigLocation
classpath:META-INF/spring-mvc.xml

1


spring
/


org.springframework.web.context.ContextLoaderListener


encodingFilter
org.springframework.web.filter.CharacterEncodingFilter

encoding
UTF-8


forceEncoding
true



encodingFilter
/*



YanzhengmaServlet
YanzhengmaServlet
cn.com.servlet.YanzhengmaServlet


YanzhengmaServlet
/yanzhengma

接着看下applicationContext.xml中的配置

<!--配置Spring->
    <!-- 自动扫描 -->
    <mvc:annotation-driven />
    <context:component-scan base-package="cn.com">
        <!-- 扫描时跳过 @Controller 注解的JAVA类(控制器) -->
<!--配置hibernate-->

<!--扫描配置文件(这里指向的是之前配置的那个config.properties)-->
<context:property-placeholder location="classpath:META-INF/config.properties" />

<!--配置数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
    <property name="driverClass" value="${jdbc.driver}" />  <!--数据库连接驱动-->
    <property name="jdbcUrl" value="${jdbc.url}" />     <!--数据库地址-->
    <property name="user" value="${jdbc.username}" />   <!--用户名-->
    <property name="password" value="${jdbc.password}" />   <!--密码-->
    <property name="maxPoolSize" value="40" />      <!--最大连接数-->
    <property name="minPoolSize" value="1" />       <!--最小连接数-->
    <property name="initialPoolSize" value="10" />      <!--初始化连接池内的数据库连接-->
    <property name="maxIdleTime" value="20" />  <!--最大空闲时间-->
</bean>

<!--配置session工厂-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan" value="cn.com.entity" />
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <!--hibernate根据实体自动生成数据库表-->
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>   <!--指定数据库方言-->
            <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>     <!--在控制台显示执行的数据库操作语句-->
            <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>     <!--在控制台显示执行的数据哭操作语句(格式)-->
        </props>
    </property>
</bean>

<!-- 事物管理器配置  -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

config.properties的文件配置
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/emp?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=123123
#hibernate config
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.format_sql = true
hibernate.hbm2ddl.auto = update

在spring-mvc.xml中的配置

<!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="views/" />      <!-- 前缀 -->
    <property name="suffix" value=".jsp" />   <!-- 后缀 -->
</bean>


<!--这里是对静态资源的映射-->
<mvc:resources mapping="/js/**" location="/resources/js/" />
<mvc:resources mapping="/css/**" location="/resources/css/" />
<mvc:resources mapping="/img/**" location="/resources/img/" />

在TUser.hbm.xml配置
是POJO与数据的字段相对应

<?xml version="1.0" encoding="UTF-8"?>

创建数据emp
创建表t_user
create database emp;
use emp;
create table t_user(
id int primary key auto_increment,
username varchar(20) not null,
password varchar(20)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

实体类
package cn.com.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = “t_user”)
public class TUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private String id ;
@Column(name = “username”)
private String userName;
@Column(name = “password”)
private String passWord;

public TUser() {
	super();
}

public String getId() {
	return id;
}

public void setId(String 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;
}

@Override
public String toString() {
	return "TUser [id=" + id + ", userName=" + userName + ", passWord=" + passWord + "]";
}	

}

dao层
package cn.com.dao.impl;

import java.io.Serializable;
import java.util.List;

public interface TUserDAO <T,PK extends Serializable>{
T load(PK id);

    T get(PK id);
    
    T get (String username);
    
    void persist(T entity);

    PK save(T entity);

    void saveOrUpdate(T entity);

    void delete(PK id);

    void flush();

}

TUserDAOPositroy类中继承TUserDAO 写出泛型类型
package cn.com.dao.impl;

import cn.com.entity.TUser;

public interface TUserDAOPositroy extends TUserDAO<TUser,String>{

}

实现dao层
TUserDaoImpl类
package cn.com.dao.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import cn.com.dao.impl.TUserDAOPositroy;
import cn.com.entity.TUser;

@Repository
public class TUserDaoImpl implements TUserDAOPositroy {
@Autowired
private SessionFactory sessionFactory;

private Session getCurrentSession() {
	return this.sessionFactory.openSession();
}

public TUser load(String id) {
	return (TUser)getCurrentSession().get(TUser.class,id);
}


public void persist(TUser entity) {
	getCurrentSession().persist(entity);

}

public String save(TUser entity) {
	return (String)getCurrentSession().save(entity);
}

public void saveOrUpdate(TUser entity) {
	getCurrentSession().saveOrUpdate(entity);

}

public void delete(String id) {
	TUser tUser = load(id);
	getCurrentSession().delete(tUser);
}

public void flush() {
	getCurrentSession().flush();
}

public TUser get(String username) {
    return (TUser) this.getCurrentSession().createQuery("from TUser where username=?").setParameter(0, username).uniqueResult();

}

}

业务层service

TUserService接口定义方法
package cn.com.service.impl;

import cn.com.entity.TUser;

public interface TUserService {

public void save(TUser tUser);


TUser get(String username);

}
实现接口TUserServiceImpl
package cn.com.service.impl;

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

import cn.com.dao.impl.TUserDAO;
import cn.com.entity.TUser;

@Service
public class TUserServiceImpl implements TUserService{

@Autowired
private TUserDAO<TUser, ?> tUserDao;


public void save(TUser tUser) {
	tUserDao.save(tUser);
}


public TUser get(String username){
	return tUserDao.get(username);
}

}

控制器层Controller
TUserController
package cn.com.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.com.entity.TUser;
import cn.com.service.impl.TUserService;

@Controller
public class TUuseController {

@Autowired
private TUserService tUserService;

@RequestMapping(value="/save.do")
public String save(HttpServletRequest request,HttpServletResponse response){

	return "regit";
}
@RequestMapping("/add.do")
public String add(HttpServletRequest request,HttpServletResponse response ,TUser tUser){
	tUser.setUserName(request.getParameter("username"));
	tUser.setPassWord(request.getParameter("password"));
	//	tUser.setId(UUID.randomUUID().toString().replaceAll("-","").substring(10));
	tUserService.save(tUser);
	return "success";
}

@RequestMapping("/login.do")
public String login(HttpServletRequest request,HttpServletResponse response) throws Exception{
	
	return "login";
}
@RequestMapping("log.do")
public String log(HttpServletRequest request,HttpServletResponse response) {
	String username = request.getParameter("username");
	String password = request.getParameter("password");
	String check = request.getParameter("check");
	TUser tUser= tUserService.get(username);
	String checked = (String) request.getSession().getAttribute("Check");
	if(!checked.equals(check)){
		request.getSession().setAttribute("yanzhengma", "你输入的验证码有误请重新输入");
	}
	if(tUser == null){
		request.getSession().setAttribute("dd", "用户名或密码有误!");
		System.err.println("username is null");
		return "login";
	}
	
	if(username.equals(tUser.getUserName())){
		if(password.equals(tUser.getPassWord())){
			if(checked.equals(check)){
				request.getSession().setAttribute("tUser", tUser);
				return "success";		
			}
		}
	}

	return "login";
}

}

注册页面
regit.jsp
<%@ page language=“java” contentType=“text/html; charset=utf8”
pageEncoding=“utf8”%>

用户注册
	</table>
</form>
用户名:
密码:
去登陆

接着登录页面
login.jsp
<%@ page language=“java” contentType=“text/html; charset=utf8”
pageEncoding=“utf8”%>
<%@ page import=“cn.com.entity.*” %>

Insert title here <%String dd = (String)request.getSession().getAttribute("dd");%>
			<td><p  style="color: red; " ><%=dd == null ? "" : dd %>	</p></td>
			
		</tr>
		<tr>
			<td>密码:</td>
			<td><input type="password" name="password"></td>
		</tr>
		<tr>
		<td>验证码:</td>
		<td><input type="text" name="check" ></td>
		<td><img  src="yanzhengma"  onclick="getcheckd(this)" > </td>
		<%String yanzhengma = (String)request.getSession().getAttribute("yanzhengma");%>

		<td><p  style="color: red; " ><%=yanzhengma == null ? "" : yanzhengma %>	</p></td>
		</tr>
		<tr>
			<td><a href="add.do">去注册</a></td>
			<td colspan="2" align="center"><input type="submit" value="登录"></td>
		</tr>
	</table>
</form>
用户名:

验证码功能
利用一个的Servlet的service方法
作为访问路径
package cn.com.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class YanzhengmaServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	//获取宽度
	int width = 80;
	//获取高度
	int height = 30;
	//获取缓冲图片
	BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
	//获取画笔
	Graphics g = image.getGraphics();
	//设置画笔颜色
	g.setColor(Color.pink);
	//填充图片
	g.fillRect(0, 0, width, height);
	//接收验证码
	String check =  check();
	//将接收的数据放入session中
	request.getSession().setAttribute("Check", check);
	//设置画笔的颜色
	g.setColor(Color.blue);
	//设置字体
	g.setFont(new Font("宋体",Font.BOLD, 20));
	//将
	g.drawString(check, 5, 25);

	ImageIO.write(image, "PNG", response.getOutputStream());



}

public String check(){
	//定义验证的大小
	String base = "0123456789QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnnm";
	//定义长度
	int size = base.length();
	//获取随机数
	Random ran = new Random();
	//获取流
	StringBuilder sb = new StringBuilder();

	for(int i = 1;i<=4;i++){
		int index = ran.nextInt(size);
		char c = base.charAt(index);
		sb.append(c);
	}

	return sb.toString();
}

}
注册的界面:
在这里插入图片描述

登陆的界面:
在这里插入图片描述
页面不美观请自行调整。

本人也是第一次发,代码仅供个人参考,不喜欢勿喷。

  • 2
    点赞
  • 2
    评论
  • 5
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

评论 2 您还未登录,请先 登录 后发表或查看评论
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页

打赏作者

liu

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值