Thursday, May 16, 2019

Set JSON response to servlet



<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>${javax.servlet.version}</version>
</dependency>
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>${gson.version}</version>
</dependency>


=======================================================
public class Employee {
     
    private int id;
     
    private String name;
     
    private String department;
    
    private long salary;
 
    // constructors
    // standard getters and setters.
}

=================================================================
String employeeJsonString = new Gson().toJson(employee);


========= setting for response ==================================
PrintWriter out = response.getWriter();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
out.print(employeeJsonString);
out.flush();


============================================================


If you use Jackson , then code will be as follows

private void writeResponse(HttpServletResponse aResponse, String errorCode, String errorMessage) {
  try {
   aResponse.setHeader("SAP-Exception", errorMessage);
   aResponse.setHeader("SAP-NFA-Exception-Code", errorCode);
   aResponse.setHeader("Content-Type", "application/json");
   ObjectMapper objectMapper = new ObjectMapper();
   NFAErrorResponse errorResponse = new NFAErrorResponse();
   errorResponse.setCode(errorCode);
   errorResponse.setMessage(errorMessage);
   String errorJsonString =objectMapper.writeValueAsString(errorResponse);
   PrintWriter out = aResponse.getWriter();
   out.print(errorJsonString);
   out.flush();
  } catch (IOException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  }
 }


for further info
https://www.baeldung.com/servlet-json-response






javax.servlet.http.HttpServletResponse.setHeader()

@Override
public void forwardToUrl(SectionInfo info, String link, int code)
{
 info.setRendered();
 try
 {
  HttpServletResponse response = info.getResponse();
  if( response == null )
  {
   throw new Error("info not bound to a request/response");
  }
  response.setStatus(code);
  response.setHeader("Location", link);
  response.flushBuffer();
 }
 catch( Exception e )
 {
  throw Throwables.propagate(e);
 }
}
 

============================================
Example 2

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String filename = request.getParameter("file");
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=" + filename);

    ViewerHtmlHandler handler = Utils.createViewerHtmlHandler();
    InputStream original = null;
    try {
        original = handler.getFile(filename).getStream();
    } catch (Exception x) {
        throw new RuntimeException(x);
    }

    Utils.writeToResponse(original, response);
}

====================================================================
Example 3
public void exportProjectBackupFile(HttpServletRequest req, HttpServletResponse resp) throws Exception {
 String path=req.getParameter("path");
 String projectPath=Utils.decodeURL(path);
 if(StringUtils.isEmpty(projectPath)){
  throw new RuleException("Export project not be null.");
 }
 SimpleDateFormat sd=new SimpleDateFormat("yyyyMMddHHmmss");
 String projectName=projectPath.substring(1,projectPath.length());
 String filename=projectName+"-urule-repo-"+sd.format(new Date())+".bak";
 resp.setContentType("application/octet-stream");
 resp.setHeader("Content-Disposition", "attachment; filename=\"" + new String(filename.getBytes("utf-8"),"iso-8859-1") + "\"");
 resp.setHeader("content-type", "application/octet-stream");
 OutputStream outputStream=resp.getOutputStream();
 repositoryService.exportXml(projectPath,outputStream);
 outputStream.flush();
 outputStream.close();
}
=========================================================================

Example 4

private void downloadWorkflowDescription(HttpServletResponse response, String workflowName) throws ServletException {
 
    try {

        String xml = injector.getInstance(WfDefinitionService.class).fetchWfDefinition(workflowName);
        
        PrintWriter writer = response.getWriter();
        response.setContentType("application/force-download");
        response.setContentLength(xml.length());
        response.setHeader("Content-Transfer-Encoding", "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + workflowName + ".oswf.xml\"");
    
        BufferedReader reader = new BufferedReader(new StringReader(xml)); 
        String line;
        while((line = reader.readLine()) != null) {
            writer.print(line);
            writer.print("\n");
        }
        
    } catch (Exception exception) {
        throw new ServletException(exception);
    }
    
}
============================================================================
Example 5
@SuppressWarnings("unchecked")
private void writeJson(HttpServletResponse response, Map<String, Object> sessionParams) throws ServletException {
 try {
  JSONObject json = new JSONObject();
  json.putAll(sessionParams);
  response.setContentType("application/json");
  response.setHeader("Cache-Control", "no-cache");

  if (log.isTraceEnabled()) {
   log.trace("Responding with: " + json.toJSONString());
  }

  response.getWriter().write(json.toJSONString());
 } catch (IOException e) {
  throw new ServletException("Could not create json.", e);
 }
}
 
===========================================================================
Example 6
 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 String idStr = request.getParameter("id");
 if (idStr != null) {
  Long id = Long.valueOf(idStr);
  LocationPicture picture = null;
  if (id >= 0) {
   picture = LocationPictureDAO.getInstance().get(id);
  } else {
   Map<Long, LocationPicture> temp = (Map<Long, LocationPicture>)request.getSession().getAttribute(TEMP_ROOM_PICTURES);
   if (temp != null)
    picture = temp.get(id);
  }
  if (picture != null) {
   response.setContentType(picture.getContentType());
   response.setHeader( "Content-Disposition", "attachment; filename=\"" + picture.getFileName() + "\"" );
   OutputStream out = response.getOutputStream(); 
   out.write(picture.getDataFile());
   out.flush();
  } else {
   new ServletException("Room picture of the given id does not exist.");
  }
 }
 new ServletException("No room picture id provided.");
}
 

===========================================================================
example 7
**
 * Enables CORS (Cross-origin resource sharing) for the servlet;
 * 
 * @param response
 */
private void setCors(HttpServletResponse response) {
 response.setHeader("Access-Control-Allow-Origin", "*");
 response.setHeader("Access-Control-Max-Age", "3600");
 response.setHeader("Access-Control-Allow-Credentials", "true");
 response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Authorization");
}
========================================================================
for more info