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());
	}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值