UserAction 控制器
package action;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import com.opensymphony.xwork2.ActionSupport;
public class UserAction extends ActionSupport {
private InputStream inputStream;//返回的字符流信息,名字一定叫 inputStream
private String name;//用户名
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String execute(){
String result = "<font color='red'>用户已经存在</font>";
if(!"景临境".equals(name)){//不存在该用户
result = "恭喜你,用户可以注册!";
}
try {
//把最终的结果转为 inputStream 类型
inputStream = new ByteArrayInputStream(result.getBytes("utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return SUCCESS;
}
}
struts.xml 配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="default" namespace="/" extends="struts-default">
<action name="checkUser" class="action.UserAction">
<!-- 定义 stream 类型的 result 结果集 -->
<result type="stream">
<!-- 指定 stream 生成的响应数据的类型 -->
<param name="contentType">text/html</param>
<!-- 指定要返回输出的结果 -->
<param name="inputStream">inputStream</param>
</result>
</action>
</package>
</struts>
index.jsp 页面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>对话框</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#user").blur(function(){
var user = $(this).val();
//post
$.post("checkUser.action","name="+user,function(msg){
$("#info").html(msg);
});
//load 的写法,用 get 方法发送的请求
//$("#info").load("checkUser.action","name="+user);
});
});
</script>
</head>
<body>
用户名:<input type="text" id="user" /><span id="info"></span>
</body>
</html>
效果图: