Java tutorial
/* * 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.viseur.control; import com.viseur.model.ConceptItem; import com.viseur.model.DateCUtil; import com.viseur.model.Idea; import com.viseur.model.ItemComment; import com.viseur.model.Project; import com.viseur.model.User; import java.io.IOException; import java.io.PrintWriter; 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 javax.servlet.http.HttpSession; import org.json.JSONObject; /** * * @author JHK */ @WebServlet(name = "AddComment", urlPatterns = { "/AddComment" }) public class AddComment extends HttpServlet { /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int item = Integer.valueOf(request.getParameter("itemtype")); int itemId = Integer.valueOf(request.getParameter("itemid")); String cmntText = request.getParameter("comment"); HttpSession session = request.getSession(); User usr = (User) session.getAttribute("user"); String addedTime = DateCUtil.getSimpleDateTime(); int success = 0; ConceptItem rateItm = null; ItemComment c = new ItemComment(usr.regId, cmntText, addedTime); int cmtId = c.createComment(); if (cmtId > 0) { if (item == 1) { rateItm = new Project(itemId); } else if (item == 2) { rateItm = new Idea(itemId); } if (rateItm != null) { if (rateItm.addComment(cmtId)) { success = 1; } } } JSONObject json = new JSONObject(); json.put("success", success); if (success == 1) { json.put("userName", usr.username); json.put("time", DateCUtil.convertToDateTime(addedTime)); json.put("id", cmtId); } else { json.put("error", "Please try again"); } try (PrintWriter out = response.getWriter()) { out.print(json.toString()); out.flush(); } } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Add Comments"; } }