Heroku HttpServlet:正在调用doGet()而不是doPost()

时间:2015-12-24 22:35:19

标签: java http servlets heroku

(Servelt托管于Heroku)

在我的Servlet中,我实现了为用户创建POST方法。尽管我已将其实现为POST方法,但每当我使用POST向/ serverAccount URI发出请求时,我的doGet()方法都会被调用。为什么我的doGet()方法被调用而不是我的doPost()方法?

Github代码:https://github.com/jchio001/AravindsBackend/blob/master/src/main/java/Main.java

原始代码:

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.json.JSONException;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.*;

public class Main extends HttpServlet{

    private static String TABLE_CREATION = "CREATE TABLE IF NOT EXISTS profile (user_id SERIAL, name varchar(32), " +
            "about_me varchar(1024), village varchar(32), zip_code int, phone_number varchar(16), email varchar(32));";
    private static String TABLE_CREATION_2 = "CREATE TABLE IF NOT EXISTS Connections (requester_id int, target_id int, status varchar(32));";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Connection connection = null;
        try {
            connection = getConnection();
            Statement stmt = connection.createStatement();
            stmt.executeUpdate(TABLE_CREATION);
            stmt.executeUpdate(TABLE_CREATION_2);
            resp.getWriter().print("I did get X.");
        }
        catch (Exception e) {
            resp.setStatus(500);
            resp.getWriter().print("Table creation error: " + e.getMessage());
        }

        finally {
            try {
                connection.close();
            }
            catch (SQLException e) {
                resp.getWriter().print("Failed to close connection: " + getStackTrace(e));
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException
    {
        Connection connection = null;
        try {
            connection = getConnection();
            Statement stmt = connection.createStatement();
            stmt.executeUpdate(TABLE_CREATION);
            stmt.executeUpdate(TABLE_CREATION_2);
            resp.getWriter().print("I did post.");
        }
        catch (Exception e) {
            resp.setStatus(500);
            resp.getWriter().print("Table creation error: " + e.getMessage());
        }

        StringBuffer jb = new StringBuffer();
        String line;
        try {
            BufferedReader reader = req.getReader();
            while ((line = reader.readLine()) != null)
                jb.append(line);
        }
        catch (IOException e) {
            resp.setStatus(400);
            resp.getWriter().print("Couldn't read in request body: " + getStackTrace(e));
        }

        try {
            JSONObject jsonObject = new JSONObject(jb.toString());
            if (req.getRequestURI().endsWith("/createAccount")) {
                resp.setStatus(200);
                resp.getWriter().print("Creating!");
                String name = jsonObject.getString("name");
                String about_me = jsonObject.getString("about_me");
                String village = jsonObject.getString("village");
                String zip_code = jsonObject.getString("zip_code");
                String phone_number = jsonObject.getString("phone_number");
                String email = jsonObject.getString("email");
                String update_sql = "INSERT INTO profile (name, about_me, village, zip_code, phone_number, email) VALUES (?, ?, ?, ?, ?, ?)";
                try {
                    PreparedStatement stmt = connection.prepareStatement(update_sql);
                    stmt.setString(1, name);
                    stmt.setString(2, about_me);
                    stmt.setString(3, village);
                    stmt.setString(4, zip_code);
                    stmt.setString(5, phone_number);
                    stmt.setString(6, email);
                    stmt.executeUpdate();
                    stmt.close();
                }
                catch (SQLException e) {
                    resp.getWriter().print("SQL ERROR @POST: " + getStackTrace(e));
                }
            }
            else {
                resp.setStatus(404);
            }
        }
        catch (JSONException e1) {
            resp.setStatus(400);
            resp.getWriter().print("Error parsing request JSON: " + getStackTrace(e1));
        }
        catch (IOException e) {
            resp.setStatus(500);
            resp.getWriter().print("Error creating SQL statement: " + getStackTrace(e));
        }

        finally {
            try {
                connection.close();
            }
            catch (SQLException e) {
                resp.getWriter().print("Failed to close connection: " + getStackTrace(e));
            }
        }
    }

    private static Connection getConnection() throws URISyntaxException, SQLException {
      URI dbUri = new URI(System.getenv("DATABASE_URL"));

      String username = dbUri.getUserInfo().split(":")[0];
      String password = dbUri.getUserInfo().split(":")[1];
      String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + dbUri.getPath();

      return DriverManager.getConnection(dbUrl, username, password);
    }

    public static void main(String[] args) throws Exception {
      Server server = new Server(Integer.valueOf(System.getenv("PORT")));
      ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
      context.setContextPath("/");
      server.setHandler(context);
      context.addServlet(new ServletHolder(new Main()), "/*");
      server.start();
      server.join();
    }

    public static String getStackTrace(Throwable aThrowable) {
      final Writer result = new StringWriter();
      final PrintWriter printWriter = new PrintWriter(result);
      aThrowable.printStackTrace(printWriter);
      return result.toString();
    }

}

编辑:发出HTTP请求时POSTMAN的样子截图(包括发出相同请求所需的所有信息): http://i.imgur.com/286Boz4.png 可以看出,我的输出是"我确实得到X",这意味着正在执行doGet()。

1 个答案:

答案 0 :(得分:1)

发送POST请求

要发送包含与之关联的数据的POST请求,请按以下步骤操作:

  • 确保选中“普通”选项卡,这是默认设置。

  • 提供请求网址。请务必将实际值放在URL中,因为此处不会定义curl语句中使用的环境变量。

  • 选择POST作为选定的HTTP方法。

  • 单击Headers按钮,并提供Header - Value对Content-Type - application / json。

  • 点击网址参数按钮。对于参数配置,首先选择raw,然后从下拉列表中选择JSON。

  • 将配置JSON粘贴到提供的区域。

  • 单击“发送”。 (如果您最近提交了请求,则可能不会要求您再次进行身份验证。)您将看到一个弹出窗口,用于输入您的凭据。这样做,然后单击“确定”。

此处的更多信息: Use Postman for HTTP Requests