Struts 2+Hibernate实现完整登录注册(带验证)

Struts 2+Hibernate实现完整登录注册

Struts 2+Hibernate实现完整登录注册(带验证)_第1张图片

Struts 2+Hibernate实现完整登录注册(带验证)_第2张图片

环境

MyEclipse 2014
数据库:SQL sever 2016
Tomcat:apache-tomcat-8.0.46
JDK:1.6
Sturts版本:2.1
Hibernate版本:4.1

前期准备

Struts 2+Hibernate实现完整登录注册(带验证)_第3张图片

创建项目以后,为项目添加SturtsHibernate能力

连接数据库并生成POJO类:Hibernate框架连接SQL sever 2016完整详细步骤

还有一个一定会出错的地方,因为Hibernate和Struts 2 中有相同的包(版本不同)会引起冲突,所以要把Struts 2 中的antlr-2.7.2.jar移除,具体操作可以看这篇:java.lang.NoSuchMethodError: antlr.collections.AST.getLine()I最终解决方案

登录功能

1.先编写对数据库进行操作的DAO类UserInfoDao.java

public class UserInfoDao {
    private Session session;
    private Transaction t;
    public void getCurrentSession(){
        session=HibernateSessionFactory.getSession();
    }

    public void closeSession(){
        if(session!=null){
            HibernateSessionFactory.closeSession();
        }
    }

    /**
     * 登录函数:验证用户名和密码
     * @param vo
     * @return true 存在
     * @return false 不存在
     */

    public boolean loginByUserInfo(UserInfo vo){
        getCurrentSession();
        t=session.beginTransaction();
        String userAccount = vo.getUserAccount();
        String userPassword = vo.getUserPassword();
        Query query = session.createQuery("from UserInfo where userAccount='"+userAccount+"' and userPassword='"+userPassword+"'");
        List list=query.list();
        closeSession();
        if(list!=null)
            return true;
        return false;
    }
}

2.LoginAction.java

package org.action;

import java.util.Map;

import org.dao.UserInfoDao;
import org.vo.UserInfo;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport{
    private UserInfo userInfo;
    private String message;  //用于显示验证错误信息

    /**
     *  处理用户请求的 execute 方法
     *  因为此函数在 validate()后执行,所以可以保证用户名和密码正确
     *  @return SUCCESS 
     */
    public String execute() throws Exception{
        Map session = ActionContext.getContext().getSession();
        session.put("userInfo", userInfo);
        return SUCCESS;
    }

    /**
     *  验证用户名和密码
     *  先判断是否为空,再验证
     */
    public void validate(){
        if(userInfo.getUserAccount()==null || userInfo.getUserAccount().equals(""))
            this.addFieldError("userAccount", "用户名不能为空");
        else if(userInfo.getUserPassword()==null || userInfo.getUserPassword().equals(""))
            this.addFieldError("userPassword", "密码不能为空");
        else {
            UserInfoDao dao = new UserInfoDao();
            if(dao.loginByUserInfo(userInfo)==false)
                this.addFieldError("userAccount", "用户名或密码错误");
        }
    }

    //自动生成的getter和setter
    public UserInfo getUserInfo() {
        return userInfo;
    }
    public void setUserInfo(UserInfo userInfo) {
        this.userInfo = userInfo;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

3.登录界面login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<html>
  <head>
  <title>login.jsptitle>
  head>

  <body>
    <s:form action="loginAction" method="post" theme="simple">
        <s:fielderror><s:property value="message"/>s:fielderror><br>
        用户名:<s:textfield name="userInfo.userAccount"/><br>
        密码:<s:password name="userInfo.userPassword"/><br>
        <s:submit value="登录"/><s:reset value="重置"/>
    s:form>
  body>
html>

登录成功界面success.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<html>
  <head>
  <title>success.jsptitle>
  head>

  <body>
    <s:set name="userInfo" value="#session['userInfo']"/>
    <s:property value="#userInfo.userAccount"/>,你好!
  body>
html>

4.修改struts.xml文件



<struts>
    <package name="default" extends="struts-default">
    
    <action name="loginAction" class="org.action.LoginAction">
        <result name="success">/success.jspresult>
        <result name="input">/login.jspresult>
    action>
    
    package>
struts>    

访问http://localhost:8080/Ex5/login.jsp,可以判断输入是否合法,且可以验证用户名和密码,并在上面给出错误信息

注册功能

1.在UserInfoDao.java中添加实现注册的函数

package org.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.util.HibernateSessionFactory;
import org.vo.UserInfo;

public class UserInfoDao {
    private Session session;
    private Transaction t;
    public void getCurrentSession(){
        session=HibernateSessionFactory.getSession();
    }

    public void closeSession(){
        if(session!=null){
            HibernateSessionFactory.closeSession();
        }
    }
    /**
     * 登录函数:验证用户名和密码
     * @param vo
     * @return true 存在
     * @return false 不存在
     */

    public boolean loginByUserInfo(UserInfo vo){
        getCurrentSession();
        t=session.beginTransaction();
        String userAccount = vo.getUserAccount();
        String userPassword = vo.getUserPassword();
        Query query = session.createQuery("from UserInfo where userAccount='"+userAccount+"' and userPassword='"+userPassword+"'");
        List list=query.list();
        closeSession();
        if(list!=null)
            return true;
        return false;
    }

    /**
     * 注册函数:先查询表中是否已经存在相同的用户名,再进行插入操作
     * @param vo
     * @return true 注册成功
     * @return false 注册失败
     */
    public boolean registerByUserInfo(UserInfo vo){
        getCurrentSession();
        t=session.beginTransaction();
        String userAccount = vo.getUserAccount();

        Query query = session.createQuery("from UserInfo where userAccount='"+userAccount+"'");
        List list = query.list();
        if(list.size()>0){//如果表中已经有相同的用户名
            closeSession();
            return false;
        }else{
            session.save(vo);
            t.commit();
            closeSession();
            return true;
        }
    }
}

2.RegisterAction.java实现判断输入是否合法以及数据库中是否已存在相同的用户名

package org.action;

import java.util.Map;

import org.dao.UserInfoDao;
import org.vo.UserInfo;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class RegisterAction extends ActionSupport{

    private String userAccount;
    private String userPassword;
    private String rePassword;
    private String message;  //用于显示验证错误信息

    /**
     *  处理用户请求的 execute 方法
     *  因为此函数在 validate()后执行,所以可以保证用户名和密码正确
     *  @return SUCCESS 
     */
    public String execute() throws Exception{
        Map session = ActionContext.getContext().getSession();
        UserInfo vo = new UserInfo();
        vo.setUserAccount(userAccount);
        vo.setUserPassword(userPassword);
        session.put("userInfo", vo);
        return SUCCESS;
    }

    /**
     *  先验证用户名和密码是否为空
     *  再验证进行插入操作
     */
    public void validate(){
        if(userAccount==null||userAccount.equals("")){
            this.addFieldError("userAccount", "用户名不能为空");
        }else if(userPassword==null||userPassword.equals("")){
            this.addFieldError("userPassword", "密码不能为空");
        }else if(userPassword.equals(rePassword)==false){
            this.addFieldError("rePassword", "两次密码必须一致");
        }else{
            UserInfoDao dao = new UserInfoDao();
            UserInfo vo = new UserInfo();
            vo.setUserAccount(userAccount);
            vo.setUserPassword(userPassword);
            if(dao.registerByUserInfo(vo)==false){
                this.addFieldError("userAccount", "对不起!该用户名已被注册");
            }
        }
    }

    //自动生成的getter和setter
    public String getUserAccount() {
        return userAccount;
    }

    public void setUserAccount(String userAccount) {
        this.userAccount = userAccount;
    }

    public String getUserPassword() {
        return userPassword;
    }

    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

    public String getRePassword() {
        return rePassword;
    }

    public void setRePassword(String rePassword) {
        this.rePassword = rePassword;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

3.注册界面register.java

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<html>
  <head>
  <title>register.jsptitle>
  head>

  <body>
    <s:form action="registerAction" method="post" theme="simple">
    <s:fielderror><s:property value="message"/>s:fielderror><br>
        用户名:<s:textfield name="userAccount" /><br>
        密码:<s:password name="userPassword" /><br>
        重复密码:<s:password name="rePassword"/><br>
        <s:submit value="提交"/><s:reset value="重置"/>
    s:form>
  body>
html>

4.在struts.xml文件中添加用户注册的action配置



<struts>
    <package name="default" extends="struts-default">
    
    <action name="loginAction" class="org.action.LoginAction">
        <result name="success">/success.jspresult>
        <result name="input">/login.jspresult>
    action>
    
    <action name="registerAction" class="org.action.RegisterAction">
        <result name="success">/success.jspresult>
        <result name="input">/register.jspresult>
    action>
    package>
struts>    

访问http://localhost:8080/Ex5/register.jsp即可实现注册

其他:

最终的struts.xml

Struts 2+Hibernate实现完整登录注册(带验证)_第4张图片
web.xml


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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_3_0.xsd" version="3.0">
  <display-name>Ex5display-name>
  <filter>
    <filter-name>struts2filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilterfilter-class>
  filter>
  <filter-mapping>
    <filter-name>struts2filter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>
web-app>

你可能感兴趣的:(Hibernate,Struts,2,hibernate,struts,javaEE)