一、Ajax结合struts的应用,如何获取响应数据
1.Ajax请求数据,服务器端必须以流的方式。
否则如果使用跳转的方式,则会重置浏览器端界面,ajax失效。
2.Ajax结合struts应用,struts肯定不能以跳转的方式传输数据。
Ajax结合struts应用,实现局部刷新:
1.AjAX请求数据,在strust中获取输出流写出数据。
同时,struts方法不返回结果标记。
2.Ajax请求数据,struts以json的方式写出数据。
借助struts-json-plugin的插件包。
二、案例
2.1 Ajax请求数据,在struts中获取输出流写出数据
Ajax请求数据,strust以流的方式写出。不美观。
CheckCodeAction.java
public class CheckCodeAction {
private String code;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String checkCode() throws IOException {
System.out.println("校验验证码");
String target = (String) ActionContext.getContext().getSession().get("CODE");
PrintWriter pw = ServletActionContext.getResponse().getWriter();
if(code.equals(target)) {
pw.write("./images/MsgSent.gif");
}else {
pw.write("./images/MsgError.gif");
}
//这种方式不太优雅。struts有更好的方式。
//ps:那种方式也很垃圾
return null;
}
}
EncodeInterceptor .java
public class EncodeInterceptor implements Interceptor{
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void init() {
// TODO Auto-generated method stub
}
@Override
public String intercept(ActionInvocation ai) throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
//设置编码
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
return ai.invoke();
}
}
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="xxxx" extends="struts-default">
<!-- 加入拦截器 -->
<interceptors>
<interceptor name="encode" class="org.jsoft.interceptor.EncodeInterceptor"></interceptor>
<interceptor-stack name="myStack">
<interceptor-ref name="encode"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="myStack"></default-interceptor-ref>
<action name="checkCode" class="org.jsoft.controller.CheckCodeAction" method="checkCode">
</action>
</package>
</struts>
checkcode.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="./checkcode">
<table border="0" style="margin:100px auto;" cellspacing="0" >
<tr>
<td>用户名: </td>
<td><input type="text" name="userName" ></td>
</tr>
<tr>
<td>密码: </td>
<td><input type="text" name="pwd"></td>
</tr>
<tr>
<td>验证码: </td>
<td>
<input type="text" onkeyup="checkCode(this)" />
<img src="image.jsp" width="100px" height="30px" >
<span><img src="" name="img"></span>
</td>
</tr>
<tr>
<td colspan="2"><input type="button" value="提交"></td>
</tr>
</table>
</form>
<script type="text/javascript">
var userName=document.getElementsByName("userName")[0];
var pwd=document.getElementsByName("pwd")[0];
var img=document.getElementsByName("img")[0];
//创建异步对象
function createAJAX(){
var ajax=null;
try{
ajax=new ActiveXObject("microsoft.xmlhttp");
}catch(e){
try{
ajax=new XMLHttpRequest();
}catch (e) {
alert("你的浏览器没有异步对象")
}
}
return ajax;
}
function checkCode(obj){
var str = obj.value.trim();
if(str.length != 4){
return;
}
//创建
var ajax=createAJAX();
//准备
var method="GET";
var url="./checkCode?code="+obj.value;
alert(url)
ajax.open(method,url);
//设置
//ajax.setRequestHeader("content-type","application/x-www-form-urlencoded");
//发送
ajax.send(null);
//监听
ajax.onreadystatechange=function(){
if(ajax.readyState ==4){
if(ajax.status == 200 ){
console.log(ajax)
var imgUrl=ajax.responseText;
console.log(imgUrl)
img.src=imgUrl;
img.style.width="70px";
img.style.height="40px"
}
}
}
}
</script>
</body>
</html>
image.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ page contentType="image/jpeg" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" %>
<%!
public Color getColor(){
Random random = new Random();
int r = random.nextInt(256);//0-255
int g = random.nextInt(256);
int b = random.nextInt(256);
return new Color(r,g,b);
}
public String getNum(){
String str = "";
Random random = new Random();
for(int i=0;i<4;i++){
str += random.nextInt(10);//0-9
}
return str;
}
%>
<%
//清除缓存。防止浏览器缓存验证码
response.setHeader("pragma", "mo-cache");
response.setHeader("cache-control", "no-cache");
response.setDateHeader("expires", 0);
BufferedImage image = new BufferedImage(80,30,BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(new Color(200,200,200));
g.fillRect(0,0,80,30);
for (int i = 0; i < 30; i++) {
Random random = new Random();
int x = random.nextInt(80);
int y = random.nextInt(30);
int xl = random.nextInt(x+10);
int yl = random.nextInt(y+10);
g.setColor(getColor());
g.drawLine(x, y, x + xl, y + yl);
}
g.setFont(new Font("serif", Font.BOLD,16));
g.setColor(Color.BLACK);
String checkNum = getNum();//"2525"
StringBuffer sb = new StringBuffer();
for(int i=0;i<checkNum.length();i++){
sb.append(checkNum.charAt(i)+" ");//"2 5 2 5"
}
g.drawString(sb.toString(),15,20);
session.setAttribute("CODE",checkNum);//2525
ImageIO.write(image,"jpeg",response.getOutputStream());
out.clear();
out = pageContext.pushBody();
%>
测试
输入验证码,后台进行校验
2.2 Ajax请求数据,struts以json的方式写出数据
CheckCodeAction.java
public class CheckCodeAction {
private String code;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
//写出json数据
private String checkCodeMsg;
public String getCheckCodeMsg() {
return checkCodeMsg;
}
public String checkCode() throws IOException {
System.out.println("校验验证码");
String target = (String) ActionContext.getContext().getSession().get("CODE");
PrintWriter pw = ServletActionContext.getResponse().getWriter();
if(code.equals(target)) {
checkCodeMsg="./images/MsgSent.gif";
}else {
checkCodeMsg="./images/MsgError.gif";
}
//必须返回success标记。 JSON拦截器获取到成功标记后,才会将当前action对象的属性解析为json
return "success";
}
}
EncodeInterceptor .java
public class EncodeInterceptor implements Interceptor{
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void init() {
// TODO Auto-generated method stub
}
@Override
public String intercept(ActionInvocation ai) throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
//设置编码
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
return ai.invoke();
}
}
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="xxxx" extends="json-default">
<!-- 加入拦截器 -->
<interceptors>
<interceptor name="encode" class="org.jsoft.interceptor.EncodeInterceptor"></interceptor>
<interceptor-stack name="myStack">
<interceptor-ref name="encode"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="myStack"></default-interceptor-ref>
<!-- 设置请求路径与资源映射 -->
<action name="checkCode" class="org.jsoft.controller.CheckCodeAction" method="checkCode">
<result type="json" />
</action>
</package>
</struts>
checkcode.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="./checkcode">
<table border="0" style="margin:100px auto;" cellspacing="0" >
<tr>
<td>用户名: </td>
<td><input type="text" name="userName" ></td>
</tr>
<tr>
<td>密码: </td>
<td><input type="text" name="pwd"></td>
</tr>
<tr>
<td>验证码: </td>
<td>
<input type="text" onkeyup="checkCode(this)" />
<img src="image.jsp" width="100px" height="30px" >
<span><img src="" name="img"></span>
</td>
</tr>
<tr>
<td colspan="2"><input type="button" value="提交"></td>
</tr>
</table>
</form>
<script type="text/javascript">
var userName=document.getElementsByName("userName")[0];
var pwd=document.getElementsByName("pwd")[0];
var img=document.getElementsByName("img")[0];
//创建异步对象
function createAJAX(){
var ajax=null;
try{
ajax=new ActiveXObject("microsoft.xmlhttp");
}catch(e){
try{
ajax=new XMLHttpRequest();
}catch (e) {
alert("你的浏览器没有异步对象")
}
}
return ajax;
}
function checkCode(obj){
var str = obj.value.trim();
if(str.length != 4){
return;
}
//创建
var ajax=createAJAX();
//准备
var method="GET";
var url="./checkCode?code="+obj.value;
alert(url)
ajax.open(method,url);
//设置
//ajax.setRequestHeader("content-type","application/x-www-form-urlencoded");
//发送
ajax.send(null);
//监听
ajax.onreadystatechange=function(){
if(ajax.readyState ==4){
if(ajax.status == 200 ){
console.log(ajax)
//返回JAVA格式的JSON文本
var jsonText=ajax.responseText;
alert(jsonText);
//将JSON文本转为JSON对象
var jsonObj=eval("("+jsonText+")");
img.src=jsonObj.checkCodeMsg;
img.style.width="70px";
img.style.height="40px"
}
}
}
}
</script>
</body>
</html>
image.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ page contentType="image/jpeg" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" %>
<%!
public Color getColor(){
Random random = new Random();
int r = random.nextInt(256);//0-255
int g = random.nextInt(256);
int b = random.nextInt(256);
return new Color(r,g,b);
}
public String getNum(){
String str = "";
Random random = new Random();
for(int i=0;i<4;i++){
str += random.nextInt(10);//0-9
}
return str;
}
%>
<%
//清除缓存。防止浏览器缓存验证码
response.setHeader("pragma", "mo-cache");
response.setHeader("cache-control", "no-cache");
response.setDateHeader("expires", 0);
BufferedImage image = new BufferedImage(80,30,BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(new Color(200,200,200));
g.fillRect(0,0,80,30);
for (int i = 0; i < 30; i++) {
Random random = new Random();
int x = random.nextInt(80);
int y = random.nextInt(30);
int xl = random.nextInt(x+10);
int yl = random.nextInt(y+10);
g.setColor(getColor());
g.drawLine(x, y, x + xl, y + yl);
}
g.setFont(new Font("serif", Font.BOLD,16));
g.setColor(Color.BLACK);
String checkNum = getNum();//"2525"
StringBuffer sb = new StringBuffer();
for(int i=0;i<checkNum.length();i++){
sb.append(checkNum.charAt(i)+" ");//"2 5 2 5"
}
g.drawString(sb.toString(),15,20);
session.setAttribute("CODE",checkNum);//2525
ImageIO.write(image,"jpeg",response.getOutputStream());
out.clear();
out = pageContext.pushBody();
%>
测试
输入验证码,后台进行校验