public class Java2JsAndBackServlet extends HttpServlet {
//
private static final String CONTENT_TYPE = "text/html";
//
private static Employee[] emps;
public void init() throws ServletException {
emps = new Employee[] {
new Employee(1, "STEFANO", "ROSSI"),
new Employee(2, "GIOVANNI", "VERDI"),
new Employee(3, "IVAN", "BIANCHI")
};
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String editData = request.getParameter("edit");
if (editData != null) {
Employee emp = js2Java(editData);
for (int i = 0; i < emps.length; i++) {
if (emps[i].getId() == emp.getId()) {
emps[i] = emp;
}
}
return;
}
String id = (id = request.getParameter("id")) == null ? "-1" :
"".equals(id) ?
"-1" : id;
Employee tmp = searchById(Integer.parseInt(id));
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
if (tmp != null) {
out.print(buildResponse(tmp));
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request, response);
}
private String buildResponse(Employee e) {
StringBuffer sb = new StringBuffer();
sb.append("\n var e = ").append(java2Js(e))
.append("\n refreshView(e);");
return sb.toString();
}
private Employee searchById(int id) {
if (id == -1) {
return null;
}
for (int i = 0; i < emps.length; i++) {
if (emps[i].getId() == id) {
return emps[i];
}
}
return null;
}
private String java2Js(Employee e) {
StringBuffer sb = new StringBuffer();
sb.append("{ ").append("id:").append(e.getId()).append(',')
.append("name:'").append(e.getName()).append("',")
.append("lastName:'").append(e.getLastName()).append("'};");
return sb.toString();
}
private Employee js2Java(String data) {
Employee emp = new Employee();
String toParse = data.replace('{', ' ').replace('}', ' ').replaceAll("'",
"").
trim();
String[] entries = toParse.split(",");
for (int i = 0; i < entries.length; i++) {
String[] vals = entries[i].split(":");
if (vals[0].equals("id")) {
emp.id = Integer.parseInt(vals[1]);
}
if (vals[0].equals("name")) {
emp.name = vals[1];
}
if (vals[0].equals("lastName")) {
emp.lastName = vals[1];
}
}
return emp;
}
/**
* <p>Title: Classe Impiegato </p>
*/
public class Employee {
//
private int id;
//
private String name;
//
private String lastName;
public Employee() {
}
public Employee(int id, String name, String lastName) {
this.id = id;
this.name = name;
this.lastName = lastName;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public String getLastName() {
return lastName;
}
public String toString() {
return "EMPLOYEE - ID: " + getId() + " NAME: " + getName() + " LAST: " +
getLastName();
}
}
} //END