java - 如何将 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,那么它会抛出错误。请任何有任何知识的人帮助我
解决方案
请阅读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 方法有什么区别?对于这个选项
在执行此操作之前,您当然应该仔细检查您正在运行的查询是否在直接查询数据库时实际返回数据。
推荐阅读
- c# - Xamarin Android 应用程序不再被 Firebase 正确验证,因为在另一部手机上使用了手机 #
- react-native - fontFamily FontAwesome 不是系统字体,没有通过 Font.loadAsync 加载
- python - 根据用户输入检查 Python 列表/字典并从另一个列表中的相同索引值显示
- android - 我的应用程序如何在两个模拟器上运行发送/接收 SMS DATA 消息
- android - Android Kotin:要求用户将应用设置为默认短信处理程序不起作用
- android - 在 FragmentContainerView 中使用带有 XML 属性的 SupportMapFragment
- google-analytics - Google Analytics(分析)项目类别似乎没有按承诺使用“/”分隔
- r - 回归系数作为条形图和按组:ggplot
- r - R中的情况
- javascript - 在 React 中调用同步函数以在异步 UseEffect 中编辑 API 调用