您的位置:首页 > 其它

会员卡管理系统技术解析(五)登陆与注册之登陆

2015-05-28 21:32 302 查看

会员卡管理系统技术解析(五)登陆与注册之登陆

登陆是用户是否被允许对系统进行资源访问以及操作的一个权限标记。这里可以通过账号密码登陆,以及验证码防止非法登陆等。

1、界面效果图:



1.1(图1)

从界面可以看到本项目这里用到的控件有:

控件名称

说明
文本框(表单元素input)
第一要设置每个控件的id,第二设置样式不设置也有默认,第三(data-options)是数据操作:可以设置控件的一些属性和事件
图片按钮(img)
文本标签(span)

2、功能实现:

第1步:数据库(与控件使用方法)
1、表与关系

表1:用户表(Sys_User)

用于存放用户信息

列名

数据类型
主键/外键
说明
userID
int
主键
用户ID
userName
nchar(50)
 
用户名
pwd
nchar(120)
 
密码
StaffID
int
外键
员工表,员工ID
2、控件的使用:

1. 文本框(表单元素input)

A.普通文本框

作用:输入并显示文本

普通文本框截图(如:本登陆界面的验证码输入框):



创建普通文通文本框代码:

<input name="userName" type="text" id="userName"  style="height:22px;width:105px;outline:none; vertical-align:middle;" />


含图标文本框截图(如:本登陆界面的用户名输入框):



创建如图文本框代码:

<div class="div1">
<input name="userName" type="text" id="userName"  style="height:22px;width:105px;outline:none; vertical-align:middle;" />
</div>


div1对应的样式代码:

<style type="text/css">
.div1 {
padding-left: 30px;
background: url(Content/photos/1.png) 4px no-repeat;
/*设置背景图片,background:url(背景连接)  位置   重复类型
*重复类型有:repeat(水平和垂直方向重复),
*repeat-x(水平方向重复),repeat-y(垂直方向重复),
*no-repeat(不重复)*/
background-color: #FFFFFF; /*设置背景颜色为白色*/
width: 105px; /*设置宽度*/
height: 25px; /*设置高度*/
line-height: 25px; /*设置行高*/
border: 1px solid #ccc;
/*设置边框,格式:border:边框宽度  边框类型  边框颜色
*边框类型有:dotted(点状线),solid(实线),
*double(双线),dashed(虚线),•••*/
}
</style>


B.密码文本框

作用:用小圆点或其他符号掩盖显示输入的文本框内容,只允许粘贴和输入,不允许复制、剪切。以保护密码不被偷窥窃取

密码文本框截图:



创建密码文本框代码:

<input name="pwd" type="password" id="pwd" style="height:22px;width:105px;outline:none;vertical-align:middle;" onpaste="return false" oncontextmenu="return false" oncopy="return false" oncut="return false"/>


给文本框赋值的代码:

