本博客为原创:综合 尚硅谷(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都是乱码。一定注意

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

  1. [原创]java WEB学习笔记75:Struts2 学习之路-- 总结 和 目录

    本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...

  2. [原创]java WEB学习笔记95:Hibernate 目录

    本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...

  3. [原创]java WEB学习笔记66:Struts2 学习之路--Struts的CRUD操作( 查看 / 删除/ 添加) 使用 paramsPrepareParamsStack 重构代码 ,PrepareInterceptor拦截器,paramsPrepareParamsStack 拦截器栈

    本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...

  4. [原创]java WEB学习笔记11:HttpServlet(HttpServletRequest HttpServletRsponse) 以及关于 Servlet 小结

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

  5. [原创]java WEB学习笔记21:MVC案例完整实践(part 2)---DAO层设计

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

  6. [原创]java WEB学习笔记20:MVC案例完整实践(part 1)---MVC架构分析

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

  7. [原创]java WEB学习笔记26:MVC案例完整实践(part 7)---修改的设计和实现

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

  8. [原创]java WEB学习笔记25:MVC案例完整实践(part 6)---新增操作的设计与实现

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

  9. [原创]java WEB学习笔记24:MVC案例完整实践(part 5)---删除操作的设计与实现

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

随机推荐

  1. Database returned an invalid value in QuerySet.datetimes(). Are time zone definitions for your datab

    Database returned an invalid value in QuerySet.datetimes(). Are time zone definitions for your datab ...

  2. HTTP协议图解

    1.HTTP简介 http是用于客户端与服务端之间的通信 实际情况中客户端与服务端角色有可能互换,但从一条通信线路来说服务器端和客户端角色是确定的,http协议知道那个是服务端那个是客户端呢. htt ...

  3. Android下Slidingmenu和actionbarsherlock的使用

    1 http://blog.csdn.net/wangjinyu501/article/details/9331749  博客很多,推荐此教程,slidingmenu的demo可以演示 2 http: ...

  4. 安卓SAX解析XML文件

    XML文件经常使用的解析方式有DOM解析,SAX解析. 一.Sax SAX(simpleAPIforXML)是一种XML解析的替代方法. 相比于DOM.SAX是一种速度更快,更有效的方法. 它逐行扫描 ...

  5. python easy install时,使用aliyun阿里云镜像提示主机名不匹配的问题

    因网络问题,因此设置 easy_install 使用阿里云的源, ## 更新 easy_install 源 tee ~/.pydistutils.cfg <<-'EOF' [easy_in ...

  6. jquery的find()

    jQuery 遍历 - find() 方法 jQuery 遍历参考手册 实例 搜索所有段落中的后代 span 元素,并将其颜色设置为红色: $("p").find("sp ...

  7. Problem A. Dynamic Grid

    Problem We have a grid with R rows and C columns in which every entry is either 0 or 1. We are going ...

  8. ionic新手教程第七课-简要说明几种界面之间的參数传递及优缺点

    截至2016年4月13日19点32分,我公布的ionic新手教程,已经公布6课了, 总訪问量将近6000,平均每节课能有1000的訪问量.当中訪客最多的是第三课有2700的訪客. watermark/ ...

  9. RabbitMQ集群安装配置+HAproxy+Keepalived高可用

    RabbitMQ集群安装配置+HAproxy+Keepalived高可用 转自:https://www.linuxidc.com/Linux/2016-10/136492.htm rabbitmq 集 ...

  10. Unity Editor Inspector编辑模板

    效果图: using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEdito ...