0
在我的项目中,我正在向servlet类请求插入,更新和删除数据,然后处理并获取响应。将servlet类扩展为自定义类以获得更多自定义响应
这一切都通过jQuery ajax发生。
现在它的反应只有成功或失败如下
PrintWriter out = response.getWriter();
out.println("<custom message>");
现在我想使该消息更有意义
默认情况下,我会接受1个参数调用"format"
,如果格式是null
然后默认情况下,特定的servlet类将以json
格式响应,否则只有2个选项将在那里json
和xml
。
然后我需要设置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
}
}
它可能.. ??
我该如何将响应转换为xml
或json
动态...?