在我的项目中,为了插入、更新和删除我向 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
动态...??