首页 > 解决方案 > 如何将 java 类的参数化方法调用到 servlet doget 方法中

问题描述

我有一个 java 类,其中我有一个方法返回我一个 json 我想将该方法调用到我的 servlet doGet 方法中,以便以后可以进行 AJAX 调用

但是在调用 java 类方法(Outlet.Outlet)时,它要求传递一个参数我不知道要传递什么,请查看我的代码

这是我的java类

public class Outlet {
static Connection con = null;
static Statement statement = null;
ResultSet resultSet = null;

public static String Outlet(String idDB) throws ClassNotFoundException, SQLException {
    List<String> list = new ArrayList<String>();
    con = DBConnection.createConnection();
    statement = con.createStatement();

    String sql="select CUSTOMERDESCRIPTOR as OUTLETNAME from ecustomer where CUSTOMERIDENTIFIER in(select CUSTOMERIDENTIFIER from mt_distributrol where mt_distributr_vcdistributrcode = '"+idDB+"')";

  System.out.println("iddb  :"+idDB);
    try {

        ResultSet resultSet = statement.executeQuery(sql);
        while (resultSet.next()) {
            list.add(resultSet.getString("OUTLETNAME"));

        }

    } catch (SQLException e) {
        e.printStackTrace();
    }
    String json = new Gson().toJson(list);
    System.out.println("Json Outlet :"+json);
    return json;
}

}

在上面的 java 类中,我返回一个 Json,我想将该方法调用到我的 servlet doGost

我的 doGet 是

    try {
        String json = Outlet.Outlet();  //what should i pass here as a parameter
        response.setContentType("application/json");
        response.getWriter().write(json);
        System.out.println("dheeraj"+json);
    }
    catch (Exception e) {

        e.printStackTrace();
    }

}

如果我通过 idDB,那么它会抛出错误。请任何有任何知识的人帮助我

标签: javasqlservletsjdbcmethods

解决方案


请阅读OWASP - SQL 注入并了解 PreparedStatements

首先,方法不应该以大写字母开头,所以你可以将它命名为Outlet.findById而不是Outlet.Outlet(方法不应该与类相同,读起来真的很混乱),你可以从请求中获取参数

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String id = request.getParameter("id");
    String s = Outlet.findById(id);

调用 API 时,添加?id=value

或者您可以从 获取路径的最后一部分request,假设您的 API 设置如下/path/ids/value- 请参阅HttpServletRequest 中的 getRequestURI 和 getPathInfo 方法有什么区别?对于这个选项

在执行此操作之前,您当然应该仔细检查您正在运行的查询是否在直接查询数据库时实际返回数据。


推荐阅读