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. 方便地针对单个接口做异常降级处理
随机推荐
- 2016年3月10日Android实习日记
待解决问题: *1:内部ScrollView与外部手势事件滑动冲突问题. *2:Linearlayout+View+LinearLayout横向排列,这其中两个LinearLayout内部各有3个竖向 ...
- [原创]PostMan接口测试神器
[原创]PostMan接口测试神器 1 PostMan是什么? Postman是一款功能强大的网页调试与发送网页HTTP请求的Chrome插件. 2 Postman工具下载及安装 官方网站: htt ...
- 利用Delphi编写IE扩展
就是如何使IE扩展组件可以响应事件. 在自己的程序中使用过WebBrowser控件的朋友都知道,WebBrowser控件定义了诸如BeforeNavigate.DownloadComplete ...
- Scala:Next Steps in Scala
Array val greetStrings = new Array[String](3) greetStrings(0) = "Hello" greetStrings(1) = ...
- Struts2漏洞拉响网站安全红色警报以及把Struts2更新为最新版本Struts2.3.15.1步骤
360网站安全检测平台今日发布红色警报称,广泛应用在国内大型网站系统的Struts2框架正在遭到黑客猛烈攻击.利用Struts2“命令执行漏洞”,黑客可轻易获得网站服务器ROOT权限.执行任意命令,从 ...
- .hashCode方法的作用
对于包含容器类型的程序设计语言来说,基本上都会涉及到hashCode.在Java中也一样,hashCode方法的主要作用是为了配合基于散列的集合一起正常运行,这样的散列集合包括HashSet.Hash ...
- 1.2 Stream API
引例: List<String> strList = Arrays.asList("zhaojigang","nana","tianya& ...
- 第十五章 dubbo结果缓存机制
dubbo提供了三种结果缓存机制: lru:基于最近最少使用原则删除多余缓存,保持最热的数据被缓存 threadlocal:当前线程缓存 jcache:可以桥接各种缓存实现 一.使用方式 <du ...
- plsql 操纵表数据的2种方式
1.情景展示 在plsql中,对表的操作(增.删.改.查),其实有2种方式,只是很多人都只会第一种方式罢了. 2.方式介绍 第1种方式:直接将值与sql写到一起 直接按F8运行即可. 第2种方式: ...
- Linux 系统实时监控的瑞士军刀 —— Glances
Linux 系统实时监控的瑞士军刀 —— Glances 对于 RHEL/CentOS/Fedora 发行版 ## RHEL/CentOS 7 64-Bit ## # wget http://dl.f ...