2012-05-10 24 views
0

在我的项目中,我正在向servlet类请求插入,更新和删除数据,然后处理并获取响应。将servlet类扩展为自定义类以获得更多自定义响应

这一切都通过jQuery ajax发生。

现在它的反应只有成功或失败如下

PrintWriter out = response.getWriter(); 
out.println("<custom message>"); 

现在我想使该消息更有意义

默认情况下,我会接受1个参数调用"format",如果格式是null然后默认情况下,特定的servlet类将以json格式响应,否则只有2个选项将在那里jsonxml

然后我需要设置response.setContentType("application/json");

因此,我会做一个servlet类如下

import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 


public class myservlet extends HttpServlet { 

    /** 
    * 
    */ 
    private static final long serialVersionUID = 1L; 

    public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,java.io.IOException 
    { 
     String format = req.getParameter("format"); 

     if(format == null) 
     { 
      format = "json"; 
     } 
     else 
     { 
      if(format.equals("json")) 
      { 
       resp.setContentType("application/json"); 
      } 
      else if(format.equals("xml")) 
      { 
       resp.setContentType("application/rss+xml"); 
      } 
      else 
      { 
       //error 
      } 
     } 
    } 

    public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,java.io.IOException 
    { 
     String format = req.getParameter("format"); 

     if(format == null) 
     { 
      format = "json"; 
     } 
     else 
     { 
      if(format.equals("json")) 
      { 
       resp.setContentType("application/json"); 
      } 
      else if(format.equals("xml")) 
      { 
       resp.setContentType("application/rss+xml"); 
      } 
      else 
      { 
       //error 
      } 
     } 
    } 

} 

,这上面的类如下

进口java.io.延长PrintWriter的;

import javax.servlet.ServletException; 

public class abc extends myservlet 
{ 
    private static final long serialVersionUID = 1L; 

    public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,java.io.IOException 
    { 
     PrintWriter out  = resp.getWriter(); 
      out.println("{/"id/": /"file/"}"); 
     //response must be converted to either json or to xml 
    } 
} 

它可能.. ??

我该如何将响应转换为xmljson动态...?

回答

2

不要在servlet中这样做。这是一个很好的机会来创建一个过滤器,这将做你的转换工作。

  1. 过滤器使用ServletResponseWrapper并把它传递给servlet
  2. 的Servlet节省了响应
  3. 筛选检查参数和委托给相应的转换器(JSON,XML) - 后处理。