$('#pwd).val("");


获取文本框值的代码:

$('#pwd).val();


2. 图片按钮(img)

作用:以图片作为按钮,使其在美观的同时,拥有按钮(button)的功能。

图片按钮截图:



创建图片按钮代码:

<img src="Content/photos/btnDengLu.jpg" style="cursor:hand" width="70" height="26"  onclick="loginOnClick()"/>


第2步:编写IDAO(与数据库联系的接口)和DAO(接口实现)
A、编写IDAO(与数据库联系的接口)

首先,创建一个包,名为“MEMBCERP.IDAO”,然后,在这个包下创建类,一个名为“Page”,另一个名为“IDAO”。结果如下图:



1.1.2.2(图1)
接着,把下面我写好的通用类代码复制到“Page.java”这个类中,代码如下:

package MEMBCERP.IDAO;

import java.util.ArrayList;
import java.util.List;

public class Page<T> {
//当前页数
private int currentPage;
//总页数
private int totalsPage;
//每页显示记录条数
private int pageSize;
//总记录条数
private int totalsCount;
//查询返回结果
private List<T> result = new ArrayList<T>();
//分页链接
private String uri;
public String getUri() {

return uri;

}
public void setUri(String uri) {

this.uri = uri;

}
public int getCurrentPage() {

return currentPage;

}
public void setCurrentPage(int currentPage) throws Exception {

if (currentPage < 0) {

currentPage = 0;

}

this.currentPage = currentPage;

}
public int getTotalsPage() {
try {

if (totalsCount % pageSize == 0) {

totalsPage = totalsCount / pageSize;

} else {

totalsPage = (totalsCount / pageSize) + 1;

}

} catch (Exception e) {

throw new RuntimeException(e);

}

return totalsPage;

}
public void setTotalsPage(int totalsPage) {

if (totalsPage < 0) {

totalsPage = 0;

}

this.totalsPage = totalsPage;

}
public int getPageSize() {

return pageSize;

}
public void setPageSize(int pageSize) {

if (pageSize <= 0) {

pageSize = 20;

}

this.pageSize = pageSize;

}
public int getTotalsCount() {

return totalsCount;

}
public void setTotalsCount(int totalsCount) {

if (totalsCount < 0) {

totalsCount = 0;

}

this.totalsCount = totalsCount;

}
public List<T> getResult() {

return result;

}
public void setResult(List<T> result) {

this.result = result;

}
}


最后,把下面我写好的通用类代码复制到“IDAO.java”这个类中,代码如下:

package yite.com.IDAO;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate3.HibernateTemplate;
import yite.com.DAO.Page;
/**
*
* @author phreez
*  this is a DAO(Data Access Object) interface
*/
public interface IDAO  {
public <T> boolean add(T entity,Object[] param) throws Exception;
public <T> Integer addAndGetId4Integer(T entity) throws Exception;
public <T> String addAndGetId4String(T entity) throws Exception;
public int executeByHql(String hql) throws Exception;
public <T> List<T> findByHql(String hql,Object[] val) throws Exception;
public <T> List<T> findByHql(String hql) throws Exception;
public int executeBySql(String sql) throws Exception;
public <T> List<T> findBySql(String sql) throws Exception;
public <T> boolean edit(T entity) throws Exception;
public boolean edit(String hql) throws Exception;
public int editByHql(String hql) throws Exception;
public <T> boolean remove(T entity) throws Exception;
public <T> T getById(Class<T> c, String id) throws Exception;
public <T>  T getById(Class<T> c, Integer id) throws Exception;
public <T> T get(Class<T> c, Serializable id) throws Exception;
public <T> T get(String hql) throws Exception;
public <T> List<T> getList(String hql) throws Exception;
public boolean remove(String hql) throws Exception;
public <T> List<T> getList(Class<T> c) throws Exception;
public <T> List<T> getList(String hql, Object[] obj) throws Exception;
public List<?> showPage(String queryHql, String queryCountHql, int firstResult, int maxResult) throws Exception;
public <T> void showPage(String queryHql, String queryCountHql, Page<T> page) throws Exception;
public List<?> showPage(String queryCountHql, DetachedCriteria cResult, int firstResult, int maxResult) throws Exception;
public <T> void showPage(String queryCountHql, DetachedCriteria cResult, Page<T> page) throws Exception;
public <T> List<T> find(DetachedCriteria dc) throws Exception;
public Session session();
public HibernateTemplate getTemplate();
}


B、 DAO(接口实现)

首先,创建一个包,名为“MEMBCERP.DAO”,然后,在这个包下创建一个类,名为“baseDAO”。结果如下图:



1.1.2.2(图2)

接着,把下面我写好的通用类代码复制到“baseDAO.java”这个类中,代码如下:

package MEMBCERP.DAO;

import java.io.Serializable;

/*注意 getHibernateTemplate() 方法和 getSession() 方法有区别。
* getHibernateTemplate()方法是Spring对SessionFactory的封装,
* 里面包含各种事务管理操作;
* 而 getSession() 方法要自己实现事务操作*/
import java.util.ArrayList;
import java.util.List;

import org.hibernate.*;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import MEMBCERP.IDAO.IDAO;
import MEMBCERP.IDAO.Page;

@SuppressWarnings("unchecked")
public class baseDAO extends HibernateDaoSupport implements IDAO {

@Override
public <T> boolean add(T entity,Object[] param) throws Exception {
boolean bo = false;
try {
Serializable io = this.getHibernateTemplate().save(entity);
if (io != null) {
bo = true;
}
} catch (Exception e) {
bo = false;
throw new RuntimeException(e);
}
return bo;
}

@Override
public <T> Integer addAndGetId4Integer(T entity) throws Exception {
Integer id = null;
try {
id = (Integer) this.getHibernateTemplate().save(entity);
} catch (Exception e) {
throw new RuntimeException(e);
}
return id;
}

@Override
public <T> String addAndGetId4String(T entity) throws Exception {
String id = null;
try {
id = (String) this.getHibernateTemplate().save(entity);
} catch (Exception e) {
throw new RuntimeException(e);
}
return id;
}

@Override
public int executeByHql(String hql) throws Exception {
try {

return this.getHibernateTemplate().bulkUpdate(hql);

} catch (Exception e) {

throw new RuntimeException(e);

}
}

@Override
public <T> List<T> findByHql(String hql,Object[] val) throws Exception {
List<T> list = null;
try {
list=this.getHibernateTemplate().find(hql, val);
//query.uniqueResult();
//for (int i=0;i<val.length;i++){
//query.setParameter(i, val[i]);
//}
//list=query.list();
//list = (List<T>) this.getHibernateTemplate().find(hql,password);
} catch (Exception e) {
throw new RuntimeException(e);
}
return list;
}

@Override
public int executeBySql(String sql) throws Exception {
try {
return this.getSession().createSQLQuery(sql).executeUpdate();
} catch (Exception e) {
throw new RuntimeException(e);
}
}

@Override
public <T> List<T> findBySql(String sql) throws Exception {
List<T> list = null;
try {
list = (List<T>) this.getSession().createSQLQuery(sql).list();
} catch (Exception e) {
throw new RuntimeException(e);
}
return list;
}

@Override
public <T> boolean edit(T entity) throws Exception {
boolean bo = false;
try {

this.getHibernateTemplate().update(entity);
bo = true;
} catch (Exception e) {
bo = false;
throw new RuntimeException(e);
}
return bo;
}

@Override
public boolean edit(String hql) throws Exception {
boolean bo = false;
try {
int count = this.getHibernateTemplate().bulkUpdate(hql);
bo = count > 0 ? true : false;
} catch (Exception e) {
bo = false;
throw new RuntimeException(e);
}
return bo;
}

@Override
public int editByHql(String hql) throws Exception {
int count = 0;
try {
count = this.getHibernateTemplate().bulkUpdate(hql);
} catch (Exception e) {
throw new RuntimeException(e);
}
return count;
}

@Override
public <T> boolean remove(T entity) throws Exception {
boolean bo = false;
try {
this.getHibernateTemplate().delete(entity);
bo = true;
} catch (Exception e) {
bo = false;
throw new RuntimeException(e);
}
return bo;
}

@Override
public <T> T getById(Class<T> c, String id) throws Exception {
T ety = null;
try {
ety = (T) this.getHibernateTemplate().get(c, id);
} catch (Exception e) {
throw new RuntimeException(e);
}
return ety;
}

@Override
public <T> T getById(Class<T> c, Integer id) throws Exception {
T ety = null;
try {
ety = (T) this.getHibernateTemplate().get(c, id);
} catch (Exception e) {
throw new RuntimeException(e);
}
return ety;
}

@Override
public <T> T get(Class<T> c, Serializable id) throws Exception {
T ety = null;
try {
ety = (T) this.getHibernateTemplate().get(c, id);
} catch (Exception e) {
throw new RuntimeException(e);
}
return ety;
}

@Override
public <T> T get(String hql) throws Exception {
T ety = null;
try {
ety = (T) this.getSession().createQuery(hql).setMaxResults(1).uniqueResult();
} catch (Exception e) {
throw new RuntimeException(e);
}
return ety;
}

@Override
public <T> List<T> getList(String hql) throws Exception {
List<T> list = null;
try {
list = (List<T>) this.getHibernateTemplate().find(hql);
} catch (Exception e) {
throw new RuntimeException(e);
}
return list;
}

@Override
public boolean remove(String hql) throws Exception {
try {
return this.getHibernateTemplate().bulkUpdate(hql) > 0 ? true : false;
} catch (Exception e) {
throw new RuntimeException(e);
}
}

@Override
public <T> List<T> getList(Class<T> c) throws Exception {
List<T> list = null;
try {
this.getHibernateTemplate().findByCriteria(DetachedCriteria.forClass(c));
} catch (Exception e) {
throw new RuntimeException(e);
}
return list;
}

@Override
public <T> List<T> getList(String hql, Object[] obj) throws Exception {
List<T> list = null;
try {
list = (List<T>) this.getHibernateTemplate().find(hql, obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
return list;
}

@Override
public List<?> showPage(String queryHql, String queryCountHql,
int firstResult, int maxResult) throws Exception {
List<Object> list = new ArrayList<Object>();
try {
Session session = this.getSession();
list.add(session.createQuery(queryHql)
.setFirstResult(firstResult).setMaxResults(maxResult).list());
list.add(session.createQuery(queryCountHql).setMaxResults(1).uniqueResult());
} catch (Exception e) {
throw new RuntimeException(e);
}
return list;
}

@Override
public <T> void showPage(String queryHql, String queryCountHql, Page<T> page)
throws Exception {
try {
Session session = this.getSession();
page.setResult(session.createQuery(queryHql)
.setFirstResult(page.getCurrentPage()).setMaxResults(page.getPageSize()).list());
page.setTotalsCount(Integer.parseInt(session.createQuery(queryCountHql).setMaxResults(1).uniqueResult().toString()));
} catch (Exception e) {
throw new RuntimeException(e);
}
}

@Override
public List<?> showPage(String queryCountHql, DetachedCriteria cResult,
int firstResult, int maxResult) throws Exception {
List<Object> list = new ArrayList<Object>();
try {
Session session = this.getSession();
list.add(this.getHibernateTemplate().findByCriteria(cResult, firstResult, maxResult));
list.add(session.createQuery(queryCountHql).setMaxResults(1).uniqueResult());
} catch (Exception e) {
throw new RuntimeException(e);
}
return list;
}

@Override
public <T> void showPage(String queryCountHql, DetachedCriteria cResult,
Page<T> page) throws Exception {
try {
Session session = this.getSession();
page.setResult(this.getHibernateTemplate().findByCriteria(cResult, page.getCurrentPage(), page.getPageSize()));
page.setTotalsCount(Integer.parseInt(session.createQuery(queryCountHql).setMaxResults(1).uniqueResult().toString()));
} catch (Exception e) {
throw new RuntimeException(e);
}
}

@Override
public <T> List<T> find(DetachedCriteria dc) throws Exception {
List<T> list = new ArrayList<T>();
try {
list = (List<T>) this.getHibernateTemplate().findByCriteria(dc);
} catch (Exception e) {
throw new RuntimeException(e);
}
return list;
}

@Override
public Session session() {
return this.getSession();
}

@Override
public HibernateTemplate getTemplate() {
return this.getHibernateTemplate();
}

@Override
public <T> List<T> findByHql(String hql) throws Exception {
List<T> list = null;
try {
list = (List<T>) this.getHibernateTemplate().find(hql);
} catch (Exception e) {
throw new RuntimeException(e);
}
return list;
}

}


第3步:服务层接口(Iservice)
首先,创建一个包,名为“MEMBCERP.IService”,然后,在这个包下创建一个类,名为“LoginIService”。结果如下图:



1.1.2.3(图1)
接着,更改LoginIService类的类型,如下图:



1.1.2.3(图2)
最后,定义一个登陆的方法接口,代码如下:

package MEMBCERP.IService;
//服务层接口
public interface LoginIService {
public int Login(String userName, String pwd);//用户登陆

}


第4步:服务层(service)
首先,创建一个包,名为“MEMBCERP.Service”,然后,在这个包下创建一个类,名为“LoginService”。结果如下图:



1.1.2.4(图1)
然后,实现 LoginIService接口并实现登陆验证,代码如下:

package MEMBCERP.Service;

import java.util.List;

import MEMBCERP.IDAO.IDAO;
import MEMBCERP.IService.LoginIService;
import MEMBCERP.pojo.SysRoleOfEmployees;
import MEMBCERP.pojo.SysStaff;
import MEMBCERP.pojo.SysUser;

public class LoginService implements LoginIService{
private IDAO dao;/*操作数据库的数据使用类型*/

public IDAO getDao() {
return dao;
}

public void setDao(IDAO dao) {
this.dao = dao;
}

@Override
/*服务层接口实现-用户登陆验证方法
* userName 用户名
* pwd 密码
* */
public int Login(String userName, String pwd) {
/*实例化StringBuffer*/
StringBuffer queryString = new StringBuffer();
queryString.append("FROM SysUser as u " + //实例化表
"WHERE u.userName = ? AND u.pwd = ?"); //满足条件
try {/*尝试运行代码*/
SysUser user =(SysUser)this.dao.findByHql(queryString.toString(), new Object[]{userName,pwd}).get(0);
return user.getUserId();
} catch (Exception e) {/*尝试运行代码出现错误,执行异常处理*/
return 0;
}
}
}


第5步:方法层(Action)
首先,创建一个包,名为“MEMBCERP.Action”,然后,在这个包下创建一个类,名为“baseAction”。结果如下图:



1.1.2.5(图1)
然后,把下面我写好的通用类代码复制到“baseAction.java”这个类中,代码如下:

package MEMBCERP.Action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ServletRequestAware;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public abstract class baseAction extends ActionSupport implements ServletRequestAware {
private HttpServletRequest request;
private HttpSession session;
@Override
public void setServletRequest(HttpServletRequest arg0) {
this.request=arg0;
this.session=this.request.getSession();
}
public HttpServletRequest getRequest() {
return request;
}
public void setRequest(HttpServletRequest request) {
this.request = request;
}
public HttpSession getSession() {
return session;
}
public void setSession(HttpSession session) {
this.session = session;
}
}


接着,再新建一个类“LoginAction”,结果如下图:



1.1.2.5(图2)
然后,继承BaseAction,并实现登陆验证,代码如下:

package MEMBCERP.Action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import MEMBCERP.IService.LoginIService;

public class LoginAction extends baseAction{
private LoginIService loginService;
private JSONArray JSArr;
private JSONObject JSObj;
private int INT;
public int getINT() {
return INT;
}
public void setINT(int iNT) {
INT = iNT;
}
private String MSG;
public LoginIService getLoginService() {
return loginService;
}
public void setLoginService(LoginIService loginService) {
this.loginService = loginService;
}
public String getMSG() {
return MSG;
}
public void setMSG(String mSG) {
MSG = mSG;
}

public JSONArray getJSArr() {
return JSArr;
}
public void setJSArr(JSONArray jSArr) {
JSArr = jSArr;
}
public JSONObject getJSObj() {
return JSObj;
}
public void setJSObj(JSONObject jSObj) {
JSObj = jSObj;
}
//登录验证
public String login(){
String userName= this.getRequest().getParameter("userName");//获取页面传递过来的参数userName
String pwd=this.getRequest().getParameter("pwd");//获取页面传递过来的参数pwd
int userId=this.loginService.Login(userName, pwd);//验证用户
String vCode=this.getRequest().getParameter("vCode").toLowerCase();//获取验证码
if (userId > 0) {
if(ActionContext.getContext().getSession().get("randomImg").toString().toLowerCase().equals(vCode)){ //校检验证码
HttpServletRequest request =ServletActionContext.getRequest();
request.getSession().setAttribute("username", userName);				//将userName存放到session中
request.getSession().setAttribute("userid", Integer.toString(userId));  //将userId存放到session中
this.MSG="OK";//验证通过
}else {
this.MSG="vCodeErr";//验证码错误
}
}else {
this.MSG="NO";//验证失败
}
return SUCCESS;
}

}


第6步:配置applicationContext与struts2
A、对applicationContext配置

首先,打开applicationContext,然后配置“baseDAO.java”,代码如下:

<bean id="dao" class="MEMBCERP.DAO.baseDAO">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>


截图如下:



1.1.2.6(图1)

接着,配置“baseAction.java”,代码如下:

<bean id="baseAction" class="MEMBCERP.Action.baseAction" abstract="true"></bean>


截图如下:



1.1.2.6(图2)

最后,对loginService loginAction进行配置,代码如下:

<!-- 	登陆管理-->
<bean id="loginService" class="MEMBCERP.Service.LoginService">
<property name="dao">
<ref bean="dao"/>
</property>
</bean>
<bean id="loginAction" class="MEMBCERP.Action.LoginAction" parent="baseAction">
<property name="loginService">
<ref bean="loginService"/>
</property>
</bean>


截图如下:



1.1.2.6(图3)

B、对struts2配置

首先,打开struts.xml,然后对验证用户登陆的方法进行配置,代码如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="struts2" extends="json-default" namespace="/">
<!-- **************登陆注册管理****************** -->

<!-- 登录验证 -->
<action name="login" class="loginAction" method="login">
<result type="json">
<param name="root">MSG</param>
</result>
</action>
</package>
</struts>


截图如下:



1.1.2.6(图4)

第7步:视图层调用
首先创建一个视图,选中需要添加的项目中的“WebRoot”,右键,选择“New”,然后选择“JSP”,如下图:



1.1.2.7(图1)

选择后,新建一个文件名为“Login.jsp”的视图,如下:



1.1.2.7(图2)

“Finish”后,结构如下图



1.1.2.7(图3)

接着,更改页面格式为“UTF-8”,如下图:



1.1.2.7(图4)

导入jquery-easyui-1.3.3样式,到“WebRoot”目录下,

下载地址:http://yunpan.cn/cwqJbcVpCivbe 访问密码 b112

接着,在页面引用jquery-easyui-1.3.3样式,如下图:



1.1.2.7(图5)

噢,对了,验证码。

在包“MEMBCERP.Action”下,添加一个名为“VerificationCode”的类,如下图:



1.1.2.7(图6)

接着,把下面的代码复制到“VerificationCode.java”中,代码如下:

package MEMBCERP.Action;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;

import com.opensymphony.xwork2.ActionContext;

public class VerificationCode extends baseAction{
private ByteArrayInputStream inputStream;
private String MSG;

public ByteArrayInputStream getInputStream()
{
return inputStream;
}
public void setInputStream(ByteArrayInputStream inputStream)
{
this.inputStream = inputStream;
}

public String getMSG() {
return MSG;
}
public void setMSG(String mSG) {
MSG = mSG;
}

public String getVerificationCode() throws Exception
{
int width = 65, height = 20;//定义验证码图片宽高
BufferedImage image = new  BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);//实例化图片对象image
Graphics g = image.getGraphics();//获取该图片对象的画笔
Random random = new Random();//实例化随机对象
g.setColor(getRandColor(200, 255));//设置画笔颜色为随机RGB(200~255,200~255,200~255)
g.fillRect(0, 0, width, height);//填充图片区域(即填充图片背景颜色),g.fillRect(起点坐标X, 起点坐标Y, 填充宽度, 填充高度)

g.setFont(new Font("Times New Roman", Font.PLAIN, 18));//设置画笔字体,new Font(字体名称, 字体样式, 字体大小)
g.setColor(getRandColor(160, 200));//设置画笔颜色为随机RGB(160~200,160~200,160~200)
for(int i = 0; i < 155; i++)//训话155次,随机画出155根线条
{
int x1 = random.nextInt(width);//获取随机X轴坐标x1,范围0~图片宽度
int y1 = random.nextInt(height);//获取随机Y轴坐标y1,范围0~图片高度
int x2 = random.nextInt(12);//获取随机X轴坐标x2,范围0~12
int y2 = random.nextInt(12);//获取随机Y轴坐标y2,范围0~12
g.drawLine(x1, y1, x2, y2);//从坐标点(x1,y1)画一根线到坐标的(x2,y2)
}

String sRand = "";//声明变量sRand,用于存放所获得的随机字符
for(int i = 0; i < 4; i++)//循环4次,获取4个随机字符
{
String rand = getRandomChar();//调用getRandomChar()方法,获取一个随机字符
sRand += rand;//字符串拼接,将所获得的随机字符rand拼接到随机字符串sRand后面
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
//设置画笔随机颜色,范围RGB(20+(0~110),20+(0~110),20+(0~110))
g.drawString(rand, 13*i+6, 16);//画出当前随机字符,绘画原点(13*i+6, 16),g.drawString(需要绘制的字符, 绘画原点x坐标, 绘画原点y坐标);
}
ActionContext.getContext().getSession().put("randomImg", sRand.toLowerCase());//将获得的随机字符串存放到session对象“randomImg”中,用于验证
g.dispose();//释放画笔
ByteArrayOutputStream output = new ByteArrayOutputStream();//实例化输出流对象output
ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);//根据流对象ImageIO创建一个输入输出流对象到output
ImageIO.write(image, "JPEG", imageOut);//将图片对象image以JPEG格式写入到输入输出流对象imageOut中
imageOut.close();//关闭imageOut对象
ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());//根据输出流对象output中的数据,创建一个输入流对象input
this.setInputStream(input);//将输入流对象input放到公共输入流对象inputStream中
return SUCCESS;//处理完毕,返回SUCCESS消息

}

public String validateVerificationCode(){
//从session对象中获取randomImg
String str = ActionContext.getContext().getSession().get("randomImg").toString();
//判断传递过来的vCode参数跟randomImg是否一致
if(this.getRequest().getParameter("vCode").toString().toLowerCase().trim().equals(str)){
this.setMSG("true");//若一致则返回true
}
else{
this.setMSG("false");//否则返回false
}
return SUCCESS;
}

private Color getRandColor(int fc, int bc)
{
Random random = new Random();//实例化随机对象random
if(fc > 255) fc = 255;//限制fc最大为255
if(bc > 255) bc = 255;//限制bc最大为255
int r = fc + random.nextInt(bc - fc);//获取随机数r,范围fc~bc
int g = fc + random.nextInt(bc - fc);//获取随机数g,范围fc~bc
int b = fc + random.nextInt(bc - fc);//获取随机数b,范围fc~bc
return new Color(r, g, b);//根据随机数r、g、b,创建并返回一个颜色对象
}
private static String getRandomChar()
{
int rand = (int)Math.round(Math.random() * 2);//产生一个随机数0~1并乘2,再从0到这个数之间随机获取一个值rand
long itmp = 0;//声明一个长整形临时变量
char ctmp = '\u0000';//生成一个字符变量
switch (rand)//根据所得随机数rand进行分支判断
{
case 1://若为1
itmp = Math.round(Math.random() * 25 + 65);//随机获取一个大写字母的ASCⅡ码
ctmp = (char)itmp;//将所得ASCⅡ码转换成字符
return String.valueOf(ctmp);//将字符转换成字符串并返回
case 2://若为2
itmp = Math.round(Math.random() * 25 + 97);//随机获取一个小写字母的ASCⅡ码
ctmp = (char)itmp;//将所得ASCⅡ码转换成字符
return String.valueOf(ctmp);//将字符转换成字符串并返回
default :
itmp = Math.round(Math.random() * 9);//从0~9获取一个随机数

}
return String.valueOf(itmp);//将随机数转换成字符串并返回
}
}


到这里,再配置一下struts,代码如下:

<!-- 验证码图片 -->
<action name="getVerificationCode" class="verificationCode" method="getVerificationCode">
<result type="stream">
<param name="contentType">image/jpeg</param>
<param name="inputtName">inputStream</param>
</result>
</action>


截图如下:



1.1.2.7(图7)

再接着,配置一下applicationContext,代码如下:

<!-- 	验证码 -->
<bean id="verificationCode" class="MEMBCERP.Action.VerificationCode" parent="baseAction"></bean>


截图如下:



1.1.2.7(图8)

最后,就是验证用户登陆的发放请求了。

jQuery代码:

<!--     方法代码段 -->
<script type="text/javascript">
//注册全局回车事件
$(function(){
document.onkeydown = function(e){
var ev = document.all ? window.event : e;
if(ev.keyCode==13) {
loginOnClick();//调用登陆方法
}
}
});
//登陆方法
function loginOnClick(){
//判断相关信息是否填写完整
if($('#userName').val() == '' || $('#pwd').val() == '' || $('#vCode').val() == ''){

if($('#userName').val() == '')//若用户名为空
{
$('.div1').css('border-color','red');//设置class为div1的元素的边框为红色
}
else{//否则
$('.div1').css('border-color','#ccc');//设置class为div1的元素的边框为灰色
}
if($('#pwd').val() == '')
{
$('.div2').css('border-color','red');
}
else{
$('.div2').css('border-color','#ccc');
}
if($('#vCode').val() == '')
{
$('#vCode').css('border-color','red');
}
else{
$('#vCode').css('border-color','#ccc');
}
alert('对不起!请输入相关信息后再操作');
}
else{
$.getJSON("login?userName="+$('#userName').val()+"&pwd="+$('#pwd').val()+"&vCode="+$('#vCode').val(),function(result){
if(result == 'OK'){
$('#vCode').css('border-color','#1ACF0B');//选中id为“vCodeBorder”的元素,并设置该元素的border样式为0 solid
location.href = 'index.jsp';
}else
{
if (result == 'vCodeErr'){
$('#vCode').css('border-color','red');//选中id为“vCode”的元素,并设置该元素的border-color样式为red
alert('验证码错误!');//提示验证码错误
$('#vCode').val("");
}else if (result == 'NO'){
$('.div1').css('border-color','red');
$('.div2').css('border-color','red');
alert('账号或密码错误!');
$('#userName').val("");
$('#pwd').val("");
$('#vCode').val("");
} else{
alert('登录失败!');//提示登陆失败
}
onVCodeImgClick();//调用验证码方法,进行更新
}
})
}
}
}


至此,会员卡管理系统技术解析(五)登陆与注册之登陆技术解析完毕。

注意:仅供学习,禁止用于商业用途!否则,后果自负。

@最终解析权归本人所有
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: