使用stream类型的Result实现Ajax
1、视图:test.jsp
<%-- Created by IntelliJ IDEA. User: dong Date: 15-4-22 Time: 下午3:26 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title></title> <link rel="stylesheet" href="js/jquery-1.10.2.min.js"> </head> <body> 用户名:<input type="text" id="name" onblur="aa()" value="张三" name="userName" /> <span id="sp"></span><br/> <input type="text" id="other" /> <script> function aa(){ $(document).ready(function() { $.post("checkuserName.action", { userName: document.getElementById("name").value }, function (data, status) { alert("Data:" + data + "\nStatus:" + status); if(status=="success"){ if(data=="yes") document.getElementById("sp").innerHTML="账户名可以被注册"; else document.getElementById("sp").innerHTML="不能注册"; } },"html"); }); } </script> <script src="js/jquery-1.10.2.min.js"></script> </body> </html>
2、test.java
@Component public class Test extends ActionSupport { //取得post中userName对应的value值 private String userName; //封装输出结果的二进制流 private InputStream inputStream; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public InputStream getInputStream() { return inputStream; } public void setInputStream(InputStream inputStream) { this.inputStream = inputStream; } @Override public String execute() throws Exception { inputStream = userName.equals("张三")? new ByteArrayInputStream("yes".getBytes("UTF-8")):new ByteArrayInputStream("no".getBytes("UTF-8")); return Action.SUCCESS; } }
3、struts.xml文件
<constant name="struts.i18n.encoding" value="UTF-8"/> <constant name="struts.devMode" value="true"/> <constant name="struts.enable.DynamicMethodInvocation" value="false"/> <package name="zjd" extends="struts-default"> <action name="checkuserName" class="loginAction"> <result type="stream"> <!--指定stream生成的响应数据的类型--> <param name="contentType">text/html</param> <!--指定由getResult()方法返回输出结果的InputStream--> <param name="inputStream">result</param> </result> </action> </package>
时间: 2024-10-11 20:43:30