现在正在学习ajax,前台代码都懂,不懂的是servlet这里怎么返回数据给前台
比如我要返回一个json对象给前台,用什么来返回啊?还有另一个疑惑就是用struts的时候,action不是都要设置一个result的吗,如果我前台访问的是action,最后他又跳到了另一个页面,那前台那里怎么得到数据啊?
麻烦先解释第一个问题,这个最重要,先解决这个才能继续研究action的,谢谢

解决方案 »

  1.   


    response.getWriter.print( json );
      

  2.   

    一个返回的结果是json的例子 1.新建一个类JsonOjectResult实现com.opensymphony.xwork2.Result。 
    Result里就一个方法execute,ActionInvocation的invoke执行到最后会调用Result的execute方法。 JsonResult.java 
    Java代码 
    package com.dukuai.search.view.result;   
      
    import java.io.PrintWriter;   
      
    import javax.servlet.http.HttpServletResponse;   
      
    import net.sf.json.JSONArray;   
    import net.sf.json.JSONObject;   
      
    import org.apache.struts2.ServletActionContext;   
      
    import com.dukuai.search.constant.RestError;   
    import com.opensymphony.xwork2.ActionInvocation;   
    import com.opensymphony.xwork2.Result;   
    import com.opensymphony.xwork2.util.ValueStack;   
    import com.spinn3r.log5j.Logger;   
      
      
    public class JsonResult implements Result {   
        private static final long serialVersionUID = 6881760833309063964L;   
      
        private static final Logger LOG = Logger.getLogger();   
      
        private String exposedValue = null;   
      
        public void execute(ActionInvocation invocation) throws Exception {   
            HttpServletResponse response = ServletActionContext.getResponse();   
            final PrintWriter out = response.getWriter();   
            try {   
                response.setContentType("text/plain; charset=UTF-8");   
                final ValueStack stack = invocation.getStack();   
                Object object = invocation.getInvocationContext().get(RestError.KEY_REST_ERROR);   
                if (object == null)   
                    object = invocation.getInvocationContext().get(exposedValue);   
                if (object == null)   
                    object = stack.findValue(exposedValue);   
                if (object == null) {   
                    out.write(JSONObject.fromObject(RestError.ServerInternalError.getErrorMap()).toString());   
                } else {   
                    if (object instanceof String || object instanceof Number) {   
                        out.print(object);   
                    } else if (object.getClass().isArray()) {   
                        JSONArray jsonArray = JSONArray.fromObject(object);   
                        out.print(jsonArray.toString());   
                    } else {   
                        JSONObject jsonObject = JSONObject.fromObject(object);   
                        out.write(jsonObject.toString());   
                    }   
                }   
            } catch (Exception e) {   
                LOG.error(e.getMessage());   
                out.write(JSONObject.fromObject(RestError.ServerInternalError.getErrorMap()).toString());   
            }   
            out.close();   
        }   
        public String getExposedValue() {   
            return exposedValue;   
        }   
      
        public void setExposedValue(String exposedValue) {   
            this.exposedValue = exposedValue;   
        }   
    }  package com.dukuai.search.view.result;import java.io.PrintWriter;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONArray;
    import net.sf.json.JSONObject;import org.apache.struts2.ServletActionContext;import com.dukuai.search.constant.RestError;
    import com.opensymphony.xwork2.ActionInvocation;
    import com.opensymphony.xwork2.Result;
    import com.opensymphony.xwork2.util.ValueStack;
    import com.spinn3r.log5j.Logger;
    public class JsonResult implements Result {
    private static final long serialVersionUID = 6881760833309063964L; private static final Logger LOG = Logger.getLogger(); private String exposedValue = null; public void execute(ActionInvocation invocation) throws Exception {
    HttpServletResponse response = ServletActionContext.getResponse();
    final PrintWriter out = response.getWriter();
    try {
    response.setContentType("text/plain; charset=UTF-8");
    final ValueStack stack = invocation.getStack();
    Object object = invocation.getInvocationContext().get(RestError.KEY_REST_ERROR);
    if (object == null)
    object = invocation.getInvocationContext().get(exposedValue);
    if (object == null)
    object = stack.findValue(exposedValue);
    if (object == null) {
    out.write(JSONObject.fromObject(RestError.ServerInternalError.getErrorMap()).toString());
    } else {
    if (object instanceof String || object instanceof Number) {
    out.print(object);
    } else if (object.getClass().isArray()) {
    JSONArray jsonArray = JSONArray.fromObject(object);
    out.print(jsonArray.toString());
    } else {
    JSONObject jsonObject = JSONObject.fromObject(object);
    out.write(jsonObject.toString());
    }
    }
    } catch (Exception e) {
    LOG.error(e.getMessage());
    out.write(JSONObject.fromObject(RestError.ServerInternalError.getErrorMap()).toString());
    }
    out.close();
    }
    public String getExposedValue() {
    return exposedValue;
    } public void setExposedValue(String exposedValue) {
    this.exposedValue = exposedValue;
    }
    }HotTypeAction.java 
    Java代码 
    package com.dukuai.search.view.action;   
      
    import com.opensymphony.xwork2.ActionSupport;   
      
      
    public class HotTypeAction extends ActionSupport {   
        private static final long serialVersionUID = -6632949471204152470L;   
      
        private static final String[] HOT_TYPES = {"5630", "N92", "6630", "N75"};   
           //stack.findValue(exposedValue) 会根据配置调用该方法。   
        public String[] getHotTypes() {   
            return HOT_TYPES;   
        }   
    }  package com.dukuai.search.view.action;import com.opensymphony.xwork2.ActionSupport;
    public class HotTypeAction extends ActionSupport {
    private static final long serialVersionUID = -6632949471204152470L; private static final String[] HOT_TYPES = {"5630", "N92", "6630", "N75"};
           //stack.findValue(exposedValue) 会根据配置调用该方法。
    public String[] getHotTypes() {
    return HOT_TYPES;
    }
    }struts.xml 
    Java代码 
    <?xml version="1.0" encoding="UTF-8" ?>   
    <!DOCTYPE struts PUBLIC   
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
        "http://struts.apache.org/dtds/struts-2.0.dtd">   
    <struts>   
        <constant name="struts.objectFactory" value="spring"></constant>   
        <constant name="struts.enable.DynamicMethodInvocation" value="false" />   
        <constant name="struts.i18n.encoding" value="GBK" />   
        <constant name="struts.devMode" value="false" />   
        <include file="struts-default.xml"></include>   
        <package name="api-rest" extends="struts-default" namespace="/api">   
            <result-types>   
                <result-type name="jsonOjectResult" class="com.dukuai.search.view.result.JsonResult"></result-type>   
            </result-types>   
            <!-- 热门型号 -->   
            <action name="hotjob" class="hotJobAction">   
                <result type="JsonResult">   
                    <param name="exposedValue">hotTypes</param>   
                </result>   
            </action>   
        </package>   
    </struts>  
    copy了一个struts2的result代码 你直接看看吧我学了struts1 没有学过2 呵呵。。
      

  3.   


    我刚开始也是用这个
    PrintWriter pw = resp.getWriter();
    pw.println("{name:'Kotomi',name:'Nagisa',name:'Tomoyo'}");
    pw.flush();
    pw.close();
    可是看responseText却是<html><head><title>Apache Tomcat/6.0.29 - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 405 - HTTP method GET is not supported by this URL</h1><HR size="1" noshade="noshade"><p><b>type</b> Status report</p><p><b>message</b> <u>HTTP method GET is not supported by this URL</u></p><p><b>description</b> <u>The specified HTTP method is not allowed for the requested resource (HTTP method GET is not supported by this URL).</u></p><HR size="1" noshade="noshade"><h3>Apache Tomcat/6.0.29</h3></body></html>
      

  4.   


    确实来说应该是返回这个,我GET和POST都用过了
    HTTP Status 405 - HTTP method GET is not supported by this URLtype Status reportmessage HTTP method GET is not supported by this URLdescription The specified HTTP method is not allowed for the requested resource (HTTP method GET is not supported by this URL).
      

  5.   

    pw.flush();
    pw.close();
    这个去了 再调试一下看看!你前台用什么捕获的?
      

  6.   

    发现问题了,重写的doPost和doGet方法里没有把super.doPost和super.doGet去掉,简直恶心死了