<p id="check">
<label>验证码:</label>
<input class="vid" id="ValidateCode" name="ValidateCode" type="text" value="" onblur="checkValidateCode()"/>
<img id="checkcodeimg" src="<%=path %>/image.jsp" style="margin-left:10px;" width="74px" height="28px" onclick="this.src='<%=path %>/image.jsp?date='+new Date();"/>
<span id="codeSpan"></span>
</p>

image.jsp

 <%@ page contentType="image/jpeg" import="java.awt.*, java.awt.image.*,java.util.*,javax.imageio.*"%>
<%!Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}%>
<%
out.clear();//????resin???????tomacat??????
out = pageContext.pushBody();
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0); int width = 60, height = 20;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics();
Random random = new Random(); g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height); g.setFont(new Font("Times New Roman", Font.PLAIN, 18)); g.setColor(getRandColor(160, 200));
for (int i = 0; i < 155; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
} String sRand = "";
for (int i = 0; i < 4; i++) {
String rand = String.valueOf(random.nextInt(10));
sRand += rand; g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
g.drawString(rand, 13 * i + 6, 16);
}
// ??????SESSION
session.setAttribute("rand", sRand);
g.dispose(); ImageIO.write(image, "JPEG", response.getOutputStream());
%>

  

实现jsp

  var xmlHttpRequest;
