<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. unity 对象旋转,自转

    1.对象具体的围绕哪个轴旋转,对应的设置值: transform.Rotate(new Vector3(1,0,0));  //绕x轴旋转    //默认是物体围绕世界坐标的XYZ轴旋转,即物体绕着世 ...

  2. java程序中实现打开 某个指定浏览器

    package com.test; import java.lang.reflect.Method; //实现打开浏览器并跳到指定网址的类 public class BareBonesBrowserL ...

  3. 使用AngularJS中的filterFilter函数进行过滤

    AngularJS中有一个filterFilter函数用来对集合过滤,非常方便. 源代码大致如下: function filterFilter(){ return function(aray, exp ...

  4. R12.1.3 & R12.2.X 注册客户化应用

    R12.2 官方出了运行补丁脚本就可以自动创建客户化应用,所以也把此补丁应用在 R12.1.3上验证一下其可行性,做出以下实验. 1.创建客户化应用账号CUX --login user system ...

  5. Fortran中的指针使用

    Fortran中的指针如何使用,功能怎样,下面的的5个例子足可以让你明白一切! 对于单个值,用起来很简单,但是无法体现指针的强大功能, 示例1: program test_pointer_1 impl ...

  6. Autonomous driving - Car detection YOLO

    Andrew Ng deeplearning courese-4:Convolutional Neural Network Convolutional Neural Networks: Step by ...

  7. Cassandra的数据模型的理解

           Cassandra属于NoSQL数据库,NoSQL和传统关系型数据库不同,NOSQL偏好数据冗余,因为NoSQL一般无法做表关联查询. (1) keySpace 基本上可以将Keyspa ...

  8. Morris图表使用小记

    挺好用的,碰到几个问题,有的是瞎试解决了的: 1.我想折线图能够响应单击事件,即点击某个节点后,就能加载进一步的信息,帮助没找到,参照另外一个地方的写法,居然支持事件 Morris.Line({ el ...

  9. 使用SpringBoot配置了 server.servlet.path后无效的解决方案

    一.问题描述 使用SpringBoot配置了 server.servlet.path后无效,访问时无法通过:http://127.0.0.1:8080/app/hello.html 访问. 二.解决方 ...

  10. linux实现共享内存同步的四种方法

    https://blog.csdn.net/sunxiaopengsun/article/details/79869115 本文主要对实现共享内存同步的四种方法进行了介绍. 共享内存是一种最为高效的进 ...