没有使用if块时,这个servlet工作正常,但现在我需要使用if块添加更多选项。 请任何人告诉我为什么?
public class SearchServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html");
FileReader fr = null;
BufferedReader br = null;
try {
ArrayList<Contact> contactList = new ArrayList<>();
String query = request.getParameter("q");
String path = getServletContext().getRealPath("pb.txt");
File file = new File(path);
fr = new FileReader(file);
br = new BufferedReader(fr);
String byPhone = request.getParameter("byPhone");
String byAddress = request.getParameter("byAddress");
String byEmail = request.getParameter("byEmail");
out.println(byPhone);
String data = null;
if (byPhone.equals("on")) {
out.print("By Phone:"+byPhone);
while ((data = br.readLine()) != null) {
String[] token = data.split(":");
if (token[1].toLowerCase().startsWith(query.toLowerCase())) {
Contact c = new Contact(token[0], token[1], token[2], token[3]);
contactList.add(c);
}
}
}
out.print("Else");
while ((data = br.readLine()) != null) {
String[] token = data.split(":");
if (token[0].toLowerCase().startsWith(query.toLowerCase())) {
Contact c = new Contact(token[0], token[1], token[2], token[3]);
contactList.add(c);
}
}
out.print("<h1>Results</h1>");
out.print("<table>");
out.print("<tr>");
out.print("<td>Name</td>");
out.print("<td>Phone No</td>");
out.print("<td>Email</td>");
out.print("<td>Address</td>");
out.print("</tr>");
for (Contact c : contactList) {
out.print("<tr>");
out.print("<td>" + c.getName() + "</td>");
out.print("<td>" + c.getPhoneNo() + "</td>");
out.print("<td>" + c.getEmail() + "</td>");
out.print("<td>" + c.getAddress() + "</td>");
out.print("</tr>");
}
out.print("</table>");
out.print("<a href=\"search.html\">Back</a>");
} finally {
if (fr != null) {
fr.close();
}
if (br != null) {
br.close();
}
out.close();
}
}
}
你可以在String data = null;
下面看到if块谢谢!
答案 0 :(得分:1)
一种显而易见的失败方式似乎是在请求中未提供参数byPhone
时,留下变量byPhone = null
,在if语句中导致NullPointerException
。
解决这个问题的两种方法:
// Explicit null check
if (byPhone != null && byPhone.equals("on")) {
// Reverse equals check
if ("on".equals(byPhone)) {