实现用户注册与登陆模块
注册界面:

登陆界面:

一、定义UserService其它接口并将其实现
/**
* 用户注册
* @param user
*/
public void register(User user);
/**
* 判断用户是否存在
* @param username
* @return
*/
public boolean exsit(String username);
/**
* 判断用户名及密码是否通过
* @param username
* @param password
* @return
*/
public boolean validate(String username,String password);
/**
* 更新密码
* @param username 用户名
* @param newpassword 新密码
*/
public void updatePassword(String username, String newpassword);
/**
* 判断邮箱是否已注册
* @param email
* @return
*/
public boolean exsitEmail(String email);
/**
* 更新注册邮箱
* @param username
* @param newemail
*/
public void updateEmail(String username,String newemail);
实现类:
@Service("userServiceBean")
public class UserServiceBean extends DaoSupport<User> implements UserService {
@Resource(name="userRoleServiceBean")
private UserRoleService userRoleService;
public void updateEmail(String username,String newemail){
em.createQuery("update User o set o.email=?1 where o.username=?2")
.setParameter(1, newemail).setParameter(2, username).executeUpdate();
}
public void updatePassword(String username, String newpassword){
em.createQuery("update User o set o.password=?1 where o.username=?2")
.setParameter(1, MD5.MD5Encode(newpassword)).setParameter(2, username).executeUpdate();
}
public void register(User user){
//对密码进行md5加密
user.setUserrole(userRoleService.getReference("user"));
UserGrade userGrade = new UserGrade();
user.setUsergrade(userGrade);
UserInfo userInfo = new UserInfo();
userInfo.setNickname(user.getUsername());
user.setUserinfo(userInfo);
user.setPassword(MD5.MD5Encode(user.getPassword()));
super.save(user);
}
@Transactional(propagation=Propagation.NOT_SUPPORTED)
public boolean exsitEmail(String email){
long count = (Long)em.createQuery("select count(o) from User o where o.email=?1")
.setParameter(1, email).getSingleResult();
return count>0;
}
@Transactional(propagation=Propagation.NOT_SUPPORTED)
public boolean exsit(String username){
long count = (Long)em.createQuery("select count(o) from User o where o.username=?1")
.setParameter(1, username).getSingleResult();
return count>0;
}
@Transactional(propagation=Propagation.NOT_SUPPORTED)
public boolean validate(String username,String password){
long count = (Long)em.createQuery("select count(o) from User o where o.username=?1 and o.password=?2")
.setParameter(1, username).setParameter(2, MD5.MD5Encode(password)).getSingleResult();
return count>0;
}
}
知识提示: 注册的同时需对密码进行md5加密
二、UserRegAction类的实现
@Controller("userRegAction") @Scope("prototype")
public class UserRegAction extends ActionSupport{
private static final long serialVersionUID = 1159518406043666180L;
private User user;
private String repassword;
private String code;
@Resource(name="userServiceBean")
private UserService userService;
public String getRepassword() {
return repassword;
}
public void setRepassword(String repassword) {
this.repassword = repassword;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
/**
* 打开用户注册界面
* @return
* @throws Exception
*/
public String registerUI()throws Exception{
return Action.SUCCESS;
}
/**
* 用户注册
* @return
* @throws Exception
*/
public String register() throws Exception {
String validateCode = (String)ActionContext.getContext().getSession().get("validateCode");
if(!validateCode.equals(this.getCode())){
this.addFieldError("codeerror","验证码有误!");
return Action.INPUT;
}
//判断用户是否存在
if(userService.exsit(user.getUsername().trim())){
this.addFieldError("user.username", "用户名已存在!");
return Action.INPUT;
}
//判断邮箱是否已初注册过
if(userService.exsitEmail(user.getEmail().trim())){
this.addFieldError("user.email", "邮箱已被注册过!");
return Action.INPUT;
}
userService.register(user);
return Action.SUCCESS;
}
}
基于xml的数据验证,文件跟action在同一个目录下,并命名为:UserRegAction-register-validation.xml,register是action名.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.3//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.3.dtd">
<validators>
<field name="user.username">
<field-validator type="requiredstring">
<!-- 默认为true -->
<param name="trim">true</param>
<message>用户名不能为空!</message>
</field-validator>
<field-validator type="stringlength">
<param name="maxLength">15</param>
<param name="minLength">6</param>
<!-- 给用户显示的提示信息,可以国际化 -->
<message>用户名长度在${minLength}~${maxLength}之间!</message>
</field-validator>
</field>
<field name="user.password">
<field-validator type="requiredstring">
<!-- 默认为true -->
<param name="trim">true</param>
<message>密码不能为空!</message>
</field-validator>
<field-validator type="stringlength">
<param name="maxLength">15</param>
<param name="minLength">6</param>
<!-- 给用户显示的提示信息,可以国际化 -->
<message>密码长度在${minLength}~${maxLength}之间!</message>
</field-validator>
</field>
<field name="repassword">
<field-validator type="requiredstring">
<!-- 默认为true -->
<param name="trim">true</param>
<message>重复密码不能为空!</message>
</field-validator>
<field-validator type="fieldexpression">
<param name="expression"><![CDATA[repassword.equals(user.password)]]></param>
<message>密码输入不一致!</message>
</field-validator>
</field>
<field name="user.email">
<field-validator type="requiredstring">
<message>电子邮箱不能为空!</message>
</field-validator>
<field-validator type="email">
<message>电子邮箱格式不正确!</message>
</field-validator>
</field>
</validators>
知识提示: 这个配置文件支持正则表达式(如:${minLength})和ognl表达式(如:repassword.equals(user.password))
2.2 配置struts-user.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="forward" namespace="/" extends="struts-default">
<!-- 用户注册界面 -->
<action name="registerUI" class="userRegAction" method="registerUI">
<result>/WEB-INF/forward/register.jsp</result>
</action>
<!-- 用户注册 -->
<action name="register" class="userRegAction" method="register">
<result name="input">/WEB-INF/forward/register.jsp</result>
<result name="success">/WEB-INF/forward/register_comp.jsp</result>
</action>
<!-- 用户登陆界面 -->
<action name="loginUI" class="userLoginAction" method="loginUI">
<result name="success">/WEB-INF/forward/login.jsp</result>
</action>
<!-- 用户登陆 -->
<action name="login" class="userLoginAction" method="login">
<result name="input">/WEB-INF/forward/login.jsp</result>
<result name="success" type="redirectAction">index</result>
</action>
<!-- 判断用户或邮箱是否被注册过 -->
<action name="*_Exist" class="usernameOrEmailExistAction" method="{1}">
</action>
<!-- 前台主页 -->
<action name="index">
<result>/WEB-INF/forward/index.jsp</result>
</action>
</package>
</struts>
2.3 验证码Servlet: VerifyCodeServlet,这个验证的实现也不是很好! 大家有没有更好的实现.在web.xml文件配置:
<!-- 验证码 --> <servlet> <servlet-name>VerifyCodeServlet</servlet-name> <servlet-class>cn.daxia.web.servlet.verify.VerifyCodeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>VerifyCodeServlet</servlet-name> <url-pattern>/verifyCodeServlet</url-pattern> </servlet-mapping>
2.4 设置basePath: 写一个filter-->MyPrepareAndExecuteFilter,继承StrutsPrepareAndExecuteFilter,重新配置web.xml文件
public class MyPrepareAndExecuteFilter extends StrutsPrepareAndExecuteFilter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
super.init(filterConfig);
}
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
//转换成HttpServletRequest
HttpServletRequest request = (HttpServletRequest)req;
ServletContext context = request.getSession().getServletContext();
if(context.getAttribute("basePath")==null){
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
context.setAttribute("basePath", basePath);
}
super.doFilter(req, res, chain);
}
}
改写filter,此解决方案个人觉得不是很好,大家有没有其他方案
<filter>
<filter-name>struts2</filter-name>
<filter-class>cn.daxia.web.filter.MyPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2.5 用户注册js验证文件在/js/user/register.js,验证用户或邮箱是否存在用了ajax实现,使用的js库是jquery1.3,js代码没有重构,比较乱
function ajaxUserNameSumbit(url,post){
$.ajax({
type: "post",
url: url,
data: post,
success: function(msg){
if(msg=='notexist'){
document.forms[0].uservalidate.value='true';
$("#usermsg").css("display","inline").html("<div class='rightSign'></div><font color='green'>您可以使用该用户名!</font>").fadeIn("slow");
}else{
document.forms[0].uservalidate.value='false';
$("#usermsg").css("display","inline").html("<div class='errorSign'></div><font color='red'>此用户名已被使用!</font>").fadeIn("slow");;
}
}
});
}
三、用户登陆部分大家不访自己去实现一下
本文介绍了一个简单的用户注册与登录系统的实现过程,包括用户注册时的密码MD5加密、邮箱验证等功能,以及利用Struts2框架进行界面展示和交互。
1万+

被折叠的 条评论
为什么被折叠?



