JavaWeb_(SSH论坛)_三、用户模块

时间:2024-09-24 09:36:44

基于SSH框架的小型论坛项目  

  一、项目入门  传送门

  二、框架整合  传送门

  三、用户模块  传送门

  四、页面显示  传送门

  五、帖子模块  传送门

  六、点赞模块  传送门

  七、辅助模块  传送门

User表

  id:

  username:登陆账号

  password:登陆密码

  name:用户名

  email:用户邮箱

  telephone:用户电话

  state(1,0):根据邮箱判断用户是否激活

  code:

  image:用户头像

  level:用户等级

  coin:金币

JavaWeb_(SSH论坛)_三、用户模块

(根据用户表单进行创建User表)

  点击立即注册

    用户成功->登陆界面

    注册失败->用户名存在

  将表单数据链接数据库

<form action="${pageContext.request.contextPath }/UserAction_register }" method="post">

</form>

  创建User实体(domain层)

    private String id;
private String username;
private String password;
private String name;
private String email;
private String telephone;
private Integer state;
private String code;
private String image;
private Integer level;
private Integer coin;
package com.Gary.domain;

public class User {
private String id;
private String username;
private String password;
private String name;
private String email;
private String telephone;
private Integer state;
private String code;
private String image;
private Integer level;
private Integer coin; 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;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
public Integer getCoin() {
return coin;
}
public void setCoin(Integer coin) {
this.coin = coin;
} }

User.java

  用户注册流程

  一开始用户先来到UserAction.java中register()方法

    public String register() throws Exception {
// TODO Auto-generated method stub userService.addUser(user); return "toLogin"; }

  通过regiser()方法来到UserService.java

public class UserService {

    private UserDao userDao;

    public void addUser(User user) {
    
userDao.addUser(user); }
}

  通过addUser()来到Dao层save(user)

public class UserDao extends HibernateDaoSupport{

    public void addUser(User user) {
// TODO Auto-generated method stub
//拿到与当前线程绑定的session
Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
session.save(user);
} }

  register.jsp自动封装表单字段

        <form action="${pageContext.request.contextPath }/UserAction_register }" method="post">
<div class="register-box"> <label for="username" class="username_label"> 用 户 名 <input maxlength="20" name="username" type="text" placeholder="您的用户名和登录名" />
</label>
<div class="tips"></div>
</div>
<div class="register-box">
<label for="username" class="other_label"> 设 置 密 码 <input maxlength="20" type="password" name="password" placeholder="建议至少使用两种字符组合" />
</label>
<div class="tips"></div>
</div>
<div class="register-box">
<label for="username" class="other_label"> 确 认 密 码 <input maxlength="20" type="password" placeholder="请再次输入密码" />
</label>
<div class="tips"></div>
</div> <div class="register-box">
<label for="username" class="username_label"> 真实姓名 <input maxlength="20" name="name" type="text" placeholder="您的真实姓名" />
</label>
<div class="tips"></div>
</div>
<div class="register-box">
<label for="username" class="username_label"> 邮箱 <input maxlength="20" name="email" type="text" placeholder="您的邮箱" />
</label>
<div class="tips"></div>
</div>
<div class="register-box">
<label for="username" class="username_label"> 手机号 <input maxlength="20" name="telephone" type="text" placeholder="您的手机号" />
</label>
<div class="tips"></div>
</div>
<div class="arguement">
<input type="checkbox" id="xieyi" /> 阅读并同意 <a href="javascript:void(0)">《错题用户注册协议》</a> <a href="login.html">已有账号,立即登录</a>
<div class="tips"></div>
</div>
<div class="submit_btn">
<button type="submit" id="submit_btn">立 即 注 册</button>
</div>
</form>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" type="text/css" href="css/login.css" />
<link rel="stylesheet" href="css/head.css" />
</head> <body style="margin: -2px">
<iframe src="head.html" scrolling="no" width="100%" height="110px"></iframe>
<section class="sec">
<form action="${pageContext.request.contextPath }/UserAction_register }" method="post">
<div class="register-box"> <label for="username" class="username_label"> 用 户 名 <input maxlength="20" name="username" type="text" placeholder="您的用户名和登录名" />
</label>
<div class="tips"></div>
</div>
<div class="register-box">
<label for="username" class="other_label"> 设 置 密 码 <input maxlength="20" type="password" name="password" placeholder="建议至少使用两种字符组合" />
</label>
<div class="tips"></div>
</div>
<div class="register-box">
<label for="username" class="other_label"> 确 认 密 码 <input maxlength="20" type="password" placeholder="请再次输入密码" />
</label>
<div class="tips"></div>
</div> <div class="register-box">
<label for="username" class="username_label"> 真实姓名 <input maxlength="20" name="name" type="text" placeholder="您的真实姓名" />
</label>
<div class="tips"></div>
</div>
<div class="register-box">
<label for="username" class="username_label"> 邮箱 <input maxlength="20" name="email" type="text" placeholder="您的邮箱" />
</label>
<div class="tips"></div>
</div>
<div class="register-box">
<label for="username" class="username_label"> 手机号 <input maxlength="20" name="telephone" type="text" placeholder="您的手机号" />
</label>
<div class="tips"></div>
</div>
<div class="arguement">
<input type="checkbox" id="xieyi" /> 阅读并同意 <a href="javascript:void(0)">《错题用户注册协议》</a> <a href="login.html">已有账号,立即登录</a>
<div class="tips"></div>
</div>
<div class="submit_btn">
<button type="submit" id="submit_btn">立 即 注 册</button>
</div>
</form>
</section>
<script src="js/index.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>

register.jsp

  register()中手动封装表单未添加数据

public String register() throws Exception {
// TODO Auto-generated method stub /*
自动封装的打1
private String id;
private String username; 1
private String password; 1
private String name; 1
private String email; 1
private String telephone; 1
private Integer state;
private String code;
private String image;
private Integer level;
private Integer coin;
*/ //没有的数据手动封装
user.setState(0);
user.setCode(UUID.randomUUID().toString());
user.setImage("0");
user.setLevel(1);
user.setCoin(1000); //是否添加成功
userService.addUser(user); return "toLogin"; }

配置hibernate

  applicationContext.xml中有一句

<property name="mappingDirectoryLocations"
value="classpath:com/Gary/domain"></property>
    <!-- 配置sessionFactory -->
<bean name="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sqp">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property> <property name="mappingDirectoryLocations"
value="classpath:com/Gary/domain"></property> </bean>

  数据源字段再User,hbm中配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.Gary.domain">
<class name="User" table="user">
<id name="id">
<generator class="uuid"></generator>
</id> <!--
private String username;
private String password;
private String name;
private String email;
private String telephone;
private Integer state;
private String code;
private String image;
private Integer level;
private Integer coin; --> <property name="username" column="username"></property>
<property name="password" column="password"></property>
<property name="name" column="name"></property>
<property name="email" column="email"></property>
<property name="telephone" column="telephone"></property>
<property name="state" column="state"></property>
<property name="code" column="code"></property>
<property name="image" column="image"></property>
<property name="level" column="level"></property>
<property name="coin" column="coin"></property> </class>
</hibernate-mapping>

User.hbm.xml

配置Struts

  在UserAction对Struts进行配置

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html> <head>
<meta charset="UTF-8"> <link rel="stylesheet" href="css/head.css" />
<link rel="stylesheet" type="text/css" href="css/login.css" />
</head> <body style="margin: -2px"> <iframe src="head.html" scrolling="no" width="100%" height="110px"></iframe> <section class="sec">
<form action="UserLoginServlet" method="post">
<div class="register-box">
<label for="username" class="username_label"> 用 户 名 <input maxlength="20" name="userName" type="text" placeholder="您的用户名和登录名" />
</label>
<div class="tips"></div>
</div>
<div class="register-box">
<label for="username" class="other_label"> 密 码 <input maxlength="20" type="password" name="pwd" placeholder="建议至少使用两种字符组合" />
</label>
<div class="tips"></div>
</div>
<div class="arguement">
<input type="checkbox" id="xieyi" /> 阅读并同意 <a href="javascript:void(0)">《你问我答用户注册协议》</a> <a href="register.html">没有账号,立即注册</a>
<div class="tips"></div>
</div>
<div class="submit_btn">
<button type="submit" id="submit_btn">立 即 登录</button>
</div>
</form>
</section>
<script src="js/index.js" type="text/javascript" charset="utf-8"></script>
</body>

login.jsp

<?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> <!-- 开启动态方法调用 -->
<constant name="struts.devMode" value="true"></constant>
<constant name="struts.enable.DynamicMethodInvocation" value="true"></constant> <package name="Gary_SSHForum" namespace="/" extends="struts-default">
<!-- 允许全部方法 -->
<global-allowed-methods>regex:.*</global-allowed-methods>
<action name="UserAction_*" class="com.Gary.web.UserAction">
<result name="toLogin" type="redirect">/login.jsp</result> </action>
</package> </struts>

配置spring

<struts>

    <!--开启动态方法调用 -->
<constant name="struts.devMode" value="true"></constant>
<constant name="struts.enable.DynamicMethodInvocation" value="true"></constant> <!-- 告诉struts不用自己创建Action,Spring来帮你创建 -->
<constant name="struts.objectFactory" value="spring"></constant> <package name="Gary_SSHForum" namespace="/" extends="struts-default">
<!-- 允许全部方法 -->
<global-allowed-methods>regex:.*</global-allowed-methods>
<action name="UserAction_*" class="com.Gary.web.UserAction" method="{1}">
<result name="toLogin" type="redirect">/login.jsp</result> </action>
</package> </struts>

  applicationContext.xml中进行整合

    <!-- 配置Action -->
<bean name="userAction" class="com.Gary.web.UserAction" scope="prototype"> <property name="userService" ref="userService"> </property>
</bean> <!-- 配置Service -->
<bean name="userService" class="com.Gary.service.UserService">
<property name="userDao" ref="userDao"></property>
</bean> <!-- 配置Dao -->
<bean name="userDao" class="com.Gary.dao.UserDao">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>

   测试

  在项目中进行表单注册

JavaWeb_(SSH论坛)_三、用户模块

JavaWeb_(SSH论坛)_三、用户模块

表单校验

  页面自带表单校验

  通过引入jquery.validate.min.js就可以实现

//input各种判断
//用户名:
$('input').eq(0).blur(function(){
if($(this).val().length==0){
$(this).parent().next("div").text("");
$(this).parent().next("div").css("color",'#ccc');
}else if($(this).val().length>0 && $(this).val().length<4){
$(this).parent().next("div").text("长度只能在4-20个字符之间");
$(this).parent().next("div").css("color",'red');
}else if($(this).val().length>=4&& !isNaN($(this).val())){
$(this).parent().next("div").text("用户名不能为纯数字");
$(this).parent().next("div").css("color",'red');
}
})
//密码
$('input').eq(1).blur(function(){
if($(this).val().length==0){
$(this).parent().next("div").text("");
$(this).parent().next("div").css("color",'#ccc');
}else if($(this).val().length>0 && $(this).val().length<3){
$(this).parent().next("div").text("长度只能在3-20个字符之间");
$(this).parent().next("div").css("color",'red');
}else{
$(this).parent().next("div").text("");
}
})
// 确认密码
$('input').eq(2).blur(function(){
if($(this).val().length==0){
$(this).parent().next("div").text("");
$(this).parent().next("div").css("color",'#ccc');
}else if($(this).val()!=$('input').eq(1).val()){
$(this).parent().next("div").text("两次密码不匹配");
$(this).parent().next("div").css("color",'red');
}else{
$(this).parent().next("div").text("");
}
})

实现From表单中邮箱校验

  邮箱name="email"

 <div class="register-box">
<label for="username" class="username_label"> 邮箱 <input maxlength="20" name="email" type="text" placeholder="您的邮箱" />
</label>
<div class="tips"></div>
</div>
<script type="text/javascript">

    $(function(){
$("#myform").validate({ //json格式规则
rules:{
"email":{
//是否未必填字段
"required":true,
"email":true
}
}, //如果违反了规则应该怎么办
messages:{
"email":{
"required":"邮箱不能为空",
"email":"请输入正确的邮箱"
}
} }) }) </script>

JavaWeb_(SSH论坛)_三、用户模块

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" type="text/css" href="css/login.css" />
<link rel="stylesheet" href="css/head.css" />
<script src="js/jquery-1.7.2.min.js"></script>
<script src="js/jquery.validate.min.js"></script>
<script src="js/index.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> $(function(){
$("#myform").validate({ //json格式规则
rules:{
"email":{
//是否未必填字段
"required":true,
"email":true
}
}, //如果违反了规则应该怎么办
messages:{
"email":{
"required":"邮箱不能为空",
"email":"请输入正确的邮箱"
}
} }) }) </script> </head> <body style="margin: -2px">
<iframe src="head.html" scrolling="no" width="100%" height="110px"></iframe>
<section class="sec">
<form id="myform" action="${pageContext.request.contextPath }/UserAction_register" method="post">
<div class="register-box"> <label for="username" class="username_label"> 用 户 名 <input maxlength="20" name="username" type="text" placeholder="您的用户名和登录名" />
</label>
<div class="tips"></div>
</div>
<div class="register-box">
<label for="username" class="other_label"> 设 置 密 码 <input maxlength="20" type="password" name="password" placeholder="建议至少使用两种字符组合" />
</label>
<div class="tips"></div>
</div>
<div class="register-box">
<label for="username" class="other_label"> 确 认 密 码 <input maxlength="20" type="password" placeholder="请再次输入密码" />
</label>
<div class="tips"></div>
</div> <div class="register-box">
<label for="username" class="username_label"> 真实姓名 <input maxlength="20" name="name" type="text" placeholder="您的真实姓名" />
</label>
<div class="tips"></div>
</div>
<div class="register-box">
<label for="username" class="username_label"> 邮箱 <input maxlength="20" name="email" type="text" placeholder="您的邮箱" />
</label>
<div class="tips"></div>
</div>
<div class="register-box">
<label for="username" class="username_label"> 手机号 <input maxlength="20" name="telephone" type="text" placeholder="您的手机号" />
</label>
<div class="tips"></div>
</div>
<div class="arguement">
<input type="checkbox" id="xieyi" /> 阅读并同意 <a href="javascript:void(0)">《错题用户注册协议》</a> <a href="login.html">已有账号,立即登录</a>
<div class="tips"></div>
</div>
<div class="submit_btn">
<button type="submit" id="submit_btn">立 即 注 册</button>
</div>
</form>
</section>
</body>
</html> register.jsp

register.jsp

  书写表单校验提示信息

<div class="register-box">
<label for="username" class="username_label"> 邮箱 <input maxlength="20" name="email" type="text" placeholder="您的邮箱" />
</label>
<div class="tips"><label class="error" for="email" style="display:none">请输入正确的邮箱</label></div>
</div>

  让提示信息变得好看

  错误信息颜色变红

<style>
.error{
color:red;
}
</style>
<div class="register-box">
<label for="username" class="username_label"> 邮箱 <input maxlength="20" name="email" type="text" placeholder="您的邮箱" />
</label>
<div class="tips"><label class="error" for="email" style="display:none; padding-left:0px ; line-height: 25px;color:red">请输入正确的邮箱</label></div>
</div>

Ajax实现用户名异步校验

  异步校验:当用户注册账号一离焦,立马将数据与数据库中的数据进行校验

  给用户名表单添加Ajax校验

<label for="username" class="username_label"> 用 户 名 <input id="username" maxlength="20" name="username" type="text" placeholder="您的用户名和登录名" />
</label>
$(function()
{
$("#username").blur(function(){
$.post(
//action地址 //提交的数据
{},
//回调函数
function(data)
{ }
//数据的格式
"json" )
})
})

  JavaWeb_(SSH论坛)_三、用户模块

  

  基于Ajax异步校验检测,Web层,Service层,Dao层

  Web层校验用户名是否存在

public String checkUsername() throws Exception {

        //获得用户username
boolean success = userService.findUserByUsername(user.getUsername()); //获得原生Servlet对象
ServletActionContext.getResponse().getWriter().write("{\"success\":"+success+"}"); return null;
}

  Service层去查找有没有username

public boolean findUserByUsername(String username) {
// TODO Auto-generated method stub
Long count = userDao.findUserByUsername(username);
if(count==0)
return true;
else
return false;
}

  Dao层对数据库进程数据查询

public Long findUserByUsername(String username){
// TODO Auto-generated method stub
Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
String sql = "select count(*) from user where username = ?";
NativeQuery query = session.createSQLQuery(sql); //1号位置设置为username
query.setParameter(1,username);
BigInteger result = (BigInteger)query.uniqueResult(); return result.longValue();
}

  register.jsp返回要查询的值

$(function()
{
$("#username").blur(function(){
var usernameInput = $(this).val();
//alert(usernameInput);
$.post(
//action地址checkUsername()
"${pageContext.request.contextPath}/UserAction_checkUsername",
//提交的数据
{"username":usernameInput},
//回调函数
function(data)
{
var success = data.success;
//可以添加
if(success)
{
$("#usernameInfo").css("color","green");
$("#usernameInfo").html("用户名可以使用!");
}
//不可添加
else
{
$("#usernameInfo").css("color","red");
$("#usernameInfo").html("用户名已经被注册!");
}
},
//数据的格式
"json"
)
})
})

JavaWeb_(SSH论坛)_三、用户模块

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" type="text/css" href="css/login.css" />
<link rel="stylesheet" href="css/head.css" />
<style>
.error{
color:red;
}
</style>
<script src="js/jquery-1.7.2.min.js"></script>
<script src="js/jquery.validate.min.js"></script>
<script src="js/index.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> $(function(){
$("#myform").validate({ //json格式规则
rules:{
"email":{
//是否未必填字段
"required":true,
"email":true
}
}, //如果违反了规则应该怎么办
messages:{
"email":{
"required":"邮箱不能为空",
"email":"请输入正确的邮箱"
}
} }) }) $(function()
{
$("#username").blur(function(){
var usernameInput = $(this).val();
//alert(usernameInput);
$.post(
//action地址checkUsername()
"${pageContext.request.contextPath}/UserAction_checkUsername",
//提交的数据
{"username":usernameInput},
//回调函数
function(data)
{
var success = data.success;
//可以添加
if(success)
{
$("#usernameInfo").css("color","green");
$("#usernameInfo").html("用户名可以使用!");
}
//不可添加
else
{
$("#usernameInfo").css("color","red");
$("#usernameInfo").html("用户名已经被注册!");
}
},
//数据的格式
"json"
)
})
}) </script> </head> <body style="margin: -2px">
<iframe src="head.html" scrolling="no" width="100%" height="110px"></iframe>
<section class="sec">
<form id="myform" action="${pageContext.request.contextPath }/UserAction_register" method="post">
<div class="register-box">
<label for="username" class="username_label"> 用 户 名 <input id="username" maxlength="20" name="username" type="text" placeholder="您的用户名和登录名" />
</label>
<div id="usernameInfo" class="tips"></div>
</div>
<div class="register-box">
<label for="username" class="other_label"> 设 置 密 码 <input maxlength="20" type="password" name="password" placeholder="建议至少使用两种字符组合" />
</label>
<div class="tips"></div>
</div>
<div class="register-box">
<label for="username" class="other_label"> 确 认 密 码 <input maxlength="20" type="password" placeholder="请再次输入密码" />
</label>
<div class="tips"></div>
</div> <div class="register-box">
<label for="username" class="username_label"> 真实姓名 <input maxlength="20" name="name" type="text" placeholder="您的真实姓名" />
</label>
<div class="tips"></div>
</div>
<div class="register-box">
<label for="username" class="username_label"> 邮箱 <input maxlength="20" name="email" type="text" placeholder="您的邮箱" />
</label>
<div class="tips"><label class="error" for="email" style="display:none; padding-left:0px ; line-height: 25px;color:red">请输入正确的邮箱</label></div>
</div>
<div class="register-box">
<label for="username" class="username_label"> 手机号 <input maxlength="20" name="telephone" type="text" placeholder="您的手机号" />
</label>
<div class="tips"></div>
</div>
<div class="arguement">
<input type="checkbox" id="xieyi" /> 阅读并同意 <a href="javascript:void(0)">《错题用户注册协议》</a> <a href="login.html">已有账号,立即登录</a>
<div class="tips"></div>
</div>
<div class="submit_btn">
<button type="submit" id="submit_btn">立 即 注 册</button>
</div>
</form>
</section>
</body>
</html>

register.jsp

package com.Gary.web;

import java.util.UUID;

import org.apache.struts2.ServletActionContext;

import com.Gary.domain.User;
import com.Gary.service.UserService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven; //采用模型驱动 泛型User
public class UserAction extends ActionSupport implements ModelDriven<User>{ public User user = new User(); private UserService userService; //校验用户名是否存在
public String checkUsername() throws Exception { //获得用户username
boolean success = userService.findUserByUsername(user.getUsername()); //获得原生Servlet对象
ServletActionContext.getResponse().getWriter().write("{\"success\":"+success+"}"); return null;
} public String register() throws Exception {
// TODO Auto-generated method stub /*
自动封装的打1
private String id;
private String username; 1
private String password; 1
private String name; 1
private String email; 1
private String telephone; 1
private Integer state;
private String code;
private String image;
private Integer level;
private Integer coin;
*/ //没有的数据手动封装
user.setState(0);
user.setCode(UUID.randomUUID().toString());
user.setImage("0");
user.setLevel(1);
user.setCoin(1000); //是否添加成功
userService.addUser(user); return "toLogin"; } public UserService getUserService() {
return userService;
} public void setUserService(UserService userService) {
this.userService = userService;
} public User getModel() {
return user;
} }

UserAction.java

package com.Gary.service;

import java.math.BigInteger;

import com.Gary.dao.UserDao;
import com.Gary.domain.User; public class UserService { private UserDao userDao; public UserDao getUserDao() {
return userDao;
} public void setUserDao(UserDao userDao) {
this.userDao = userDao;
} public void addUser(User user) {
// TODO Auto-generated method stub
userDao.addUser(user);
} public boolean findUserByUsername(String username) {
// TODO Auto-generated method stub
Long count = userDao.findUserByUsername(username);
if(count==0)
return true;
else
return false;
} }

UserService.java

package com.Gary.dao;

import java.math.BigInteger;

import org.hibernate.Session;
import org.hibernate.query.NativeQuery;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport; import com.Gary.domain.User; public class UserDao extends HibernateDaoSupport{ public void addUser(User user) {
Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
session.save(user); } public Long findUserByUsername(String username){
// TODO Auto-generated method stub
Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
String sql = "select count(*) from user where username = ?";
NativeQuery query = session.createSQLQuery(sql); //1号位置设置为username
query.setParameter(1,username);
BigInteger result = (BigInteger)query.uniqueResult(); return result.longValue();
} }

UserDao.java

邮箱注册

  

    JavaWeb_(SSH论坛)_三、用户模块

  邮箱类

// 1.创建一个程序与邮件服务器会话对象 Session

        Properties props = new Properties();
props.setProperty("mail.transport.protocol", "SMTP");
props.setProperty("mail.host", "smtp.163.com");
props.setProperty("mail.smtp.auth", "true");// 指定验证为true // 创建验证器
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("m17689470428", "tt199706282818");
}
}; Session session = Session.getInstance(props, auth); // 2.创建一个Message,它相当于是邮件内容
Message message = new MimeMessage(session); message.setFrom(new InternetAddress("m17689470428@163.com")); // 设置发送者 message.setRecipient(RecipientType.TO, new InternetAddress(email)); // 设置发送方式与接收者 //设置标题
message.setSubject(title);
// message.setText("这是一封激活邮件,请<a href='#'>点击</a>"); message.setContent(emailMsg, "text/html;charset=utf-8"); // 3.创建 Transport用于将邮件发送 Transport.send(message);

  UserAction.java中添加邮箱激活内容,编写用户激活函数

public String register() throws Exception {
// TODO Auto-generated method stub //没有的数据手动封装
user.setState(0);
user.setCode(UUID.randomUUID().toString());
user.setImage("0");
user.setLevel(1);
user.setCoin(1000); //是否添加成功
userService.addUser(user); MailUtils.sendMail(user.getEmail(), "请激活", "恭喜您注册成功,请点击下面的链接激活!! <a href='http://localhost:8080/Gary_SSHForum/UserAction_active'>点击这里</a>"); return "toLogin"; }

  用户激活函数

public String active() throws Exception {

        System.out.println("active");
return null;
}

JavaWeb_(SSH论坛)_三、用户模块

JavaWeb_(SSH论坛)_三、用户模块

package com.Gary.utils;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType; public class MailUtils { //发邮箱,给谁发Email,以及Email内容
public static void sendMail(String email, String title,String emailMsg)
throws AddressException, MessagingException {
// 1.创建一个程序与邮件服务器会话对象 Session Properties props = new Properties();
props.setProperty("mail.transport.protocol", "SMTP");
props.setProperty("mail.host", "smtp.163.com");
props.setProperty("mail.smtp.auth", "true");// 指定验证为true // 创建验证器
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("m17689470428", "tt199706282818");
}
}; Session session = Session.getInstance(props, auth); // 2.创建一个Message,它相当于是邮件内容
Message message = new MimeMessage(session); message.setFrom(new InternetAddress("m17689470428@163.com")); // 设置发送者 message.setRecipient(RecipientType.TO, new InternetAddress(email)); // 设置发送方式与接收者 //设置标题
message.setSubject(title);
// message.setText("这是一封激活邮件,请<a href='#'>点击</a>"); message.setContent(emailMsg, "text/html;charset=utf-8"); // 3.创建 Transport用于将邮件发送 Transport.send(message);
}
}

MailUtils.java

package com.Gary.web;

import java.util.UUID;

import org.apache.struts2.ServletActionContext;

import com.Gary.domain.User;
import com.Gary.service.UserService;
import com.Gary.utils.MailUtils;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven; //采用模型驱动 泛型User
public class UserAction extends ActionSupport implements ModelDriven<User>{ public User user = new User(); private UserService userService; //用户激活
public String active() throws Exception { System.out.println("active");
return null;
} //校验用户名是否存在
public String checkUsername() throws Exception {
//获得用户username
boolean success = userService.findUserByUsername(user.getUsername());
//获得原生Servlet对象
ServletActionContext.getResponse().getWriter().write("{\"success\":"+success+"}"); return null;
} public String register() throws Exception {
// TODO Auto-generated method stub //没有的数据手动封装
user.setState(0);
user.setCode(UUID.randomUUID().toString());
user.setImage("0");
user.setLevel(1);
user.setCoin(1000); //是否添加成功
userService.addUser(user); MailUtils.sendMail(user.getEmail(), "请激活", "恭喜您注册成功,请点击下面的链接激活!! <a href='http://localhost:8080/Gary_SSHForum/UserAction_active'>点击这里</a>"); return "toLogin"; } public UserService getUserService() {
return userService;
} public void setUserService(UserService userService) {
this.userService = userService;
} public User getModel() {
return user;
} }

UserAction.java

  编写用户激活逻辑,设置用户state属性从0变1

MailUtils.sendMail(user.getEmail(), "请激活", "恭喜您注册成功,请点击下面的链接激活!! <a href='http://localhost:8080/Gary_SSHForum/UserAction_active?userCode="+user.getCode()+"'>点击这里</a>");

  Web层用户激活

public String active() throws Exception {

        userService.activeUser(userCode);

        return "toLogin";
}

  Service层传递数据给Dao层

public void activeUser(String userCode) {
// TODO Auto-generated method stub
userDao.activeUser(userCode);
}

  Dao层修改数据库中State为1

    public void activeUser(String userCode) {
Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
String sql = "update user set state = 1 where code = ?";
NativeQuery query = session.createSQLQuery(sql);
query.setParameter(1,userCode);
query.executeUpdate();
}

  用户注册

  JavaWeb_(SSH论坛)_三、用户模块

  查看SQL数据库中用户信息

JavaWeb_(SSH论坛)_三、用户模块

  阿里云邮箱中激活用户信息

JavaWeb_(SSH论坛)_三、用户模块

  点击激活后,修改用户个人state值

JavaWeb_(SSH论坛)_三、用户模块

package com.Gary.web;

import java.util.UUID;

import org.apache.struts2.ServletActionContext;

import com.Gary.domain.User;
import com.Gary.service.UserService;
import com.Gary.utils.MailUtils;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven; //采用模型驱动 泛型User
public class UserAction extends ActionSupport implements ModelDriven<User>{ public User user = new User(); private String userCode; private UserService userService; //用户激活
public String active() throws Exception { userService.activeUser(userCode); return "toLogin";
} public String getUserCode() {
return userCode;
} public void setUserCode(String userCode) {
this.userCode = userCode;
} //校验用户名是否存在
public String checkUsername() throws Exception {
//获得用户username
boolean success = userService.findUserByUsername(user.getUsername());
//获得原生Servlet对象
ServletActionContext.getResponse().getWriter().write("{\"success\":"+success+"}"); return null;
} public String register() throws Exception {
// TODO Auto-generated method stub //没有的数据手动封装
user.setState(0);
user.setCode(UUID.randomUUID().toString());
user.setImage("0");
user.setLevel(1);
user.setCoin(1000); //是否添加成功
userService.addUser(user); MailUtils.sendMail(user.getEmail(), "请激活", "恭喜您注册成功,请点击下面的链接激活!! <a href='http://localhost:8080/Gary_SSHForum/UserAction_active?userCode="+user.getCode()+"'>点击这里</a>"); return "toLogin"; } public UserService getUserService() {
return userService;
} public void setUserService(UserService userService) {
this.userService = userService;
} public User getModel() {
return user;
} }

UserAction.java

package com.Gary.service;

import java.math.BigInteger;

import com.Gary.dao.UserDao;
import com.Gary.domain.User; public class UserService { private UserDao userDao; public UserDao getUserDao() {
return userDao;
} public void activeUser(String userCode) {
// TODO Auto-generated method stub
userDao.activeUser(userCode);
} public void setUserDao(UserDao userDao) {
this.userDao = userDao;
} public void addUser(User user) {
// TODO Auto-generated method stub
userDao.addUser(user);
} public boolean findUserByUsername(String username) {
// TODO Auto-generated method stub
Long count = userDao.findUserByUsername(username);
if(count==0)
return true;
else
return false;
} }

UserService.java

package com.Gary.dao;

import java.math.BigInteger;

import org.hibernate.Session;
import org.hibernate.query.NativeQuery;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport; import com.Gary.domain.User; public class UserDao extends HibernateDaoSupport{ public void addUser(User user) {
Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
session.save(user); } public Long findUserByUsername(String username){
// TODO Auto-generated method stub
Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
String sql = "select count(*) from user where username = ?";
NativeQuery query = session.createSQLQuery(sql); //1号位置设置为username
query.setParameter(1,username);
BigInteger result = (BigInteger)query.uniqueResult(); return result.longValue();
} public void activeUser(String userCode) {
Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
String sql = "update user set state = 1 where code = ?";
NativeQuery query = session.createSQLQuery(sql);
query.setParameter(1,userCode);
query.executeUpdate();
} }

User.Dao

用户登陆

  用户登录JavaWeb_(SSH论坛)_三、用户模块

  用户登录流程图

JavaWeb_(SSH论坛)_三、用户模块

  Service层链接出具库,在数据库中查询数据

public int checkUser(User user) {
User temp = userDao.findUserByUsernameReturnUser(user);
//用户名不存在
if(temp==null)
{
return 1;
}
//判断密码是否相同
if(temp.getPassword().equals(user.getPassword()))
{
if(temp.getState()==1)
{
//登陆成功
return 0;
}else {
//没有激活
return 3;
}
}else {
//密码错误
return 2;
} }

  Web层传递数据给Service层

public String Login() throws Exception {

        int success = userService.checkUser(user);

        if(success == 0)
{
return "toIndex";
}
else if(success ==1) {
//用户名不存在
ActionContext.getContext().put("error","用户名不存在!!");
return "login";
}
else if(success ==2) {
//密码错误
ActionContext.getContext().put("error", "密码错误");
return "login";
}
else if(success ==3) {
//用户未激活
ActionContext.getContext().put("error","用户未激活!!");
return "login";
}else {
return "error";
} }
package com.Gary.web;

import java.util.UUID;

import org.apache.struts2.ServletActionContext;

import com.Gary.domain.User;
import com.Gary.service.UserService;
import com.Gary.utils.MailUtils;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven; //采用模型驱动 泛型User
public class UserAction extends ActionSupport implements ModelDriven<User>{ public User user = new User(); private String userCode; private UserService userService; //用户登陆
public String Login() throws Exception { int success = userService.checkUser(user); if(success == 0)
{
return "toIndex";
}
else if(success ==1) {
//用户名不存在
ActionContext.getContext().put("error","用户名不存在!!");
return "login";
}
else if(success ==2) {
//密码错误
ActionContext.getContext().put("error", "密码错误");
return "login";
}
else if(success ==3) {
//用户未激活
ActionContext.getContext().put("error","用户未激活!!");
return "login";
}else {
return "error";
} } //用户激活
public String active() throws Exception { userService.activeUser(userCode); return "toLogin";
} public String getUserCode() {
return userCode;
} public void setUserCode(String userCode) {
this.userCode = userCode;
} //校验用户名是否存在
public String checkUsername() throws Exception {
//获得用户username
boolean success = userService.findUserByUsername(user.getUsername());
//获得原生Servlet对象
ServletActionContext.getResponse().getWriter().write("{\"success\":"+success+"}"); return null;
} public String register() throws Exception {
// TODO Auto-generated method stub //没有的数据手动封装
user.setState(0);
user.setCode(UUID.randomUUID().toString());
user.setImage("0");
user.setLevel(1);
user.setCoin(1000); //是否添加成功
userService.addUser(user); MailUtils.sendMail(user.getEmail(), "请激活", "恭喜您注册成功,请点击下面的链接激活!! <a href='http://localhost:8080/Gary_SSHForum/UserAction_active?userCode="+user.getCode()+"'>点击这里</a>"); return "toLogin"; } public UserService getUserService() {
return userService;
} public void setUserService(UserService userService) {
this.userService = userService;
} public User getModel() {
return user;
} }

UserAction.java

package com.Gary.service;

import java.math.BigInteger;

import com.Gary.dao.UserDao;
import com.Gary.domain.User; public class UserService { private UserDao userDao; public int checkUser(User user) {
User temp = userDao.findUserByUsernameReturnUser(user);
//用户名不存在
if(temp==null)
{
return 1;
}
//判断密码是否相同
if(temp.getPassword().equals(user.getPassword()))
{
if(temp.getState()==1)
{
//登陆成功
return 0;
}else {
//没有激活
return 3;
}
}else {
//密码错误
return 2;
} } public UserDao getUserDao() {
return userDao;
} public void activeUser(String userCode) {
// TODO Auto-generated method stub
userDao.activeUser(userCode);
} public void setUserDao(UserDao userDao) {
this.userDao = userDao;
} public void addUser(User user) {
// TODO Auto-generated method stub
userDao.addUser(user);
} public boolean findUserByUsername(String username) {
// TODO Auto-generated method stub
Long count = userDao.findUserByUsernameReturnNum(username);
if(count==0)
return true;
else
return false;
} }

UserService.java

package com.Gary.dao;

import java.math.BigInteger;

import org.hibernate.Session;
import org.hibernate.query.NativeQuery;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport; import com.Gary.domain.User; public class UserDao extends HibernateDaoSupport{ public void addUser(User user) {
Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
session.save(user); } public Long findUserByUsernameReturnNum(String username){
// TODO Auto-generated method stub
Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
String sql = "select count(*) from user where username = ?";
NativeQuery query = session.createSQLQuery(sql); //1号位置设置为username
query.setParameter(1,username);
BigInteger result = (BigInteger)query.uniqueResult(); return result.longValue();
} public void activeUser(String userCode) {
Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
String sql = "update user set state = 1 where code = ?";
NativeQuery query = session.createSQLQuery(sql);
query.setParameter(1,userCode);
query.executeUpdate();
} public User findUserByUsernameReturnUser(User user) {
Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
String sql = "select * from user where username = ?";
NativeQuery query = session.createSQLQuery(sql);
query.addEntity(User.class);
query.setParameter(1, user.getUsername());
User temp =(User) query.uniqueResult(); return temp;
} }

UserDao.java

  对用户登陆进行测试

  此时数据库中纯在两条数据

  JavaWeb_(SSH论坛)_三、用户模块

  测试失败:用户名不存在,用户密码登陆错误,用户未激活

JavaWeb_(SSH论坛)_三、用户模块

  测试成功:跳转index页面

JavaWeb_(SSH论坛)_三、用户模块

  添加一个提示用户去激活邮箱的界面

JavaWeb_(SSH论坛)_三、用户模块

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html>
<html> <head>
<meta charset="UTF-8"> <link rel="stylesheet" href="css/head.css" />
<link rel="stylesheet" type="text/css" href="css/login.css" />
</head> <body style="margin: -2px">
<iframe src="head.html" scrolling="no" width="100%" height="110px"></iframe>
<div class="dvlogo" style="color:black;margin-top:200px;margin-left:300px">
恭喜你注册成功,请到您刚填写的邮箱去激活用户!!谢谢
</div> </body>

registerSuccess.jsp

JavaWeb_(SSH论坛)_三、用户模块

<?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> <!--开启动态方法调用 -->
<constant name="struts.devMode" value="true"></constant>
<constant name="struts.enable.DynamicMethodInvocation" value="true"></constant> <!-- 告诉struts不用自己创建Action,Spring来帮你创建 -->
<constant name="struts.objectFactory" value="spring"></constant>
<package name="Gary_SSHForum" namespace="/" extends="struts-default">
<!-- 允许全部方法 -->
<global-allowed-methods>regex:.*</global-allowed-methods>
<action name="UserAction_*" class="com.Gary.web.UserAction" method="{1}">
<result name="toLogin" type="redirect">/login.jsp</result>
<result name="login">/login.jsp</result>
<result name="toIndex" type="redirect">/index.jsp</result>
<result name="error">/login.jsp</result>
<result name="toRegisterSuccess" type="redirect">/registerSuccess.jsp</result>
</action>
</package> </struts>

struct.xml

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="res/layui/css/layui.css">
<link rel="stylesheet" href="res/css/global.css">
<link rel="stylesheet" type="text/css" href="css/index.css">
<script src="res/layui/layui.js"></script>
<style>
</style>
</head>
<body>
<div class="dvhead">
<div class="dvlogo">
<a href="index.jsp" target="_parent" fount-size="34px">论坛</a>
</div>
<div class="dvsearch">Cynical丶Gary</div>
<div class="nav-user" style="top: 0px; right: 100px;"> <!--描述:未登录的样子 <a class="avatar" href="">
<img src="res/images/avatar/11.jpg">
<cite>Gary</cite>
</a>
<div class="nav">
<a href="">
<i class="iconfont icon-tuichu" style="top: 0; font-size: 22px;"></i>
退出
</a>
</div>
-->
<!--描述:未登录的样子--> <a class="iconfont icon-touxiang layui-hide-xs" style="margin-top: 4px; display: inline-block;"> </a>
<div class="nav" style="font-size: 14px; color: white; margin-top: -5px; margin-left: 1px;" />
<a href="login.jsp" target="_parent">登录</a> <a href="register.jsp" target="_parent">注册</a>
</div>
</div>
</body>
</html>

