@Controller
public class ItemCatController {
@Autowired
private ItemCatService itemCatService;

/*@RequestMapping(value="/itemcat/list",
produces=MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8")
@ResponseBody
public String getItemCatList(String callback) {
CatResult catResult = itemCatService.getItemCatList();
//把pojo转换成字符串
String json = JsonUtils.objectToJson(catResult);
//拼装返回值
String result = callback + "(" + json + ");";
return result;
}*/
//springMVC 4.0以上版本可用
@RequestMapping("/itemcat/list")
@ResponseBody
public Object getItemCatList(String callback) {
CatResult catResult = itemCatService.getItemCatList();
MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(catResult);
mappingJacksonValue.setJsonpFunction(callback);
return mappingJacksonValue;
}
}



在Servlet中出现一个输出中文乱码的问题,已经解。 
@Override
public void doPost(HttpServletRequest reqeust, HttpServletResponse response)
throws ServletException, IOException {

//PrintWriter out = response.getWriter();在还没有给response指定编码格式时就获取了他的输出流,所以一直乱码

response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter(); //在设置完编码以后在获取输出流就好了。
jsonService = new JsonService();
String jsonString = JsonTools.createJsonString("persons", jsonService.getPersonList());
out.println(jsonString);
out.flush();
out.close();
}


 同上



@Controller
public class ItemController {

@Autowired
private ItemService itemService;

@RequestMapping("/item/{itemId}")
//@ResponseBody
public void getItemById(@PathVariable Long itemId,HttpServletResponse response) throws IOException {
TbItem tbItem;
try {
tbItem = itemService.getItemById(itemId);
//如果输出数据中文乱码
//response.setCharacterEncoding("UTF-8");
//response.setContentType("text/html;charset=UTF-8");
response.getWriter().print(tbItem);
} catch (Exception e) {

e.printStackTrace();
System.out.println("fdjksdjfsdjkfksjdkfjsjdk");

}


}
}


 



@RequestMapping(value="/httpclient/post", method=RequestMethod.POST, 
produces=MediaType.TEXT_PLAIN_VALUE+";charset=utf-8")
@ResponseBody
public String testPost(String username, String password) {
String result = "username:" + username + "\tpassword:" + password;
System.out.println(result);
return "username:" + username + ",password:" + password;
}



@Test
public void doGetWithParam() throws Exception{
//创建一个httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建一个uri对象
URIBuilder uriBuilder = new URIBuilder("http://www.sogou.com/web");
uriBuilder.addParameter("query", "花千骨");
HttpGet get = new HttpGet(uriBuilder.build());
//执行请求
CloseableHttpResponse response = httpClient.execute(get);
//取响应的结果
int statusCode = response.getStatusLine().getStatusCode();
System.out.println(statusCode);
HttpEntity entity = response.getEntity();
String string = EntityUtils.toString(entity, "utf-8");
System.out.println(string);
//关闭httpclient
response.close();
httpClient.close();
}