您的位置:首页 > Web前端 > JavaScript

js 异步请求

2016-06-02 10:26 453 查看
<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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: