Skip to content

Instantly share code, notes, and snippets.

@TheB1ackSheep
Created December 23, 2014 15:16
Show Gist options
  • Save TheB1ackSheep/daa5045215cc822cca17 to your computer and use it in GitHub Desktop.
Save TheB1ackSheep/daa5045215cc822cca17 to your computer and use it in GitHub Desktop.
package controller.document;
import model.Document;
import model.ResponseMessage;
import javax.naming.NamingException;
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.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;
/**
* Created by FALOOK on 12/23/2014.
*/
@WebServlet(name = "doc-list",urlPatterns = "/doc/list")
public class list extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
ResponseMessage rs = new ResponseMessage();
PrintWriter out = response.getWriter();
try {
if(request.getParameter("id") != null){
Document doc = Document.getById(Integer.parseInt(request.getParameter("id")));
rs.setMsg(doc);
}else {
List<Document> docs = Document.getDocuments();
rs.setMsg(docs);
}
rs.setResult(ResponseMessage.MessageType.SUCCESS);
} catch (SQLException e) {
rs.setResult(ResponseMessage.MessageType.ERROR);
rs.setMsg(e.getMessage());
} catch (NamingException e) {
rs.setResult(ResponseMessage.MessageType.ERROR);
rs.setMsg(e.getMessage());
}
out.print(rs.toJSON());
}
}
package model;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* Created by FALOOK on 12/21/2014.
*/
public class ResponseMessage {
public enum MessageType{
SUCCESS,ERROR,INVALID,FAILED
}
private MessageType result;
private Object msg;
public MessageType getResult() {
return result;
}
public void setResult(MessageType result) {
this.result = result;
}
public Object getMsg() {
return msg;
}
public void setMsg(Object msg) {
this.msg = msg;
}
@Override
public String toString() {
Gson gson = new GsonBuilder().serializeNulls().create();
return gson.toJson(this);
}
public String toJSON(){
return this.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment