通过向Java DB(Derby)发送数据来处理使用Servlet的Post请求

时间:2014-12-08 13:07:09

标签: java json servlets derby

我正在开发一个电子成绩簿程序,它将来自Java SE应用程序的http post请求发送到Java EE应用程序。 Java EE应用程序在GlassFish服务器上运行。我的目标是让Java EE应用程序中的servlet通过解析JSON并将这些值发送到Java DB(Derby)数据库报告表来处理post请求。为了使其尽可能简单,我通过邮寄请求一次发送一份学生报告,其中包含以下用JSON编码的数据:student_id,student_name,instructor_name,school_name,course_name,absent_days,tardy_days,total_grade。下面的代码通过解析它来处理JSON。如何更改下面的代码以将数据发送到Java DB(Derby)数据库表?

Java Bean

package com.edw.bean;

public class Student {

private String student_id;
private String student_name;
private String instructor_name;
private String school_name;
private String course_name;
private String absent_days;
private String tardy_days;
private String total_grade;

// setters and getters
}

package com.edw.bean;

public class Status {
    private boolean success;
    private String description;

    //setters and getters
}


Servlet

package com.edw.servlet;

import com.edw.bean.Status;
import com.edw.bean.Student;
import com.google.gson.Gson;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JsonParserServlet extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");        
    Gson gson = new Gson();

    try {
        StringBuilder sb = new StringBuilder();
        String s;
        while ((s = request.getReader().readLine()) != null) {
            sb.append(s);
        }

        Student student = (Student) gson.fromJson(sb.toString(), Student.class);

        Status status = new Status();
        if (student.getName().equalsIgnoreCase("edw")) {
            status.setSuccess(true);
            status.setDescription("success");
        } else {
            status.setSuccess(false);
            status.setDescription("not edw");
        }
        response.getOutputStream().print(gson.toJson(status));
        response.getOutputStream().flush();
    } catch (Exception ex) {
        ex.printStackTrace();
        Status status = new Status();
        status.setSuccess(false);
        status.setDescription(ex.getMessage());
        response.getOutputStream().print(gson.toJson(status));
        response.getOutputStream().flush();
    } 
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}
}

0 个答案:

没有答案