---
title: "servlet或struts的Action处理ajax请求"
author: "g21121"
date: "2011-11-15T13:46:28Z"
tags: []
categories: ["Web前端"]
slug: "servlet-struts-action-ajax"
draft: true
lastmod: "2011-11-19T20:20:55Z"
id: 1260160
url: "https://286.iteye.com/blog/1260160"
---

其实处理ajax的请求非常简单，直接看代码就行了：

```
		//如果用的是struts
		//HttpServletResponse response = ServletActionContext.getResponse();
		// 设置输出为文字流
		response.setContentType("text/plain");
		// 设置字符集
		response.setCharacterEncoding("UTF-8");
		// 获取原始的PrintWriter对象,以便输出响应结果,而不用跳转到某个视图
		PrintWriter out = null;
		//json对象
		Gson gson = new Gson();
		try {
			out = response.getWriter();
		} catch (IOException e) {
			return null;
		}
		Object o=new Object();	
		out.println(gson.toJson(o));
		out.flush();
		out.close();
		return null;


```

 

 

 这里如果想返回json格式字符串就用google的gson包，不用就自己写字符串。