[原创]java WEB学习笔记23:MVC案例完整实践(part 4)---模糊查询的设计与实现

时间:2021-08-04 14:19:08

本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明

本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用

内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系。

本人互联网技术爱好者,互联网技术发烧友

微博:伊直都在0221

QQ:951226918

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

1.查询操作:

  1)思路:

    Servlet:在查询方法中,创建CustomerDAO 对象,调用getAll() 方法,获得List<Customer> 集合,利用保证为requset,转发,获取,遍历

       

      //1. 调用 CustomerDAO 的 getAll() 得到 Customer 的集合 List<Customer> customers = customerDAO.getAll();

       //2. 把 Customer 的集合放入 request 中 request.setAttribute("customers", customers);

       //3. 转发页面到 index.jsp(不能使用重定向) request.getRequestDispatcher("/index.jsp").forward(request, response);

     JSP

      获取 request 中的 customers 属性

      遍历显示

  2)代码:

   CustomerServlet2.java

   Servlet中的 private void query(HttpServletRequest request, HttpServletResponse response)   throws ServletException, IOException{} 方法

 package com.jason.mvcapp.servlet;

 import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List; import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.jason.mvcapp.dao.CustomerDAO;
import com.jason.mvcapp.dao.impl.CustomerDAOJdbcImpl;
import com.jsaon.mvcapp.domain.CriteriaCustomer;
import com.jsaon.mvcapp.domain.Customer; /**
* Servlet implementation class CustomerServlet2
*/
@WebServlet("*.do")
public class CustomerServlet2 extends HttpServlet {
private static final long serialVersionUID = 1L; //创建一个CustomerDAO对象,多态
private CustomerDAO customerDAO = new CustomerDAOJdbcImpl(); protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
} protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//1.获取servletPath:/add.do 或者 query.do
String serveltPath = request.getServletPath(); // System.out.println(serveltPath);
//2.去除/ 和 .do 得到对应的方法,如 add query
String methodName = serveltPath.substring(1);
methodName = methodName.substring(0, methodName.length() - 3);
// System.out.println(methodName); try {
//3.利用反射获取methodName对应的方法
Method method = getClass().getDeclaredMethod(methodName,
HttpServletRequest.class, HttpServletResponse.class); //4.利用反射调用方法
method.invoke(this, request, response);
} catch (Exception e) { e.printStackTrace();
}
} private void update(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("update"); } private void editeCustomer(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("edit"); } private void deleteCustomer(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("delete"); } private void query(HttpServletRequest request, HttpServletResponse response)
78 throws ServletException, IOException {
79
80 // //1.调用CustomerDAO 的getAll()方法的到Customer 集合
81 // List<Customer> lists = customerDAO.getAll();
82 //2.把Customer 集合放入request
83 request.setAttribute("list", lists);
84 //3.转发页面到index.jsp
85 request.getRequestDispatcher("/index.jsp").forward(request, response);
86
87 }

private void addCustomer(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("add");
} }

index.jsp:获取list, 通过脚本遍历list集合,输出到表格中

  

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%> <%@ page import="com.jsaon.mvcapp.domain.Customer" %>
<%@ page import="java.util.List" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>mve_index</title>
</head>
<body> <form action="query.do" method="post">
<table>
<tr>
<td>CustomerName:</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>Address:</td>
<td><input type="text" name="address"/></td>
</tr>
<tr>
<td>Phone:</td>
<td><input type="text" name="phone"/></td>
</tr>
<tr>
<td><input type="submit" value="Query"/></td>
<td><a href="">Add New Customer</a></td>
</tr>
</table>
</form>
<br><br> <%
List<Customer> lists = (List<Customer>)request.getAttribute("list");
if(lists != null && lists.size() > 0 ){
%>
<hr>
<br><br> <table border="1" cellpadding="10" cellspacing="0">
<tr>
<th>ID</th>
<th>CustomerName</th>
<th>Address</th>
<th>Phone</th>
<th>Update\Delete</th>
</tr> <%
for(Customer customer : lists){
%>
<tr>
<td><%= customer.getId() %></td>
<td><%= customer.getName() %></td>
<td><%= customer.getAddress() %></td>
<td><%= customer.getPhone() %></td>
<td>
<a href="">Update</a>
<a href="">Delete</a>
</td>
</tr> <%
}
%> </table>
<%
}
%> </body>
</html>

