Struts2的Action配置代码
- <package name="Ajax" extends="json-default" namespace="/Ajax">
- <action name="serivceJ" class="com.wanghe.test.TestAction" method="serivceJ" >
- <result type="json"></result>
- </action>
- </package>
Action代码
- public void serivceJ() {
- try {
- HttpServletResponse response = ServletActionContext.getResponse();
- HttpServletRequest request = ServletActionContext.getRequest();
- System.out.println("request...serivceJ");
- response.setCharacterEncoding("UTF-8");
- String type = request.getParameter("type");
- String c = "none";
- if(type.equalsIgnoreCase("girl")){
- c = "女孩你好!";
- }else if(type.equalsIgnoreCase("boy")){
- c = "男孩你好!";
- }
- response.getWriter().write(c);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
HttpClient测试代码
- //创建默认的httpClient实例.
- HttpClient httpclient = new DefaultHttpClient();
- //创建httppost
- HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
- //创建参数队列
- List<NameValuePair> formparams = new ArrayList<NameValuePair>();
- formparams.add(new BasicNameValuePair("type", "girl"));
- UrlEncodedFormEntity uefEntity;
- try {
- uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
- httppost.setEntity(uefEntity);
- System.out.println("executing request " + httppost.getURI());
- HttpResponse response;
- response = httpclient.execute(httppost);
- HttpEntity entity = response.getEntity();
- if (entity != null) { System.out.println("--------------------------------------");
- System.out.println("Response content: " + EntityUtils.toString(entity,"UTF-8"));
- System.out.println("--------------------------------------");
- }
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- }catch(UnsupportedEncodingException e1) {
- e1.printStackTrace();
- }catch (IOException e) {
- e.printStackTrace();
- }finally{
- //关闭连接,释放资源
- httpclient.getConnectionManager().shutdown();
- }
输出:
- executing request http://localhost:8080/myDemo/Ajax/serivceJ.action
- --------------------------------------
- Response content: 女孩你好!
- --------------------------------------