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

  一、项目入门  传送门

  二、框架整合  传送门

  三、用户模块  传送门

  四、页面显示  传送门

  五、帖子模块  传送门

  六、点赞模块  传送门

  七、辅助模块  传送门

User表

  id:

  username:登陆账号

  password:登陆密码

  name:用户名

  email:用户邮箱

  telephone:用户电话

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

  code:

  image:用户头像

  level:用户等级

  coin:金币

(根据用户表单进行创建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>

   测试

  在项目中进行表单注册

表单校验

  页面自带表单校验

  通过引入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>

<%@ 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" )
})
})

  

  

  基于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"
)
})
})

<%@ 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

邮箱注册

  

    

  邮箱类

// 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;
}

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();
}

  用户注册

  

  查看SQL数据库中用户信息

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

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

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

用户登陆

  用户登录

  用户登录流程图

  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

  对用户登陆进行测试

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

  

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

  测试成功:跳转index页面

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

<%@ 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

<?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

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

 

JavaWeb_(SSH论坛)_三、用户模块的更多相关文章

  1. JavaWeb_(SSH论坛)_七、辅助模块

    基于SSH框架的小型论坛项目 一.项目入门 传送门 二.框架整合 传送门 三.用户模块 传送门 四.页面显示 传送门 五.帖子模块 传送门 六.点赞模块 传送门 七.辅助模块 传送门 为避免代码冗余, ...

  2. JavaWeb_(SSH论坛)_六、点赞模块

    基于SSH框架的小型论坛项目 一.项目入门 传送门 二.框架整合 传送门 三.用户模块 传送门 四.页面显示 传送门 五.帖子模块 传送门 六.点赞模块 传送门 七.辅助模块 传送门 联合主键 创建p ...

  3. JavaWeb_(SSH论坛)_五、帖子模块

    基于SSH框架的小型论坛项目 一.项目入门 传送门 二.框架整合 传送门 三.用户模块 传送门 四.页面显示 传送门 五.帖子模块 传送门 六.点赞模块 传送门 七.辅助模块 传送门 回复帖子 分析回 ...

  4. JavaWeb_(SSH论坛)_一、项目入门

    基于SSH框架的小型论坛项目 一.项目入门 传送门 二.框架整合 传送门 三.用户模块 传送门 四.页面显示 传送门 五.帖子模块 传送门 六.点赞模块 传送门 七.辅助模块 传送门 项目已上传至gi ...

  5. JavaWeb_(SSH论坛)_四、页面显示

    基于SSH框架的小型论坛项目 一.项目入门 传送门 二.框架整合 传送门 三.用户模块 传送门 四.页面显示 传送门 五.帖子模块 传送门 六.点赞模块 传送门 七.辅助模块 传送门 帖子表与回复表 ...

  6. JavaWeb_(SSH论坛)_二、框架整合

    基于SSH框架的小型论坛项目 一.项目入门 传送门 二.框架整合 传送门 三.用户模块 传送门 四.页面显示 传送门 五.帖子模块 传送门 六.点赞模块 传送门 七.辅助模块 传送门 导入Jar包 导 ...

  7. JavaWeb_(Mybatis框架)Mapper动态代理开发_三

    系列博文: JavaWeb_(Mybatis框架)JDBC操作数据库和Mybatis框架操作数据库区别_一 传送门 JavaWeb_(Mybatis框架)使用Mybatis对表进行增.删.改.查操作_ ...

  8. bookStore第三篇【用户模块、购买模块、订单模块】

    用户模块 要登陆后才能购买,因此我们先写购买模块 设计实体 private String id; private String username; private String password; p ...

  9. SSH实战OA 11:BBS模块

    <SSH实战OA>系列博客的系统管理.权限管理等内容后面再补上吧,先继续第三个模块:网上交流模块.网上交流主要做两个需求:论坛管理和论坛. BBS的一些基本术语: 板块:也叫做" ...

随机推荐

  1. # jsp及servlet学习笔记

    目录 jsp及servlet学习笔记 JSP(Java Server Page Java服务端网页) 指令和动作: servlet(小服务程序) jsp及servlet学习笔记 JSP(Java Se ...

  2. vue : 无法加载文件 C:\Users\lihongjie\AppData\Roaming\npm\vue.ps1,因为在此系统上禁止运行脚本。有关详细信息,请参阅 htt ps:/go.microsoft.com/fwlink/?LinkID=135170 中的 about_Execution_Policies。 所在位置 行:1 字符: 1 + vue init webpack vue_p

    以管理员方式打开powershell 运行命令:set-ExecutionPolicy RemoteSigned 出现: 执行策略更改执行策略可帮助你防止执行不信任的脚本.更改执行策略可能会产生安全风 ...

  3. Bat批处理文件入门

    这个东西吧,感觉在使用windows时作用不是很大,毕竟在windows环境下命令行确实用的比较少,但有时候也会用到,比如测试算法程序时使用批处理+文件可以省去每次手动输入.赶巧最近对批处理也比较感兴 ...

  4. debezium关于cdc的使用(上)

    博文原址:debezium关于cdc的使用(上) 简介 debezium是一个为了捕获数据变更(cdc)的开源的分布式平台.启动并指向数据库,当其他应用对此数据库执行inserts.updates.d ...

  5. 15 Scrapy框架之CrawlSpider

    一.简介 CrawlSpider其实是Spider的一个子类,除了继承到Spider的特性和功能外,还派生除了其自己独有的更加强大的特性和功能.其中最显著的功能就是”LinkExtractors链接提 ...

  6. 原生JS+CSS实现日期插件

    笔者最近在学习Element UI,觉得它提供的日期选择器既简单又美观,于是仿照着写了一个日期插件.笔者使用到的技术有ES5.CSS和HTML,控件兼容IE10+和谷歌浏览器.有一点需要注意,笔者使用 ...

  7. CSS media queries 媒体查询

    最近在做一些页面打印时的特殊处理接触到了media queries,想系统学习一下,在MOZILLA DEVELOPER NETWORK看到一篇文章讲的很不错,结合自己的使用总结一下. CSS2/me ...

  8. JAVA核心技术--继承(1)

    1.继承:向上追溯,对同一批类的抽象,延续和扩展父类的一切信息! 1)关键字:extends      例如,父类是Animal,子类是Dog;   eg: public class Dog exte ...

  9. 写两个线程,一个线程打印1-52,另一个线程打印A-Z,打印顺序为12A34B56C......5152Z

    题目: 写两个线程,一个线程打印1-52,另一个线程打印A-Z,打印顺序为12A34B56C......5152Z.要求用线程间的通信. /** * 写两个线程,第一个线程打印1-52,第二个线程打印 ...

  10. python视频学习笔记5(高级变量的类型)

    知识点回顾: Python 中数据类型可以分为 **数字型** 和 **非数字型*** 数字型 * 整型 (`int`) * 浮点型(`float`) * 布尔型(`bool`) * 真 `True` ...