com.dbx.feedlab.getFeedJSONServlet.java Source code

Java tutorial

Introduction

Here is the source code for com.dbx.feedlab.getFeedJSONServlet.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dbx.feedlab;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Writer;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.NamingException;

/**
 *
 * @author vkamentsev
 */
@WebServlet(name = "getFeedJSONServlet", urlPatterns = { "/feed" })
public class getFeedJSONServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String feedId = req.getParameter("id");
        //System.out.println("Feed ID=" + feedId);
        DataService ds;
        try {
            ds = DataService.getInstance();
            Feed feed = ds.getFeed(Integer.parseInt(feedId));
            //Gson gson = new Gson();
            ObjectMapper mapper = new ObjectMapper();

            String json = mapper.writeValueAsString(feed);

            Writer writer = resp.getWriter();
            writer.write(json);

        } catch (NamingException ex) {
            Logger.getLogger(getFeedJSONServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(getFeedJSONServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}