In my project, for inserting, updating and deleting the data I am requesting to servlet class and then it process and get back the response.
It all happen via jQuery ajax.
Right now it response only success or failure as follows
PrintWriter out = response.getWriter();
out.println("<custom message>");
now i want to make that message more meaningful
By default i will accept 1 parameter called "format", if the format is null then by default that particular servlet class will respond in json format else only 2 options are going to be there json and xml.
then i need to set response.setContentType("application/json"); and etc.
So i will make one servlet class as follows
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
}
}
}
}
and this above class is extended as follows
import 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
}
}
will it possible..??
how can i convert response to either xml or json dynamically…??
Don’t do this in servlet. This is good occasion to create a filter which will do your converting job.