js 异步请求
<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 异步请求的更多相关文章
- asp.net mvc放在iis7.5中提示404错误 js异步请求失效解决办法
asp.net mvc中js发请求一般写成: $.get("/Can/index"本地上是没有问题的但是部署到iis上,提示404,正确的请求的路径是:/网站名/Can/index ...
- js异步请求发展史和yield
万恶的回调 对前端工程师来说,异步回调是再熟悉不过了,浏览器中的各种交互逻辑都是通过事件回调实现的,前端逻辑越来越复杂,导致回调函数越来越多,同时 nodejs 的流行也让 javascript 在后 ...
- egg.js异步请求数据
之前已经简单的使用egg-init初始化项目,并创建控制器controller和服务service 在实际项目中, service主要负责数据的请求,并处理(http请求) controll主要负责获 ...
- 原生js 异步请求,responseXML解析
异步更新原理:用XMLHTTP发送请求得到服务器端应答数据,在不重新载入整个页面的情况下,用js操作Dom最终更新页面1.创建XMLHttp请求协议 function createXMLHttpReq ...
- js异步请求
目前async / await特性并没有被添加到ES2016标准中,但不代表这些特性将来不会被加入到Javascript中.在我写这篇文章时,它已经到达第三版草案,并且正迅速的发展中.这些特性已经被I ...
- Java爬虫系列四:使用selenium-java爬取js异步请求的数据
在之前的系列文章中介绍了如何使用httpclient抓取页面html以及如何用jsoup分析html源文件内容得到我们想要的数据,但是有时候通过这两种方式不能正常抓取到我们想要的数据,比如看如下例子. ...
- js 异步请求封装
1. function ajax(url, onsuccess) { var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ...
- js异步请求方式
一.使用defer 例: <script src="XXXXXX.js" defer></script> 二.使用promise 例: get('./moc ...
- 将前端js异步调用的多个服务合并为一个前端服务
将前端js异步调用的多个服务合并为一个前端服务 1. 减少前端js异步请求的次数改善浏览体验 2. 方便地针对单个接口做异常降级处理
随机推荐
- Postman使用记录
1. 情况: 当 本地需要测试,线上的项目也需要同时测试时,地址了输入还需要打开多个窗口,麻烦 点击圆圈部分 testForm是我新建的 输入请求的action名字 点击齿轮按钮: 地址栏填入方式: ...
- java运行时could not open ........jvm.cfg问题的解决
我相信这个问题肯定让不少人头疼.小编也纠结了将近3个小时的时间,终于弄明白这是怎么回事并且解决 java都知道时运行命令,不能打开...jvm.cfg很明显是jre虚拟机出现了问题(要么时jre的路径 ...
- nginx 方向代理 jenkins
环境 10.0.0.20 Nginx 10.0.0.21 jenkins 10.0.0.20 nginx 进入到nginx目录,去除无用字段输入到conf.d/jenkins.conf 文件中 [ro ...
- linux 删除开头是减号的文件名
若有一个文件的文件名为 : -testfile 删除方法为 : 输入“rm — -testfile”或”rm ./-testfile”命令便可顺利删除名为“-testfile”的文件. 如果是其他特殊 ...
- if判断比较详解
shell判断数组中是否包含某个元素: ary=(1 2 3) a=2 if [[ "${ary[@]}" =~ "$a" ]] ; then echo ...
- POIUtil
package com.util.poi; import java.io.ByteArrayOutputStream; import java.io.IOException; import java. ...
- EasyUI学习总结(四)——parser源码分析
parser模块是easyloader第一个加载的模块,它的主要作用,就是扫描页面上easyui开头的class标签,然后初始化成easyui控件. /** * parser模块主要是解析页面中eas ...
- 机器学习数据集,主数据集不能通过,人脸数据集介绍,从r包中获取数据集,中国河流数据集
机器学习数据集,主数据集不能通过,人脸数据集介绍,从r包中获取数据集,中国河流数据集 选自Microsoft www.tz365.Cn 作者:Lee Scott 机器之心编译 参与:李亚洲.吴攀. ...
- java异常中throw和throws的区别
throws和throwthrows:用来声明一个方法可能产生的所有异常,不做任何处理而是将异常往上传,谁调用我我就抛给谁. 用在方法声明后面,跟的是异常类名 可以跟多个异常类名,用逗号隔开 表 ...
- iOS:针对固定数据源,更好的封装cell
一.介绍 在iOS开发中,tableView非常常用,能将其展示出来,它的数据源必不可少.当然数据源有动态下发的,有固定写死的,这里我只探讨固定写死的情况.对于死数据,我们在项目中经常遇到的场景就是我 ...