struts处理AJAX请求

struts处理AJAX请求

1、使用AJAX向struts发出请求的时候,在struts.xml配置里面,要把<action>的返回值设为空,也就是所调用Action方法是没有返回值的,而是通过ServletActionContext获取HttpServletResponse将要返回的数据返回回去。

strtus.xml里面的部分配置:

 

<action name="province" class="com.hpu.action.RegisterAction" method="getProvince">
	<result></result>
</action>

 

处理请求的RegisterAction的部分实现:

 

public void getProvince() throws IOException {
        // provinces是一个List类型的集合
	provinces = registerService.getProvinces(countryId);
	
	StringBuilder sb = new StringBuilder();
	sb.append("<provinces>");
	if(provinces != null) {
		for(Iterator<Province> pros = provinces.iterator(); pros.hasNext();) {
			Province pro = pros.next();
			sb.append("<province><id>" + pro.getId() + "</id><name>" + pro.getName() + "</name></province>");
		}
	}
	sb.append("</provinces>");
	
	sendContent(sb.toString());
}

 

private void sendContent(String content) throws IOException {
	HttpServletResponse response = ServletActionContext.getResponse();
	response.setContentType("text/xml;charset=gbk");  
	response.setHeader("Cache-Control", "no-store");  //HTTP 1.1  
	response.setHeader("Pragma", "no-cache");  //HTTP 1.0  
	response.setDateHeader("Expires", 0);  //prevents caching at the proxy server  
	response.getWriter().write(content.toString()); 
}

 上面是返回XML,现在给出返回Json格式:

 

 

	/**
	 * 获取所有省份信息并返回给AJAX请求
	 * @throws Exception
	 */
	public void loadProvinces() throws Exception {
		List<Province> provinces = ajaxService.loadProvinces();
		
		JSONArray jsonArray = JSONArray.fromObject(provinces);
		System.out.println(jsonArray.toString());
		sendContent(jsonArray.toString());
	}
	
	/**
	 * 返回Json格式文件
	 * @param content
	 * @throws IOException
	 */
	private void sendContent(String content) throws IOException {
		HttpServletResponse resp = ServletActionContext.getResponse();
		resp.setContentType("application/json;charset=gbk");
		resp.setHeader("Cache-Control", "no-store");  //HTTP 1.1  
		resp.setHeader("Pragma", "no-cache");  //HTTP 1.0  
		resp.setDateHeader("Expires", 0);  //prevents caching at the proxy server  
		resp.getWriter().write(content.toString());
	}

 

 

你可能感兴趣的:(Ajax,action,strusts)