如何利用SpringMVC+Hibernate实现注册于登录
首先创建maven项目选择war包
(1)项目结构大体
项目所需的jar包
1.2.17
1.3.1
1.16.10
junit
junit
4.12
test
javax.servlet
javax.servlet-api
4.0.0
provided
org.springframework
spring-beans
4.3.10.RELEASE
org.springframework
spring-core
4.3.10.RELEASE
org.springframework
spring-context
4.3.10.RELEASE
org.springframework
spring-orm
4.3.10.RELEASE
org.springframework
spring-web
4.3.10.RELEASE
org.springframework
spring-webmvc
4.3.3.RELEASE
com.mchange
c3p0
0.9.5.2
mysql
mysql-connector-java
5.1.43
org.hibernate
hibernate-core
5.2.10.Final
org.springframework
spring-orm
4.3.10.RELEASE
org.springframework
spring-aspects
4.3.10.RELEASE
org.apache.logging.log4j
log4j-core
2.2
com.fasterxml.jackson.core
jackson-databind
2.9.1
com.fasterxml.jackson.core
jackson-core
2.9.1
com.fasterxml.jackson.core
jackson-annotations
2.9.1
javax.servlet
jstl
1.2
runtime
(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中的配置
${hibernate.hbm2ddl.auto}
${hibernate.dialect}
${hibernate.show_sql}
${hibernate.format_sql}
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中的配置
在TUser.hbm.xml配置
是POJO与数据的字段相对应
创建数据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 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
}
实现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 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”%>
用户名: | ||
密码: | ||
去登陆 |
接着登录页面
login.jsp
<%@ page language=“java” contentType=“text/html; charset=utf8”
pageEncoding=“utf8”%>
<%@ page import=“cn.com.entity.*” %>
<%=dd == null ? "" : dd %>
密码:
验证码:
<%String yanzhengma = (String)request.getSession().getAttribute("yanzhengma");%>
<%=yanzhengma == null ? "" : yanzhengma %>
去注册
用户名: |
验证码功能
利用一个的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();
}
本人也是第一次发,代码仅供个人参考,不喜欢勿喷。