首先在web.xml加上统一编码过滤器.為的是防止乱码.
<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>
com.filter.SetCharacterEncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
java代码:
/**
*
*/
package com.filter;
/**
* @author
*
*/
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 {
private String charset = "UTF-8";
public void destroy() {
}
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
arg0.setCharacterEncoding(charset);
arg1.setCharacterEncoding(charset);
arg2.doFilter(arg0, arg1);
}
public void init(FilterConfig arg0) throws ServletException {
}
}
jsp页面:
<input type="text" name="student.stu_username" id="stuid" />
javascript:
$(document).ready(function(){
$("#stuid").change(function(){
$.post("userSearchSys.action", {username: $("#stuid").val()} ,function(data){alert(data);});
});
});
绑定onchange事件.
struts2.xml:
<action name="*Sys" class="com.action.Sys" method="{1}">
<result type="stream"><param name="username">inputStream</param></result>
</action>
action:
public String userSearch(){
StudentDao sDao = new StudentDao();
try {
int i =sDao.searchUsername(username);
HttpServletResponse response = ServletActionContext.getResponse();
PrintWriter out = response.getWriter();
response.setCharacterEncoding("UTF-8");
response.setHeader("Charset","UTF-8");
response.setHeader("Cache-Control", "no-cache");
if (i==1){
out.println("用户名已经存在");
}
else {
out.println("用户名可用");
}}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}