<span style="font-size:18px;"><strong>Struts.xml</strong>配置文件 <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <include file="struts-default.xml"></include> <package name="ajax" extends="struts-default"> <action name="ajax_*" class="com.test.action.AjaxAction" method="{1}"> <result name="SUCCESS">/ajax.jsp</result> <result type="stream"> <param name="inputName">inputStream</param> </result> </action> </package> </struts></span>
AjaxAction
package com.test.action; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringBufferInputStream; import java.io.StringReader; import java.io.UnsupportedEncodingException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class AjaxAction extends ActionSupport { private InputStream inputStream; public InputStream getInputStream() { return inputStream; } public String execute() throws Exception { return SUCCESS; } public String checkUser() throws Exception { HttpServletRequest request = ServletActionContext.getRequest(); // 获取 ajax 传递的 name 参数值 Object name = request.getParameter("name"); Object password = request.getParameter("password"); System.out.println("name=>" + name); // 返回 StringBufferInputStream 对象,新的 jdk 里面已经不推荐使用,但推荐使用的 StringReader // 并不是 InputStream 接口的实现类,这个比较蛋疼,可以使用下面 test 里面其他的实现类来传递 inputStream = new StringBufferInputStream(transcoding("哈哈,"+name +password)); return SUCCESS; } public String test() throws Exception { // 返回 ByteArrayInputStream 对象至前台,注意跟上面的编码上的区别 inputStream = new ByteArrayInputStream("乱码测试".getBytes("utf-8")); return SUCCESS; } private String transcoding(String str) { try { return new String(str.getBytes("utf-8"), "iso-8859-1"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return str; } }
ajax.jsp
<span style="font-size:18px;"><%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>ajax</title> </head> <body> <form> 用户名:<input type="text" id="nameId"/><br/> 密码:<input type="text" id="passwordId"/><br/> <span id="nameId2"><span></span></span><br/> <span id="msgId"></span><br/> <input type="button" onclick="checkUserName()" value="提交"/> </form> </body> </html> <script type="text/javascript"> var xhr ; // 初始化 xhr 对象 // return value : 1 : IE , 2 , Mozila , 0 : create xhr error ; function createXHR(){ // 1,创建xhr 对象 . if( window.ActiveXObject ){ xhr = new ActiveXObject( "Microsoft.XMLHTTP" ) ; return 1 ; }else if( window.XMLHttpRequest ){ xhr = new XMLHttpRequest(); return 2 ; }else{ return 0 ; } } // ////////// 验证用户名是否存在 //////////////////// // 将用户填写的用户名发送给服务器端验证 function checkUserName(){ var ret = createXHR(); if( ret == 0 ){ alert( "create xhr error" ) ; }else{ // 在xhr中注册用于处理应答的函数(handleCheck) xhr.onreadystatechange = handleCheck ; /* * //使用Get方式向服务器发送请求 . * var url = makeQueryString( "/ajax/reg.jsp" ); * xhr.open( "get" , url ) ; * xhr.send( null ); */ // 通过Post 形式向服务器发送数据 . var url = "http://localhost:8080/ajax/ajax_checkUser.action" ; xhr.open( "post" , url ) ; xhr.setRequestHeader( "Content-Type" , "application/x-www-form-urlencoded" ) ; xhr.send( makeQueryString( null ) ) ; } } // 在指定的URL上添加参数 function makeQueryString( url ){ var name = document.getElementById( "nameId" ).value ; var password = document.getElementById( "passwordId" ).value ; var queryString ; if( url == null ){ return "name=" + name ; }else{ return url + "?name=" + name +"&password=" + password; } } function handleCheck(){ document.getElementById( "nameId2" ).firstChild.innerHTML="用户名不能为空"; // 通信过程结束 . // readyState : 1: 初始化阶段 2 :连接建立阶段 3 : 通信中阶段 4 : 通信结束 if( xhr.readyState == 4 ){ // status==200,表示服务器运行正常,其他值代表错误 if( xhr.status == 200 ){ processResult(); }else if(document.getElementById( "nameId" ).value==""){ document.getElementById( "nameId2" ).firstChild.nodeValue="用户名不能为空"; document.getElementById( "nameId2" ).color="red"; } } } function processResult(){ // 获得应答内容 ,把应答内容显示在网页上 var span = document.getElementById( "msgId" ) ; span.innerHTML = xhr.responseText ; } </script></span>
web.xml
<span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter> <filter-name>struts-cleanup</filter-name> <filter-class> com.test.filter.SetCharacterEncodingFilter </filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>struts-cleanup</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> </web-app></span>
SetCharacterEncodingFilter
<span style="font-size:18px;">package com.test.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class SetCharacterEncodingFilter implements Filter { protected String encoding = null; protected FilterConfig filterConfig = null; protected boolean ignore = true; public void destroy() { this.encoding = null; this.filterConfig = null; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (ignore || (request.getCharacterEncoding() == null)) { String encoding = selectEncoding(request); if (encoding != null) request.setCharacterEncoding(encoding); } chain.doFilter(request, response); } public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; this.encoding = filterConfig.getInitParameter("encoding"); String value = filterConfig.getInitParameter("ignore"); if (value == null) this.ignore = true; else if (value.equalsIgnoreCase("true")) this.ignore = true; else if (value.equalsIgnoreCase("yes")) this.ignore = true; else this.ignore = false; } protected String selectEncoding(ServletRequest request) { return (this.encoding); } } </span>