2.模糊查询的设计和 实现

  1)思路:

    后端:

    > 条件:根据传入的 name, address, phone 进行模糊查询.

         例子: name: a、address: b、phone: 3 则 SQL 语句的样子为: SELECT id, name, address, phone FROM customers WHERE name LIKE ‘%a%’ AND address LIKE ‘%b%’ AND phone LIKE ‘%3%

    > 需要在 CustomerDAO接口中定义一个 getForListWithCriteriaCustomer(CriteriaCustomer criteriaCustomer)。      

  其中 CriteriaCustomer 用于封装查询条件:name, address, phone。因为查询条件很多时候和 domain 类并不相同,所以要做成一个单独的类    

 package com.jsaon.mvcapp.domain;

 /**
* @author: jason
* @time:2016年5月27日上午9:31:46
* @description:封装查询信息的类
*/ public class CriteriaCustomer { private String name; private String address; private String phone; public String getName() {
if(name == null){
name = "%%";
}else{
name = "%"+ name +"%";
} return name;
} public void setName(String name) { this.name = name;
} public String getAddress() { if(address == null){
address = "%%";
}else{
address = "%"+ address +"%";
} return address;
} public void setAddress(String address) {
this.address = address;
} public String getPhone() {
if(phone == null){
phone = "%%";
}else{
phone = "%"+ phone +"%";
}
return phone;
} public void setPhone(String phone) {
this.phone = phone;
} public CriteriaCustomer(String name, String address, String phone) {
super();
this.name = name;
this.address = address;
this.phone = phone;
} public CriteriaCustomer() {
super();
} }

    >在CustomerDAOJdbcImpl 中重写CustomerDAO 中的getForListWithCriteriaCustomer(CriteriaCustomer criteriaCustomer)

 @Override
public List<Customer> getForListWithCriteriaCustomer(
CriteriaCustomer criteriaCustomer) {
//sql语句
String sql = "SELECT id,name,address,phone FROM customers WHERE name LIKE ? AND address LIKE ? AND phone LIKE ?";
//调用DAO<T> 中的方法getForList(),并且为占位符设置参数
return getForList(sql, criteriaCustomer.getName(),criteriaCustomer.getAddress(),criteriaCustomer.getPhone());
}

    > 拼 SQL: "SELECT id, name, address, phone FROM customers WHERE " + "name LIKE ? AND address LIKE ? ANDphone LIKE ?";

    

    > 为了正确的填充占位符时,重写了 CriteriaCustomer 的 getter方法  

 //获取Name
public String getName() {
if(name == null){
name = "%%";
}else{
name = "%"+ name +"%";
} return name;
} //获取Address
public String getAddress() { if(address == null){
address = "%%";
}else{
address = "%"+ address +"%";
} return address;
} //获取Phone
public String getPhone() {
if(phone == null){
phone = "%%";
}else{
phone = "%"+ phone +"%";
}
return phone;
}

        

  > 修改 Servlet:获取请求参数;把请求参数封装为 CriteriaCustomer 对象,再调用 getForListWithCriteriaCustomer(CriteriaCustomer cc) 方法

   

 private void query(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置编码格式
request.setCharacterEncoding("UTF-8"); //获取相应的参数
String name = request.getParameter("name");
String address = request.getParameter("address");
String phone = request.getParameter("phone");
//封装请求参数
CriteriaCustomer criteriaCustomer = new CriteriaCustomer(name,address,phone); //1.调用CustomerDAO 的getForListWithCriteriaCustomer(criteriaCustomer)方法的到Customer 集合
List<Customer> lists = customerDAO.getForListWithCriteriaCustomer(criteriaCustomer);
//2.把Customer 集合放入request
request.setAttribute("list", lists);
//3.转发页面到index.jsp
request.getRequestDispatcher("/index.jsp").forward(request, response); }

   前台:同上述的JSP

      获取 request 中的 customers 属性

      遍历显示

  2)代码:

CriteriaCustomer.java
 package com.jsaon.mvcapp.domain;

 /**
* @author: jason
* @time:2016年5月27日上午9:31:46
* @description:封装查询信息的类
*/ public class CriteriaCustomer { private String name; private String address; private String phone; public String getName() {
if(name == null){
name = "%%";
}else{
name = "%"+ name +"%";
} return name;
} public void setName(String name) { this.name = name;
} public String getAddress() { if(address == null){
address = "%%";
}else{
address = "%"+ address +"%";
} return address;
} public void setAddress(String address) {
this.address = address;
} public String getPhone() {
if(phone == null){
phone = "%%";
}else{
phone = "%"+ phone +"%";
}
return phone;
} public void setPhone(String phone) {
this.phone = phone;
} public CriteriaCustomer(String name, String address, String phone) {
super();
this.name = name;
this.address = address;
this.phone = phone;
} public CriteriaCustomer() {
super();
} }

CustomerServlet2.java

 package com.jason.mvcapp.servlet;

 import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List; import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.jason.mvcapp.dao.CustomerDAO;
import com.jason.mvcapp.dao.impl.CustomerDAOJdbcImpl;
import com.jsaon.mvcapp.domain.CriteriaCustomer;
import com.jsaon.mvcapp.domain.Customer; /**
* Servlet implementation class CustomerServlet2
*/
@WebServlet("*.do")
public class CustomerServlet2 extends HttpServlet {
private static final long serialVersionUID = 1L; //创建一个CustomerDAO对象,多态
private CustomerDAO customerDAO = new CustomerDAOJdbcImpl(); protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
} protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//1.获取servletPath:/add.do 或者 query.do
String serveltPath = request.getServletPath(); // System.out.println(serveltPath);
//2.去除/ 和 .do 得到对应的方法,如 add query
String methodName = serveltPath.substring(1);
methodName = methodName.substring(0, methodName.length() - 3);
// System.out.println(methodName); try {
//3.利用反射获取methodName对应的方法
Method method = getClass().getDeclaredMethod(methodName,
HttpServletRequest.class, HttpServletResponse.class); //4.利用反射调用方法
method.invoke(this, request, response);
} catch (Exception e) { e.printStackTrace();
}
} private void update(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("update"); } private void editeCustomer(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("edit"); } private void deleteCustomer(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("delete"); } private void query(HttpServletRequest request, HttpServletResponse response)
78 throws ServletException, IOException {
79 request.setCharacterEncoding("UTF-8");
80 String name = request.getParameter("name");
81 String address = request.getParameter("address");
82 String phone = request.getParameter("phone");
83
84
85
86 CriteriaCustomer criteriaCustomer = new CriteriaCustomer(name,address,phone);
87 List<Customer> lists = customerDAO.getForListWithCriteriaCustomer(criteriaCustomer);
88
89
90 // //1.调用CustomerDAO 的getAll()方法的到Customer 集合
91 // List<Customer> lists = customerDAO.getAll();
92 //2.把Customer 集合放入request
93 request.setAttribute("list", lists);
94 //3.转发页面到index.jsp
95 request.getRequestDispatcher("/index.jsp").forward(request, response);
96
97 } private void addCustomer(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("add");
} }

 

   CustomerDAOJdbcImpl.java

 package com.jason.mvcapp.dao.impl;

 import java.util.List;

 import com.jason.mvcapp.dao.CustomerDAO;
import com.jason.mvcapp.dao.DAO;
import com.jsaon.mvcapp.domain.CriteriaCustomer;
import com.jsaon.mvcapp.domain.Customer; /**
* @author: jason
* @time:2016年5月25日下午3:45:06
* @description:对CustomerDAO 的实现
*/
public class CustomerDAOJdbcImpl extends DAO<Customer> implements CustomerDAO { @Override
public List<Customer> getAll() {
String sql = "SELECT * FROM customers";
return getForList(sql);
} @Override
public void save(Customer customer) {
String sql = "INSERT INTO customers(name, address, phone) VALUES(?,?,? )";
update(sql,customer.getName(),customer.getAddress(),customer.getPhone());
} @Override
public Customer get(Integer id) {
String sql = "SELECT id, name, address, phone FROM customers WHERE id = ?";
return get(sql,id); } @Override
public void delete(Integer id) {
String sql = "DELETE FROM customers WHERE id = ?";
update(sql, id);
} @Override
public long getCountWithName(String name) {
String sql = "SELECT count(id) FROM customers WHERE name = ?";
return getForValue(sql, name);
} @Override
50 public List<Customer> getForListWithCriteriaCustomer(
51 CriteriaCustomer criteriaCustomer) {
52 //sql语句
53 String sql = "SELECT id,name,address,phone FROM customers WHERE name LIKE ? AND address LIKE ? AND phone LIKE ?";
54 //调用DAO<T> 中的方法getForList(),并且为占位符设置参数
55 return getForList(sql, criteriaCustomer.getName(),criteriaCustomer.getAddress(),criteriaCustomer.getPhone());
56 } }
CustomerDAO.java
 package com.jason.mvcapp.dao;

 import java.util.List;

 import com.jsaon.mvcapp.domain.CriteriaCustomer;
import com.jsaon.mvcapp.domain.Customer; /**
* @author: jason
* @time:2016年5月25日下午3:28:00
* @description:
*/ public interface CustomerDAO { //带参数的模糊查询
18 public List<Customer> getForListWithCriteriaCustomer(CriteriaCustomer criteriaCustomer);
//查询所有
public List<Customer> getAll(); //保存操作
public void save(Customer coustomer); //更新前,先查询
public Customer get(Integer id); //删除用户
public void delete(Integer id); //查看与参数相同的名字有多少个记录数
public long getCountWithName(String name); }

index.jsp 同上面的一样

总结:

  1)理解代码的层次

  2)在从前台获取参数的时候,一定要设置  request.setCharacterEncoding("UTF-8"); 。我在跑测试的时候,由于没有设置编码格式,在debug 运行的时候,获取到的 name,address,phone都是乱码。一定注意