//XmlHttpRequest对象
function createXmlHttpRequest(){
if(window.ActiveXObject){ //如果是IE
return new ActiveXObject("Microsoft.XMLHTTP");
}else if(window.XMLHttpRequest){ //非IE浏览器
return new XMLHttpRequest();
}
}
function checkValidateCode(){
code = document.getElementById("ValidateCode").value.trim();
var url = "user_validateCodeCheck.do?validateCode="+code;
xmlHttpRequest = createXmlHttpRequest();
xmlHttpRequest.onreadystatechange = HuiDiaoFun;
xmlHttpRequest.open("post",url,true);
xmlHttpRequest.send(null);
} //回调函数
function HuiDiaoFun(){
if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200){
var resp = xmlHttpRequest.responseText;
if (resp == "error") {
document.getElementById("codeSpan").innerHTML = "验证码错误!";
document.getElementById("codeSpan").style.color = "#FF0000";
}else if(resp == "ok"){
document.getElementById("codeSpan").innerHTML = "";
}
}
}
 public class UserAction extends BaseAction{

     private String validateCode;

     public void validateCodeCheck(){
String code = (String)getHttpSession().getAttribute("rand");
System.out.println(code);
if(StringUtils.isNoneEmpty(validateCode) && validateCode.equals(code)){
ResponseUtil.writeUTF(getHttpResponse(), "ok");
}else{
ResponseUtil.writeUTF(getHttpResponse(), "error");
}
} } import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.PageContext; import org.apache.struts2.ServletActionContext;
import org.springframework.web.context.support.WebApplicationContextUtils; import com.opensymphony.xwork2.ActionSupport; /**
* action基类,提供共用方法
*
*
*/
public class BaseAction extends ActionSupport { public UnitService baseUnitService;
public RoleService baseRoleService;
public ConfigService baseConfigService;
public ChannelService baseChannelService;
public InfoService baseInfoService;
public int pageSize=10;
public int currPage=1;
public int totalCount=0;
public String pageStr;
public String pageFuncId;
public String showMessage;
public String forwardUrl="";
public int forwardSeconds=0;
public String getForwardUrl() {
return forwardUrl;
}
public void setForwardUrl(String forwardUrl) {
this.forwardUrl = forwardUrl;
}
public int getForwardSeconds() {
return forwardSeconds;
}
public void setForwardSeconds(int forwardSeconds) {
this.forwardSeconds = forwardSeconds;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getCurrPage() {
return currPage;
}
public void setCurrPage(int currPage) {
this.currPage = currPage;
}
public HttpSession getHttpSession(){
return ServletActionContext.getRequest().getSession();
}
public HttpServletRequest getHttpRequest(){
return ServletActionContext.getRequest();
}
public HttpServletResponse getHttpResponse(){
return ServletActionContext.getResponse();
}
public PageContext getPageContext(){
return ServletActionContext.getPageContext();
}
public ServletContext getServletContext(){
return ServletActionContext.getServletContext();
}
public Map<String, Object> getApplication(){
return ServletActionContext.getContext().getApplication();
}
public String getBasePath(){
String path = getHttpRequest().getContextPath();
String basePath = getHttpRequest().getScheme()+"://"+getHttpRequest().getServerName()+":"+getHttpRequest().getServerPort()+path+"/";
return basePath;
} /**
* 获取配置
* @return
*/
public Map<String, Object> getConfig(){
if (getApplication().get("config")!=null) {
return (Map<String, Object>)getApplication().get("config");
}else {
//重新生成
return setConfig();
}
}
/**
* 获取配置值
* @return
*/
public String getConfigVal(String name){
Map<String, Object> config=getConfig();
if (config!=null && config.get(name)!=null) {
return config.get(name).toString();
}
return "";
}
/**
* 设置配置
* @return
*/
public Map<String, Object> setConfig(){
baseConfigService = (ConfigService) getBean("configService");
List<Config> configList=baseConfigService.find();
Map<String, Object> config=new HashMap<String, Object>();
if (configList!=null && configList.size()>0) {
for (int i = 0; i < configList.size(); i++) {
config.put(configList.get(i).getCode(), configList.get(i).getConfigvalue());
}
}
getApplication().put("config", config);
return config;
}
public void write(String content,String charset){
getHttpResponse().setCharacterEncoding(charset);
getHttpResponse().setContentType("text/html;charset="+charset);
try {
getHttpResponse().getWriter().print(content);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 判断是否为admin登录
*/
public boolean isAdminLogin(){
return "admin".equals(getLoginName());
}
/**
* 判断是否为站点总管理员
*/
public boolean isSiteAdmin(){
if (getHttpSession().getAttribute("siteAdmin")!=null) {
return (Boolean)getHttpSession().getAttribute("siteAdmin");
}
return false;
}
/**
* 获取当前管理站点
* @return
*/
public Site getManageSite(){
if (getHttpSession().getAttribute("manageSite")!=null) {
//获取当前管理站点
return (Site)getHttpSession().getAttribute("manageSite");
}
return null;
}
/**
* 获取session中的当前登录用户名
* @return
*/
public String getLoginName(){
if (getLoginAdmin()!=null) {
return getLoginAdmin().getLoginname();
}
return "";
}
/**
* 获取session中的当前登录用户
* @return
*/
public Users getLoginAdmin(){
if (getHttpSession().getAttribute("loginAdmin")!=null) {
return (Users)getHttpSession().getAttribute("loginAdmin");
}
return null;
}
/**
* 获取session中的当前登录会员
* @return
*/
public Member getLoginMember(){
if (getHttpSession().getAttribute("loginMember")!=null) {
return (Member)getHttpSession().getAttribute("loginMember");
}
return null;
}
/**
* 获取session中的当前登录会员组
* @return
*/
public Membergroup getLoginMembergroup(){
if (getHttpSession().getAttribute("loginMembergroup")!=null) {
return (Membergroup)getHttpSession().getAttribute("loginMembergroup");
}
return null;
}
/**
* 获取session中的当前会员登录用户名
* @return
*/
public String getLoginMemberName(){
if (getLoginMember()!=null) {
return getLoginMember().getLoginname();
}
return "";
} /**
* 获取登录用户所属单位
* @return
*/
public List<Unit> getLoginUnits(){
//先判断session是否存在
HttpSession session=getHttpSession();
if (session.getAttribute("loginUnits")!=null) {
return (List<Unit>)session.getAttribute("loginUnits");
}else {
//不存在则重新提取
baseUnitService = (UnitService) getBean("unitService");
List<Unit> list = baseUnitService.findByUser(getLoginAdmin().getId());
session.setAttribute("loginUnits", list);
return list;
}
}
/**
* 获取登录用户所属单位组成的sql语句
* 例:'','',''
* @return
*/
public String getLoginUnitIdsSql(){
List<Unit> list=getLoginUnits();
StringBuilder sb=new StringBuilder();
if (list!=null && list.size()>0) {
for (int i = 0; i < list.size(); i++) {
if (i>0) {
sb.append(",");
}
sb.append("'"+list.get(i).getId()+"'");
}
}
return sb.toString();
}
/**
* 获取登录用户所属角色
* @return
*/
public List<Roles> getLoginRoles(){
//先判断session是否存在
HttpSession session=getHttpSession();
if (session.getAttribute("loginRoles")!=null) {
return (List<Roles>)session.getAttribute("loginRoles");
}else {
//不存在则重新提取
baseRoleService = (RoleService) getBean("roleService");
List<Roles> list = baseRoleService.findByUser(getLoginAdmin().getId());
session.setAttribute("loginRoles", list);
return list;
}
}
/**
* 获取登录用户所属角色组成的sql语句
* 例:'','',''
* @return
*/
public String getLoginRoleIdsSql(){
List<Roles> list=getLoginRoles();
StringBuilder sb=new StringBuilder();
if (list!=null && list.size()>0) {
for (int i = 0; i < list.size(); i++) {
if (i>0) {
sb.append(",");
}
sb.append("'"+list.get(i).getId()+"'");
}
}
return sb.toString();
}
/**
* 返回到通用信息提示页面
* @param msg
* @param url
* @param seconds
* @return
*/
public String showMessage(String showMessage,String forwardUrl,int forwardSeconds){
this.showMessage=showMessage;
this.forwardUrl=forwardUrl;
this.forwardSeconds=forwardSeconds;
return "showMessage";
}
/**
* 设置静态化参数
* @param data
* @throws UnsupportedEncodingException
*/
public void setData(Map<String,Object> data,Site site) throws UnsupportedEncodingException{
//传递site参数
data.put("site", site);
data.put("contextPath", getContextPath());
data.put("contextPathNo", getContextPathNo());
data.put("request_remoteAddr", getHttpRequest().getRemoteAddr());
//获取参数并放入data
Enumeration<String> paramNames=getHttpRequest().getParameterNames();
if (paramNames!=null && paramNames.hasMoreElements()) {
String name;
while (paramNames.hasMoreElements()) {
name=paramNames.nextElement();
if (name!=null &&
!name.equals("site") &&
!name.equals("contextPath")&&
!name.equals("currChannelid")&&
!name.equals("currInfoid")) {
if(name.equals("key")){
String key = new String(getHttpRequest().getParameter(name).getBytes(),"UTF-8");
data.put(name, key);
}else{
data.put(name, getHttpRequest().getParameter(name));
}
}
}
}
//如果有currChannelid参数则传递currChannel对象
if (getHttpRequest().getParameter("currChannelid")!=null && getHttpRequest().getParameter("currChannelid").trim().length()>0) {
baseChannelService = (ChannelService) getBean("channelService");
data.put("currChannel",baseChannelService.findById(getHttpRequest().getParameter("currChannelid")));
}
//如果有currInfoid参数则传递currInfo对象
if (getHttpRequest().getParameter("currInfoid")!=null && getHttpRequest().getParameter("currInfoid").trim().length()>0) {
baseInfoService = (InfoService) getBean("infoService");
data.put("currInfo",baseInfoService.findById(getHttpRequest().getParameter("currInfoid")));
}
//获取seesion中存放的变量
Enumeration<String> sessionNames=getHttpSession().getAttributeNames();
if (sessionNames!=null && sessionNames.hasMoreElements()) {
String name;
while (sessionNames.hasMoreElements()) {
name=sessionNames.nextElement();
if (name!=null) {
//session变量名称改为session_变量名,避免重名
data.put("session_"+name, getHttpSession().getAttribute(name));
}
}
}
}
public String getContextPath(){
return getHttpRequest().getContextPath()+"/";
}
public String getContextPathNo(){
return getHttpRequest().getContextPath()+"/";
}
public String getPageStr() {
return pageStr;
}
public void setPageStr(String pageStr) {
this.pageStr = pageStr;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public String getPageFuncId() {
return pageFuncId;
}
public void setPageFuncId(String pageFuncId) {
this.pageFuncId = pageFuncId;
}
public UnitService getBaseUnitService() {
return baseUnitService;
}
public void setBaseUnitService(UnitService baseUnitService) {
this.baseUnitService = baseUnitService;
}
public RoleService getBaseRoleService() {
return baseRoleService;
}
public void setBaseRoleService(RoleService baseRoleService) {
this.baseRoleService = baseRoleService;
}
public ConfigService getBaseConfigService() {
return baseConfigService;
}
public void setBaseConfigService(ConfigService baseConfigService) {
this.baseConfigService = baseConfigService;
}
public String getShowMessage() {
return showMessage;
}
public void setShowMessage(String showMessage) {
this.showMessage = showMessage;
} public ChannelService getBaseChannelService() {
return baseChannelService;
}
public void setBaseChannelService(ChannelService baseChannelService) {
this.baseChannelService = baseChannelService;
}
public InfoService getBaseInfoService() {
return baseInfoService;
}
public void setBaseInfoService(InfoService baseInfoService) {
this.baseInfoService = baseInfoService;
} public Object getBean(String bean) {
return WebApplicationContextUtils.getWebApplicationContext(
ServletActionContext.getRequest().getSession().getServletContext()).getBean(bean);
}
}

js 异步请求的更多相关文章

  1. asp.net mvc放在iis7.5中提示404错误 js异步请求失效解决办法

    asp.net mvc中js发请求一般写成: $.get("/Can/index"本地上是没有问题的但是部署到iis上,提示404,正确的请求的路径是:/网站名/Can/index ...

  2. js异步请求发展史和yield

    万恶的回调 对前端工程师来说,异步回调是再熟悉不过了,浏览器中的各种交互逻辑都是通过事件回调实现的,前端逻辑越来越复杂,导致回调函数越来越多,同时 nodejs 的流行也让 javascript 在后 ...

  3. egg.js异步请求数据

    之前已经简单的使用egg-init初始化项目,并创建控制器controller和服务service 在实际项目中, service主要负责数据的请求,并处理(http请求) controll主要负责获 ...

  4. 原生js 异步请求,responseXML解析

    异步更新原理:用XMLHTTP发送请求得到服务器端应答数据,在不重新载入整个页面的情况下,用js操作Dom最终更新页面1.创建XMLHttp请求协议 function createXMLHttpReq ...

  5. js异步请求

    目前async / await特性并没有被添加到ES2016标准中,但不代表这些特性将来不会被加入到Javascript中.在我写这篇文章时,它已经到达第三版草案,并且正迅速的发展中.这些特性已经被I ...

  6. Java爬虫系列四:使用selenium-java爬取js异步请求的数据

    在之前的系列文章中介绍了如何使用httpclient抓取页面html以及如何用jsoup分析html源文件内容得到我们想要的数据,但是有时候通过这两种方式不能正常抓取到我们想要的数据,比如看如下例子. ...

  7. js 异步请求封装

    1. function ajax(url, onsuccess) { var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ...

  8. js异步请求方式

    一.使用defer 例: <script src="XXXXXX.js" defer></script> 二.使用promise 例: get('./moc ...

  9. 将前端js异步调用的多个服务合并为一个前端服务

    将前端js异步调用的多个服务合并为一个前端服务 1. 减少前端js异步请求的次数改善浏览体验 2. 方便地针对单个接口做异常降级处理

随机推荐

  1. [TYVJ1473]校门外的树3

    思路: 维护两个树状数组,一个记录种树区间左端点,一个记录右端点. 每次询问查询“看不见的树区间”,即右端点小于查询区间左端点和左端点小于查询区间右端点. #include<cstdio> ...

  2. 使用xlrd模块操作Excel

    table = data.sheets()[] table = data.sheet_by_index() print(table) #获取正行或是整列的值 con = table.row_value ...

  3. bootStrap中的ul导航4

    <div class="container"> <br/> <ul class="nav nav-pills nav-justified&q ...

  4. windows下安装SVN ,Git/SVN 常用命令笔记

    Windows下: 1 安装svn,git,python 2 下载libUV源码,https://github.com/joyent/libuv,可以用git,也可以直接下 载源码包,当前是joyen ...

  5. API使用

    至于什么是API我想不用累述了,百科上面有,其实就是别人写好了一大堆功能性的代码,然后你可以拿来用.一般的二次开发都是使用api来开发,包括现在的高级程序设计,很少自己写基本代码了,像.netFram ...

  6. LVS 之搭建

    部署LVS 10.0.0.20 [root@node1 ~]# yum -y install ipvsadm 进入到 /usr/src 目录查看结果,如果有ip_vs_rr.ip_vs,表示正常 [r ...

  7. 【原创】python模拟腾讯网页登录

    近日,研究Tencent网页模拟登录的过程,过程有些忐忑,但最终还是实现了这一功能.先将结果写于此,供大家参考: 其加密过程在c_login_old.js文件中执行,将JS关键代码提取出来如下: fu ...

  8. 15个优秀的开源项目,让你轻松应对Android开发

    一.huabanDemo-android 应用material design版的花瓣网App 项目地址 https://github.com/LiCola/huabanDemo 二.创建视差效果引导页 ...

  9. Miscellaneos:ISV

    ylbtech-Miscellaneos:ISV ISV英文全称是Independent Software Vendors ,意为“独立软件开发商”,特指专门从事软件的开发.生产.销售和服务的企业,如 ...

  10. 最佳实战Docker持续集成图文详解

    最佳实战Docker持续集成图文详解 这是一种真正的容器级的实现,这个带来的好处,不仅仅是效率的提升,更是一种变革:开发人员第一次真正为自己的代码负责——终于可以跳过运维和测试部门,自主维护运行环境( ...