ssh整合--注册登录

来源:互联网 发布:淘宝店铺怎么上传宝贝 编辑:程序博客网 时间:2024/06/12 20:26

用SSH实现登录注册

1、相关环境和技术:

  • IDE:eclipse
  • 数据库:MySQL,Navicat
  • 单元测试:JUnit
  • Struts2+Hibernate5+spring4

2、新建一个Dynamic Web project及搭建SSH环境
文件结构

3、数据库
数据库表结构

4、封装JavaBean和编写映射文件

    package hnt;    public class Userinfo {    private int id ;    private String username;    private String pwd;    private String email;    public Userinfo(){    }        public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    public String getPwd() {        return pwd;    }    public void setPwd(String pwd) {        this.pwd = pwd;    }    public String getEmail() {        return email;    }    public void setEmail(String email) {        this.email = email;    }        public String toString() {        return "Userinfo [id=" + id + ", username=" + username + ", pwd=" + pwd + ", email=" + email + "]";    }}

配置文件:Userinfo.hbm.xml

<hibernate-mapping>    <class name="hnt.Userinfo" table="USERINFO">        <id name="id" type="int">            <column name="ID" />            <generator class="assigned" />        </id>        <property name="username" type="java.lang.String">            <column name="USERNAME" />        </property>        <property name="pwd" type="java.lang.String">            <column name="PWD" />        </property>        <property name="email" type="java.lang.String">            <column name="EMAIL" />        </property>          </class></hibernate-mapping>

———–由于hibernate交由Spring管理,所以不需要cfg.xml

web.xml

<listener>        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener>    <context-param>        <param-name>contextConfigLocation</param-name>        <param-value>classpath:applicationContext.xml</param-value>    </context-param>    <!-- 解决延迟加载的问题 -->    <filter>        <filter-name>OpenSessionInViewFilter</filter-name>        <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>    </filter>    <filter-mapping>        <filter-name>OpenSessionInViewFilter</filter-name>        <url-pattern>/*</url-pattern>    </filter-mapping>    <filter>        <filter-name>struts2</filter-name>        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>    </filter>    <filter-mapping>        <filter-name>struts2</filter-name>        <url-pattern>/*</url-pattern>    </filter-mapping>    <welcome-file-list>        <welcome-file>index.html</welcome-file>        <welcome-file>index.htm</welcome-file>        <welcome-file>index.jsp</welcome-file>        <welcome-file>default.html</welcome-file>        <welcome-file>default.htm</welcome-file>        <welcome-file>default.jsp</welcome-file>    </welcome-file-list></web-app>

struts.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts PUBLIC        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"        "http://struts.apache.org/dtds/struts-2.5.dtd"><struts><package name="crm" extends="struts-default" namespace="/"><global-results><result name="login" type="redirect">/login.jsp</result></global-results><!-- 通配符配置--!><action name="user_*" class="userAction" method="{1}">          <resultname="loginok"type="redirect">/bookstore.jsp        </result><allowed-methods>add,checkCode,login,exit</allowed-methods>             </action>    </package>  </struts>

5、Action

package com.web.action;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.http.HttpServletResponse;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;import com.opensymphony.xwork2.ModelDriven;import com.web.service.UserService;import hnt.Userinfo;public class UserAction extends ActionSupport implements ModelDriven<Userinfo> {    private static final long serialVersionUID = -8629892132553041174L;    private Userinfo user= new Userinfo();    public Userinfo getModel() {                return user;    }    private UserService userService;    public void setUserService(UserService userService) {        this.userService = userService;    }    public String add(){       userService.save(user);        return LOGIN;    }    public String checkCode(){        //调业务层查询        Userinfo u =userService.checkCode(user.getUsername());        //获取response        HttpServletResponse response = ServletActionContext.getResponse();        response.setContentType("text/html;charset=UTF-8");        //获取输出流        try {            PrintWriter writer = response.getWriter();            System.out.println(u);            if(u ==null){                //可以注册                writer.print("yes");                    }else{                //说明用户已存在                writer.print("no");            }        } catch (IOException e) {               e.printStackTrace();        }        return NONE;    }    public String login(){        Userinfo existUser= userService.login(user);        if(existUser==null){            return LOGIN;        }else{          ServletActionContext.getRequest().getSession().setAttribute("existUser", existUser);            return "loginok";        }       }    public String exit(){       ServletActionContext.getRequest().getSession().removeAttribute("existUser");        return LOGIN;    }}

6、Dao

package com.web.dao;import hnt.Userinfo;public interface UserDao {    public void save(Userinfo user);    public Userinfo checkCode(String username);    public Userinfo login(Userinfo user);}

7、DaoImpl

package com.web.dao;import java.util.List;import org.hibernate.criterion.DetachedCriteria;import org.hibernate.criterion.Restrictions;import org.springframework.orm.hibernate5.HibernateTemplate;import org.springframework.orm.hibernate5.support.HibernateDaoSupport;import hnt.Userinfo;public class UserDaoImpl extends HibernateDaoSupport implements UserDao {    public void save(Userinfo user) {        this.getHibernateTemplate().save(user);    }    public Userinfo checkCode(String username) {        List<Userinfo> list= (List<Userinfo>)this.getHibernateTemplate().find("from Userinfo where username = ?", username);         if(list != null && list.size()>0){            return list.get(0);        }        return null;    }    public Userinfo login(Userinfo user) {        //QBC 按条件查询        DetachedCriteria criteria = DetachedCriteria.forClass(Userinfo.class);        //查询条件        criteria.add(Restrictions.eq("username", user.getUsername()));        criteria.add(Restrictions.eq("pwd", user.getPwd()));        criteria.add(Restrictions.eq("power", "1"));        //查询        List<Userinfo> list = (List<Userinfo>) this.getHibernateTemplate().findByCriteria(criteria);        if(list !=null&&list.size()>0){            return list.get(0);        }               return null;    }}

7、service

package com.web.service;import hnt.Userinfo;public interface UserService {    public void save(Userinfo user);    public Userinfo checkCode(String username);    public Userinfo login(Userinfo user);}

8、serviceImpl

package com.web.service;import org.springframework.transaction.annotation.Transactional;import com.web.dao.UserDao;import hnt.Userinfo;import utils.MD5Utils;@Transactionalpublic class UserServiceImpl implements UserService {    private UserDao userDao;    public void setUserDao(UserDao userDao) {        this.userDao = userDao;    }/** * MD5加密 *  */    public void save(Userinfo user) {        String pwd = user.getPwd();        user.setPwd(MD5Utils.md5(pwd));        userDao.save(user);    }    public Userinfo checkCode(String username) {        return userDao.checkCode(username);    }/** * 登录通过登录名和密码作校验 */    public Userinfo login(Userinfo user) {        String pwd = user.getPwd();        user.setPwd(MD5Utils.md5(pwd));        return userDao.login(user);    }}

9、Ajax异步校验

<script type="text/javascript">    function checkCode(){        var code=   $("#username").val();        if(code.trim()==""){            $("#idCode").addClass("error");            $("#idCode").html("用户名不能为空");         }else{            var url="${pageContext.request.contextPath}/user_checkCode.action";            var param = {"username":code};            $.post(url,param,function(data){                //操作data 进行判断                if(data && data=="no"){                    $("#idCode").addClass("error");                    $("#idCode").html("用户已存在");                 }else{                    $("#idCode").html("可以注册");                 }            });        }    }    function checkForm(){        checkCode();        if($(".error").size()>0){            return false;        }    }</script>

10、注册页面

<%@ 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>register</title><style type="text/css">.error{color:#F00}</style><script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.11.3.min.js"></script><script type="text/javascript">    function checkCode(){        var code=   $("#username").val();        if(code.trim()==""){            $("#idCode").addClass("error");            $("#idCode").html("用户名不能为空");         }else{            var url="${pageContext.request.contextPath}/user_checkCode.action";            var param = {"username":code};            $.post(url,param,function(data){                //操作data 进行判断                if(data && data=="no"){                    $("#idCode").addClass("error");                    $("#idCode").html("用户已存在");                 }else{                    $("#idCode").html("可以注册");                 }            });        }    }    function checkForm(){        checkCode();        if($(".error").size()>0){            return false;        }    }</script></head><body> <h1>用户注册</h1>    <form action="${pageContext.request.contextPath }/user_add.action" onsubmit="return checkForm()" method="post" >        <p>            <label for="username">用户名:</label>            <input type="text" name="username" id="username" onblur="checkCode()"/> <span id="idCode"></span>        </p>        <p>            <label for="pwd">密码:</label>            <input type="password" name="pwd" id="pwd" /> <span></span>        </p>        <p>            <label for="repwd">确认密码:</label>            <input type="password" name="repwd" id="repwd" /><span></span>        </p>        <p>            <label for="email">邮箱:</label>            <input type="email" name="email" id="email" />        </p>            <p>            <label for="address">地址:</label>            <input type="text" name="address" id="address" />        </p>             <p>            <label for="postcode">邮编:</label>            <input type="text" name="postcode" id="postcode" />        </p>             <p>            <label for="level">等级:</label>            <input type="text" name="level" id="level" />        </p>              <p>            <label for="power">权限:</label>            <input type="text" name="power" id="power" />        </p>        <p>            <input type="submit" value="注册">            <input type="reset" value="重填">        </p>    </form></body></html>

11、登录页面

<%@ 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>register</title><style type="text/css">.error{color:#F00}</style><script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.11.3.min.js"></script><script type="text/javascript">    function checkCode(){        var code=   $("#username").val();        if(code.trim()==""){            $("#idCode").addClass("error");            $("#idCode").html("用户名不能为空");         }else{            $("#idCode").html(" ");         }       }    function checkForm(){        checkCode();        if($(".error").size()>0){            return false;        }    }</script></head><body> <h1>用户登录</h1>    <form action="${pageContext.request.contextPath }/user_login.action" onsubmit="return checkForm()" method="post" >        <p>            <label for="username">用户名:</label>            <input type="text" name="username" id="username" onblur="checkCode()"/> <span id="idCode"></span>        </p>        <p>            <label for="pwd">密码:</label>            <input type="password" name="pwd" id="pwd" /> <span></span>        </p>       <p>            <input type="submit" value="登录">            <input type="reset" value="重填">        </p>    </form></body></html>

初学还有很多不足,欢迎大家批评指正。
记录学习之点滴。


0 0
原创粉丝点击