我正在尝试创建一个servlet,我可以在其中添加,删除和搜索客户,现在我陷入了搜索方法,我不知道为什么我的方法不起作用但是我已经创建的代码到目前为止。我正在使用DAO模式,使用以下方法按名称和姓氏过滤客户:
public List<Customers> filterCustomer(String name)
{
List<Customers> customers = new ArrayList<Customers>();
try{
st = getConnection().createStatement();
rs = st.executeQuery("SELECT * from customer where first_name like '%" + name + "%'"
+ "and surname like '%" + name+ "%'");
while(rs.next())
{
Customers customer = new Customers();
customer.setId(rs.getInt(1));
customer.setFirst_name(rs.getString(2));
customer.setSurname(rs.getString(3));
customer.setCode(rs.getString(4));
customers.add(customer);
}
首先在servlet中创建客户列表以打印出来,但如果searchString参数不为null,那么我想创建与searchString匹配的这些客户的新列表。继承了我创建的servlet部分:
out.print("<form method=\"get\" action =\"" + request.getContextPath() +"/Search\" >"
+ "<input id='searchStringBox' name='searchString'/>"
+ "<input type='submit' value='Filtreeri'>");
CustomerDao dao = new CustomerDao();
List<Customers> customers;
customers = dao.getAllCustomers();
String name = request.getParameter("searchString");
if(name != null)
customers = dao.filterCustomer(name);
out.println("<table id='listTable' class='listTable>'" +
"<thead><tr><th scope='col'>Nimi</th><th scope='col'>Perekonnanimi</th>"
+"<th scope='col'>Kood</th><th scope='col'></th></tr></thead>");
for(Customers customer : customers)
{
String value3 = String.valueOf(customer.getId());
request.setAttribute("value3",value3);
customer.getId();
out.println(
"<tbody><tr> "
+ "<td>"+ customer.getFirst_name()+" "+"</td>"
+ "<td>"+ customer.getSurname()+" "+"</td>"
+ "<td>"+ customer.getCode()+" " +"</td>"
+ " "+"<td><a href='"+request.getContextPath()+"/Search?id="+value3+"'>Delete</a></td></tr>"
);
答案 0 :(得分:2)
您正在搜索名称和姓氏之间具有公共字符串的客户。例如,如果您搜索&#34; Moses&#34;,您只会找到以下人员:
Moses Moses
Moses Mosesson
Moses O'Moses
...等。它会不找到&#34; Moses Malone&#34;或者&#34;珍妮摩西&#34;。
原因是您的条件是AND而不是OR。因此,它检查名称和姓氏是否类似于&#39;%Moses%&#39;在一起。
将查询更改为:
"SELECT * from customer where first_name like '%" + name + "%'"
+ "OR surname like '%" + name+ "%'"
确定此方法有效后,请阅读SQL Injection and how to prevent it。切勿使用来自外部世界的参数(使用您的servlet的人或黑客),而不检查它们是否有可能进行SQL注入。