我正在使用Servlet和JSP进行下面的逻辑 但是,如果我传递带有值的顺序,并取消注释Servlet中的行,它会起作用,但如果顺序为null,则不会发生任何事情,并且异常会生成“空”消息,这很简单。 下面的代码如下工作,但是如果我取消注释行,则如果order为null则停止。希望我在这里清楚,如果没有,请告诉我。
<td class="headerindex"><a href="ListCode?order=code_ready_date">Code ready date:</a></td>
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection connection = DbUtil.getConnection();
try {
Statement statement = connection.createStatement();
String query = "";
String order = "";
order = request.getParameter("order");
System.out.println("Order is: "+order);
//if (order.equals("code_ready_date")) {
//query = "SELECT * FROM codes WHERE prod_deploy_state IN ('LIVE')";
//}
//else if (order != null) {
//query = "SELECT * FROM codes WHERE prod_deploy_state IN ('LIVE','Dormant','...')";
//}
query = "SELECT * FROM codes WHERE prod_deploy_state IN ('LIVE','Dormant','...')";
System.out.println("Query is: "+query);
ResultSet rs = statement.executeQuery(query);
List<Code> codes = new ArrayList<Code>();
while (rs.next()) {
Code code = new Code();
code.setEpic_project(rs.getString("epic_project"));
code.setReleases(rs.getString("releases"));
code.setJira_tickets(rs.getString("jira_tickets"));
code.setApplications(rs.getString("applications"));
code.setComponents(rs.getString("components"));
code.setCode_ready_date(rs.getString("code_ready_date"));
code.setRtb_code_deploy(rs.getString("rtb_code_deploy"));
code.setOrt_code_deploy(rs.getString("ort_code_deploy"));
code.setProd_code_deploy(rs.getString("prod_code_deploy"));
code.setProd_deploy_state(rs.getString("prod_deploy_state"));
code.setProd_launch_date(rs.getString("prod_launch_date"));
code.setDependencies(rs.getString("dependencies"));
code.setId(rs.getString("id"));
codes.add(code);
}
request.setAttribute("code", codes);
RequestDispatcher disp = request.getRequestDispatcher("ListCodes.jsp");
disp.forward(request, response);
rs.close();
statement.close();
} catch (Exception e) {
System.out.println("Exception is: " + e.getMessage());
}
}
答案 0 :(得分:1)
当您尝试在空引用上调用equals方法时,获取空指针异常。当引用为null时,没有对象可以调用equals方法。所以你需要先检查null。请尝试以下方法:
if (order == null) {
query = "SELECT * FROM codes WHERE prod_deploy_state IN ('LIVE','Dormant','...')";
}else if (order.equals("code_ready_date")) {
query = "SELECT * FROM codes WHERE prod_deploy_state IN ('LIVE')";
} else {
query = "SELECT * FROM codes WHERE prod_deploy_state IN ('LIVE','Dormant','...')";
}