head.html

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html>
<html> <head>
<meta charset="UTF-8"> <link rel="stylesheet" href="css/head.css" />
<link rel="stylesheet" type="text/css" href="css/login.css" />
</head> <body style="margin: -2px"> <iframe src="head.html" scrolling="no" width="100%" height="110px"></iframe> <section class="sec">
<form action="${pageContext.request.contextPath }/UserAction_Login" method="post">
<div class="register-box">
<label for="username" class="username_label"> 用 户 名 <input maxlength="20" name="username" type="text" placeholder="您的用户名和登录名" />
</label>
<div class="tips"></div>
</div>
<div class="register-box">
<label for="username" class="other_label"> 密 码 <input maxlength="20" type="password" name="password" placeholder="建议至少使用两种字符组合" />
</label>
<div class="tips"></div>
</div>
<div class="arguement">
<input type="checkbox" id="xieyi" /> 阅读并同意 <a href="javascript:void(0)">《你问我答用户注册协议》</a> <a href="register.html">没有账号,立即注册</a>
<div class="tips">
<font color="red">
<s:property value="error"/>
</font>
</div>
</div>
<div class="submit_btn">
<button type="submit" id="submit_btn">立 即 登录</button>
</div>
</form>
</section>
<script src="js/index.js" type="text/javascript" charset="utf-8"></script>
</body>

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html>
<html> <head>
<meta charset="UTF-8"> <link rel="stylesheet" href="css/head.css" />
<link rel="stylesheet" type="text/css" href="css/login.css" />
</head> <body style="margin: -2px">
<iframe src="head.html" scrolling="no" width="100%" height="110px"></iframe>
<div class="dvlogo" style="color:black;margin-top:200px;margin-left:300px">
恭喜你注册成功,请到您刚填写的邮箱去激活用户!!谢谢
</div> </body>

registerSuccess.jsp

package com.Gary.web;

import java.util.UUID;

import org.apache.struts2.ServletActionContext;

import com.Gary.domain.User;
import com.Gary.service.UserService;
import com.Gary.utils.MailUtils;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven; //采用模型驱动 泛型User
public class UserAction extends ActionSupport implements ModelDriven<User>{ public User user = new User(); private String userCode; private UserService userService; //用户登陆
public String Login() throws Exception { int success = userService.checkUser(user); if(success == 0)
{
return "toIndex";
}
else if(success ==1) {
//用户名不存在
ActionContext.getContext().put("error","用户名不存在!!");
return "login";
}
else if(success ==2) {
//密码错误
ActionContext.getContext().put("error", "密码错误");
return "login";
}
else if(success ==3) {
//用户未激活
ActionContext.getContext().put("error","用户未激活!!");
return "login";
}else {
return "error";
} } //用户激活
public String active() throws Exception { userService.activeUser(userCode); return "toLogin";
} public String getUserCode() {
return userCode;
} public void setUserCode(String userCode) {
this.userCode = userCode;
} //校验用户名是否存在
public String checkUsername() throws Exception {
//获得用户username
boolean success = userService.findUserByUsername(user.getUsername());
//获得原生Servlet对象
ServletActionContext.getResponse().getWriter().write("{\"success\":"+success+"}"); return null;
} public String register() throws Exception {
// TODO Auto-generated method stub //没有的数据手动封装
user.setState(0);
user.setCode(UUID.randomUUID().toString());
user.setImage("0");
user.setLevel(1);
user.setCoin(1000); //是否添加成功
userService.addUser(user); MailUtils.sendMail(user.getEmail(), "请激活", "恭喜您注册成功,请点击下面的链接激活!! <a href='http://localhost:8080/Gary_SSHForum/UserAction_active?userCode="+user.getCode()+"'>点击这里</a>"); return "toRegisterSuccess"; } public UserService getUserService() {
return userService;
} public void setUserService(UserService userService) {
this.userService = userService;
} public User getModel() {
return user;
} }

UserAction.java

package com.Gary.service;

import java.math.BigInteger;

import com.Gary.dao.UserDao;
import com.Gary.domain.User; public class UserService { private UserDao userDao; public int checkUser(User user) {
User temp = userDao.findUserByUsernameReturnUser(user);
//用户名不存在
if(temp==null)
{
return 1;
}
//判断密码是否相同
if(temp.getPassword().equals(user.getPassword()))
{
if(temp.getState()==1)
{
//登陆成功
return 0;
}else {
//没有激活
return 3;
}
}else {
//密码错误
return 2;
} } public UserDao getUserDao() {
return userDao;
} public void activeUser(String userCode) {
// TODO Auto-generated method stub
userDao.activeUser(userCode);
} public void setUserDao(UserDao userDao) {
this.userDao = userDao;
} public void addUser(User user) {
// TODO Auto-generated method stub
userDao.addUser(user);
} public boolean findUserByUsername(String username) {
// TODO Auto-generated method stub
Long count = userDao.findUserByUsernameReturnNum(username);
if(count==0)
return true;
else
return false;
} }

UserService.java

package com.Gary.dao;

import java.math.BigInteger;

import org.hibernate.Session;
import org.hibernate.query.NativeQuery;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport; import com.Gary.domain.User; public class UserDao extends HibernateDaoSupport{ public void addUser(User user) {
Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
session.save(user); } public Long findUserByUsernameReturnNum(String username){
// TODO Auto-generated method stub
Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
String sql = "select count(*) from user where username = ?";
NativeQuery query = session.createSQLQuery(sql); //1号位置设置为username
query.setParameter(1,username);
BigInteger result = (BigInteger)query.uniqueResult(); return result.longValue();
} public void activeUser(String userCode) {
Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
String sql = "update user set state = 1 where code = ?";
NativeQuery query = session.createSQLQuery(sql);
query.setParameter(1,userCode);
query.executeUpdate();
} public User findUserByUsernameReturnUser(User user) {
Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
String sql = "select * from user where username = ?";
NativeQuery query = session.createSQLQuery(sql);
query.addEntity(User.class);
query.setParameter(1, user.getUsername());
User temp =(User) query.uniqueResult(); return temp;
} }

User.Dao

项目过程中的问题

一、Struts has detected an unhandled exception:

Messages:
  1. Duplicate entry 'Gary' for key 'username_UNIQUE'
  2. could not execute statement
  3. could not execute statement; SQL [n/a]; constraint [username_UNIQUE]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement

JavaWeb_(SSH论坛)_三、用户模块

  注册信息重名,不能添加重复的username