本文分两部分:
1. Intellij Idea建立Web应用程式;
2. 开发一个具有增删查改的WEB应用程序并部署到本地服务器。html
原料: Intellij IDE JDK Tomcat Mysql Navicat for MySQL 浏览器 开发相关jar包(c3p0,commons-beanutils,commons-collections,commons-dbutils,commons-logging,jstl,mchange-commons-java,mysql-connector-java)
File -> New Project -> 输入项目名称“Demos” ,选择Project SDK为1.7 -> Next -> Finish。java
鼠标点中项目名称demos -> 右键选择New,选择Module ->
输入Module名称“firstweb” -> 点击Next->
勾选“Web Application” -> 确认已勾选“Create web.xml” -> Finish。mysql
在web/WEB-INF下建立两个文件夹:classes和lib,classes用来存放编译后输出的class文件,lib用于存放第三方jar包。web
配置文件夹路径
File -> Project Structure (快捷键:Ctrl + Shift + Alt + S) -> 选择Module :
选择 Paths -> 选择”Use module compile output path” -> 将Output path和Test output path都选择刚刚建立的classes文件夹。
接着选择Dependencies -> 将Module SDK选择为1.7 -> 点击右边的“+”号 -> 选择1 “Jars or Directories”
-> 选择刚刚建立的lib文件夹 -> 选择“jar directory” -> 接着返回一路OK就好了。sql
打开菜单Run -> 选择Edit Configuration ->
点击“+”号 -> 选择“Tomcat Server” -> 选择“Local”->
在”Name”处输入新的服务名,点击”Application server”后面的”Configure…”,弹出Tomcat Server窗口,选择本地安装的Tomcat目录 -> OK 数据库
在”Run/Debug Configurations”窗口的”Server”选项板中,取消勾选”After launch”,设置”HTTP port”和”JMX port”(默认值便可),点击 Apply -> OK, 至此Tomcat配置完成。apache
在Tomcat中部署并运行项目
Run -> Edit Configurations,进入”Run/Debug Configurations”窗口 -> 选择刚刚创建的Tomcat容器 -> 选择Deployment -> 点击右边的“+”号 -> 选择Artifact,浏览器
选择web项目 -> Application context能够填“/hello”> OK(这个hello能够替换成你想要的名字,这个名字是浏览器访问时的程序根目录,/表明tomcat服务器根目录)。tomcat
到这里,准备工做完成,咱们开始写代码了:服务器
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>主页</title>
</head>
<frameset rows="20%,*">
<frame src="<c:url value='/top.jsp'/>" name="top"/>
<frame src="<c:url value='/welcome.jsp'/>" name="main"/>
</frameset>
</html>
index里面包含了top.jsp,为了操做方便,top.jsp是用来和用户交互的,welcome则负责数据的显示。默认welcome没数据,name=”main”表示主页面是这个框架。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<!-- 他的做用是为本页面全部的表单和超连接指定显示内容的框架-->
<base target="main">
<title>My JSP 'top.jsp' starting page</title>
</head>
<body style="text-align: center;">
<h1>客户关系管理系统</h1>
<a href="<c:url value='/add.jsp'/>">添加客户</a>
<a href="<c:url value='/CustomerServlet?method=findAll'/>">查询客户</a>
<a href="<c:url value='/query.jsp'/>">高级搜索</a>
</body>
</html>
welcome.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
</body>
</html>
咱们看到早top.jsp里面有三个操做,分别是添加用户,查询用户,高级搜索,咱们从添加用户开始实现,由于数据库一开始是没有数据的。c:url是jstl表达式,这里不便多数,点击添加用户跳转到add.jsp
add.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3 align="center">添加客户</h3>
<form action="<c:url value='/CustomerServlet'/>" method="post">
<input type="hidden" name="method" value="add">
<table border="1" align="center" width="40%" style="margin-left: 100px">
<tr>
<td width="100px">客户名称</td>
<td width="40%">
<input type="text" name="name"/>
</td>
<td align="left">
<label id="nameError" class="error"> </label>
</td>
</tr>
<tr>
<td>客户性别</td>
<td>
<input type="radio" name="gender" value="male" id="male"/>
<label for="male">男</label>
<input type="radio" name="gender" value="female" id="female"/>
<label for="female">女</label>
</td>
<td>
<label id="genderError" class="error"> </label>
</td>
</tr>
<tr>
<td>手机</td>
<td>
<input type="text" name="phone" id="phone">
</td>
<td>
<label id="phoneError" class="error"> :</label>
</td>
</tr>
<tr>
<td>邮箱</td>
<td>
<input type="text" name="email" id="email"/>
</td>
<td>
<label id="emailError" class="error"></label>
</td>
</tr>
<tr>
<td>描述</td>
<td>
<textarea rows="5" cols="30" name="description"></textarea>
</td>
<td>
<label id="discriptionError" class="error"> </label>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" name="submit"/>
<input type="reset" name="reset"/>
</td>
</tr>
</table>
</form>
</body>
</html>
页面里面是一个表单,而后我设置了一个表单提交时的隐藏项:method:add,也就是说提交到/CustomerServlet’的时候会把这个字段带上去,后台能够经过获取到这个字段判断要执行什么操做。这样作是为了方便后台代码统一管理,不至于看代码的时候找不到入口。
咱们看到提交到了/CustomerServlet这里面,那咱们就来新建一个Servlet:
src右击->new->servlet ,name填CustomerServlet,package填servlet。这里我写了一个BaseServlet.,让这个servlet集成BaseServlet,BaseServlet帮咱们作好了方法反射。
咱们这里把BaseServlet相关的贴出来。
BaseServlet.java
import servlet.GetRequest;
import java.io.IOException;
import java.lang.reflect.Method;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class BaseServlet extends HttpServlet {
public BaseServlet() {
}
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(((HttpServletRequest)request).getMethod().equalsIgnoreCase("get")) {
if(!(request instanceof GetRequest)) {
request = new GetRequest((HttpServletRequest)request);
}
} else {
((HttpServletRequest)request).setCharacterEncoding("utf-8");
}
response.setContentType("text/html;charset=UTF-8");
String methodName = ((HttpServletRequest)request).getParameter("method");
Method method = null;
try {
method = this.getClass().getMethod(methodName, new Class[]{HttpServletRequest.class, HttpServletResponse.class});
} catch (Exception var10) {
throw new RuntimeException("您要调用的方法:" + methodName + "它不存在!", var10);
}
try {
String e = (String)method.invoke(this, new Object[]{request, response});
if(e != null && !e.trim().isEmpty()) {
int index = e.indexOf(":");
if(index == -1) {
((HttpServletRequest)request).getRequestDispatcher(e).forward((ServletRequest)request, response);
} else {
String start = e.substring(0, index);
String path = e.substring(index + 1);
if(start.equals("f")) {
((HttpServletRequest)request).getRequestDispatcher(path).forward((ServletRequest)request, response);
} else if(start.equals("r")) {
response.sendRedirect(((HttpServletRequest)request).getContextPath() + path);
}
}
}
} catch (Exception var9) {
throw new RuntimeException(var9);
}
}
}
GetRequest .java
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public class GetRequest extends HttpServletRequestWrapper {
private HttpServletRequest request;
public GetRequest(HttpServletRequest request) {
super(request);
this.request = request;
}
public String getParameter(String name) {
String value = this.request.getParameter(name);
if(value == null) {
return null;
} else {
try {
return new String(value.getBytes("ISO-8859-1"), "UTF-8");
} catch (UnsupportedEncodingException var4) {
throw new RuntimeException(var4);
}
}
}
public Map getParameterMap() {
Map map = this.request.getParameterMap();
if(map == null) {
return map;
} else {
Iterator var3 = map.keySet().iterator();
while(var3.hasNext()) {
String key = (String)var3.next();
String[] values = (String[])map.get(key);
for(int i = 0; i < values.length; ++i) {
try {
values[i] = new String(values[i].getBytes("ISO-8859-1"), "UTF-8");
} catch (UnsupportedEncodingException var7) {
throw new RuntimeException(var7);
}
}
}
return map;
}
}
}
接下来咱们实现add方法了:
public class ConstomerServlet extends BaseServlet {
private CustomerServier customerService= new CustomerServier();
public String add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Customer customer = CommonUtils.toBean(request.getParameterMap(), Customer.class);
customer.setId(CommonUtils.uuid());
customerService.add(customer);
request.setAttribute("msg", "恭喜,成功添加客户");
return "/msg.jsp";
}
}
这里咱们须要新建一个公共显示的页面msg.jsp,这个页面的工做就是把msg提取出来并显示。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1 style="color:green;" align="center">${msg}</h1>
</body>
</html>
而后方法实现里面要求咱们建一个Model保存用户提交的数据,这里用了一个库,这个是commons.beanutils,同时咱们新建两个文件:CommonUtils.java,DateConverter.java。
其实像上面这些通用的组件咱们能够打包成一个jar包保存起来。
CommonUtils.java
import commons.DateConverter;
import java.util.Date;
import java.util.Map;
import java.util.UUID;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
public class CommonUtils {
public CommonUtils() {
}
public static String uuid() {
return UUID.randomUUID().toString().replace("-", "").toUpperCase();
}
public static <T> T toBean(Map map, Class<T> clazz) {
try {
Object e = clazz.newInstance();
ConvertUtils.register(new DateConverter(), Date.class);
BeanUtils.populate(e, map);
return e;
} catch (Exception var3) {
throw new RuntimeException(var3);
}
}
}
DateConverter.java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.apache.commons.beanutils.Converter;
public class DateConverter implements Converter {
public DateConverter() {
}
public Object convert(Class type, Object value) {
if(value == null) {
return null;
} else if(!(value instanceof String)) {
return value;
} else {
String val = (String)value;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
return sdf.parse(val);
} catch (ParseException var6) {
throw new RuntimeException(var6);
}
}
}
}
Customer.java
public class Customer
{
private String id;
private String name;
private String gender;
private String phone;
private String email;
private String description;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
为了让逻辑更清晰,咱们新建一个Service类来处理业务逻辑
CustomerServier .java
public class CustomerServier {
CustomerDao customerDao = new CustomerDao();
public void add(Customer customer)
{
customerDao.add(customer);
}
}
数据库专门建一个类来处理,CustomerDao
CustomerDao.java
public class CustomerDao {
private QueryRunner qr = new TxQueryRunner();
public void add(Customer c) {
try {
String sql = "insert into t_customer values(?,?,?,?,?,?)";
Object[] params = {c.getId(), c.getName(), c.getGender(),
c.getPhone(), c.getEmail(), c.getDescription()};
qr.update(sql, params);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
咱们这里须要新建两个工具类:JdbcUtils,TxQueryRunner
TxQueryRunner.java
import jdbc.JdbcUtils;
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
public class TxQueryRunner extends QueryRunner {
public TxQueryRunner() {
}
public int[] batch(String sql, Object[][] params) throws SQLException {
Connection con = JdbcUtils.getConnection();
int[] result = super.batch(con, sql, params);
JdbcUtils.releaseConnection(con);
return result;
}
public <T> T query(String sql, ResultSetHandler<T> rsh, Object... params) throws SQLException {
Connection con = JdbcUtils.getConnection();
Object result = super.query(con, sql, rsh, params);
JdbcUtils.releaseConnection(con);
return result;
}
public <T> T query(String sql, ResultSetHandler<T> rsh) throws SQLException {
Connection con = JdbcUtils.getConnection();
Object result = super.query(con, sql, rsh);
JdbcUtils.releaseConnection(con);
return result;
}
public int update(String sql) throws SQLException {
Connection con = JdbcUtils.getConnection();
int result = super.update(con, sql);
JdbcUtils.releaseConnection(con);
return result;
}
public int update(String sql, Object param) throws SQLException {
Connection con = JdbcUtils.getConnection();
int result = super.update(con, sql, param);
JdbcUtils.releaseConnection(con);
return result;
}
public int update(String sql, Object... params) throws SQLException {
Connection con = JdbcUtils.getConnection();
int result = super.update(con, sql, params);
JdbcUtils.releaseConnection(con);
return result;
}
}
从这点能够看出作Web开发,有一个本身的工具类组件库是多么重要。JdbcUtils用到了数据库链接池c3p0,那么咱们要在src目录下新建一个xml文件来配置一把
JdbcUtils.java
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
public class JdbcUtils {
private static DataSource ds = new ComboPooledDataSource();
private static ThreadLocal<Connection> tl = new ThreadLocal();
public JdbcUtils() {
}
public static DataSource getDataSource() {
return ds;
}
public static Connection getConnection() throws SQLException {
Connection con = (Connection)tl.get();
return con != null?con:ds.getConnection();
}
public static void beginTransaction() throws SQLException {
Connection con = (Connection)tl.get();
if(con != null) {
throw new SQLException("已经开启了事务,不能重复开启!");
} else {
con = ds.getConnection();
con.setAutoCommit(false);
tl.set(con);
}
}
public static void commitTransaction() throws SQLException {
Connection con = (Connection)tl.get();
if(con == null) {
throw new SQLException("没有事务不能提交!");
} else {
con.commit();
con.close();
con = null;
tl.remove();
}
}
public static void rollbackTransaction() throws SQLException {
Connection con = (Connection)tl.get();
if(con == null) {
throw new SQLException("没有事务不能回滚!");
} else {
con.rollback();
con.close();
con = null;
tl.remove();
}
}
public static void releaseConnection(Connection connection) throws SQLException {
Connection con = (Connection)tl.get();
if(connection != con && connection != null && !connection.isClosed()) {
connection.close();
}
}
}
c3p0-config.xml
这个是个人数据库配置,具体配置根据每一个人电脑不一样有所变化。至于里面具体字段表明的含义我就不一一介绍了。
<?xml version="1.0" encoding="utf-8" ?>
<c3p0-config>
<default-config>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/customer</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="user">root</property>
<property name="password">root</property>
<property name="acquireIncrement">3</property>
<property name="initialPoolSize">10</property>
<property name="minPoolSize">2</property>
<property name="maxPoolSize">10</property>
</default-config>
</c3p0-config>
到这里,咱们新建客户的操做就作好了,来运行一下看看效果。运行就是那个播放键。
好了,效果出来了,咱们新建一个也成功了。一看数据库,确实插入进去了。有同窗会说,数据库的代码还没贴出来呢?好吧,那我把数据库设计的表贴出来吧。。。。
t_customer.sql
/* Navicat MySQL Data Transfer Source Server : larsonconn Source Server Version : 50520 Source Host : localhost:3306 Source Database : customer Target Server Type : MYSQL Target Server Version : 50520 File Encoding : 65001 Date: 2017-05-18 14:54:29 */
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `t_customer`
-- ----------------------------
DROP TABLE IF EXISTS `t_customer`;
CREATE TABLE `t_customer` ( `id` varchar(50) NOT NULL, `name` varchar(50) DEFAULT NULL, `gender` varchar(20) DEFAULT NULL, `phone` varchar(50) DEFAULT NULL, `email` varchar(50) DEFAULT NULL, `description` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
咱们看top.jsp是这样写的
那门须要在servlet里面实现这个findAll方法:
public String findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/* *1.获取页面传递的pc * 2.给定pr的值 * 3.使用pc和pr调用service方法,获得pageBean,保存到request域 * 4.转发到list.jsp */
/* * 1.获得pc * 若是pc参数不存在,说明pc=1 * 若是pc参数存在,须要转换成int类型 */
int pc=getPc(request);
int pr=10;//给定pr的值,每页10行纪录
PageBean<Customer> pb= customerService.findAll(pc,pr);
pb.setUrl(getUrl(request));
request.setAttribute("pb",pb);
return "f:/list.jsp";
}
由于使用了分页查询,因此咱们须要再建一个Bean,
PageBean.java
public class PageBean<Object>
{
private int pc;//当前页码page code
//private int tp;//总页数total pages
private int tr;//总纪录数tatal records
private int pr;//每页纪录数page records
private List<Object> beanList;//当前页的纪录
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getPc() {
return pc;
}
public void setPc(int pc) {
this.pc = pc;
}
public int getTp()
{
int tp=tr/pr;
return tr % pr == 0 ? tp : tp + 1 ;
}
public int getTr() {
return tr;
}
public void setTr(int tr) {
this.tr = tr;
}
public int getPr() {
return pr;
}
public void setPr(int pr) {
this.pr = pr;
}
public List<Object> getBeanList() {
return beanList;
}
public void setBeanList(List<Object> beanList) {
this.beanList = beanList;
}
}
而后再service实现findAll方法:
public PageBean<Customer> findAll(int pc, int pr) {
return customerDao.findAll(pc,pr);
}
而后是Dao层实现:先查询有多少条记录,记录多的时候就须要分页。使用limit指令实现。
public PageBean<Customer> findAll(int pc, int pr) {
try {
/* *1.他须要建立pageBean对象pb * 2.设置pb的pc和pr * 3.获得tr,设置给pb * 4.获得beanList设置给pb * 最后返回给pb */
PageBean<Customer> pb = new PageBean<>();
pb.setPc(pc);
pb.setPr(pr);
String sql = "select count(*) from t_customer";
Number number = (Number) qr.query(sql, new ScalarHandler<>());
int tr = number.intValue();
pb.setTr(tr);
sql = "select * from t_customer order by name limit ?,?";
Object[] params = {(pc - 1) * pr, pr};
List<Customer> beanList = qr.query(sql, new BeanListHandler<>(Customer.class), params);
pb.setBeanList(beanList);
return pb;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
如今咱们拿到数据了,须要把这些数据显示出来,咱们新建一个jsp用来显示这些数据:
list.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>客户列表</title>
</head>
<body>
<h3 align="center" >客户列表</h3>
<table border="1" width="70%" align="center">
<tr>
<th>客户姓名</th>
<th>性别</th>
<th>手机</th>
<th>邮箱</th>
<th>描述</th>
<th>操做</th>
</tr>
<c:forEach items="${pb.beanList}" var="cstm">
<tr>
<td>${cstm.name}</td>
<td>${cstm.gender}</td>
<td>${cstm.phone}</td>
<td>${cstm.email}</td>
<td>${cstm.description}</td>
<td>
<a href="<c:url value='/CustomerServlet?method=preEdit&id=${cstm.id}'/> ">编辑</a>
<a href="<c:url value='/CustomerServlet?method=delete&id=${cstm.id}'/> ">删除</a>
</td>
</tr>
</c:forEach>
</table>
<br/>
<center>
第${pb.pc}页/共${pb.tp}页
<a href="${pb.url}&pc=1">首页</a>
<c:if test="${pb.pc>1}">
<a href="${pb.url}&pc=${pb.pc-1}">上一页</a>
</c:if>
<c:choose>
<c:when test="${pb.tp<=10}">
<c:set var="begin" value="1"/>
<c:set var="end" value="${pb.tp}"/>
</c:when>
<c:otherwise>
<c:set var="begin" value="${pb.pc-5}"/>
<c:set var="end" value="${pb.pc+4}"/>
<%--头溢出--%>
<c:if test="${begin<1}">
<c:set var="begin" value="1"/>
<c:set var="end" value="10"/>
</c:if>
<%--尾溢出--%>
<c:if test="${end>pb.tp}">
<c:set var="end" value="${pb.tp}"/>
<c:set var="begin" value="${pb.tp-9}"/>
</c:if>
</c:otherwise>
</c:choose>
<%--循环遍历页码列表--%>
<c:forEach var="i" begin="${begin}" end="${end}">
<c:choose>
<c:when test="${i eq pb.pc}">
[${i}]
</c:when>
<c:otherwise>
<a href="${pb.url}&pc=${i}">[${i}]</a>
</c:otherwise>
</c:choose>
</c:forEach>
<c:if test="${pb.pc<pb.tp}">
<a href="${pb.url}&pc=${pb.pc+1}">下一页</a>
</c:if>
<a href="${pb.url}&pc=${pb.tp}">尾页</a>
</center>
</body>
</html>
好了,list.jsp从传入的对象里面读取到数据并显示出来,到这里一个查询功能就实现了。
那查询作完了,咱们来作一下高级查询,高级查询就是能够指定信息查询,从top页面进入,看到有/query.jsp,那咱们建一个/query.jsp
/query.jsp’
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title></title>
</head>
<body>
<h3 align="center">高级搜索</h3>
<form action="<c:url value="/CustomerServlet"/>" method="get">
<input type="hidden" name="method" value="query">
<table border="0" align="center" width="40%" style="margin-left: 100px">
<tr>
<td width="100px">客户名称</td>
<td width="40%">
<input type="text" name="name">
</td>
</tr>
<tr>
<td>客户性别</td>
<td>
<select name="gender">
<option value="">==请选择性别==</option>
<option value="male">male</option>
<option value="female">female</option>
</select>
</td>
</tr>
<tr>
<td>手机</td>
<td>
<input type="text" name="phone"/>
</td>
</tr>
<tr>
<td>邮箱</td>
<td>
<input type="text" name="email"/>
</td>
</tr>
<tr>
<td> </td>
<td>
<input type="submit" value="搜索"/>
<input type="reset" value="重置"/>
</td>
</tr>
</table>
</form>
</body>
</html>
这下查询表单也写好了,咱们来实现query方法,仍是回到Servlet
public String query(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Customer customer=CommonUtils.toBean(request.getParameterMap(),Customer.class);
// System.out.println(getUrl(request));
customer=encoding(customer);
int pc=getPc(request);
int pr=10;
PageBean<Customer> pb= customerService.query(customer,pc,pr);
pb.setUrl(getUrl(request));
request.setAttribute("pb",pb);
return "/list.jsp";
}
咱们再来实现service里面的query方法:
public PageBean<Customer> query(Customer customer, int pc, int pr) {
return customerDao.query(customer, pc,pr);
}
而后就是Dao里的查询:根QueryAll差很少,只是作了where查询限定
public PageBean<Customer> query(Customer customer, int pc, int pr) {
try {
PageBean<Customer> pb = new PageBean<Customer>();
pb.setPc(pc);
pb.setPr(pr);
StringBuilder cntSql = new StringBuilder("select count(*) from t_customer ");
StringBuilder whereSql = new StringBuilder(" where 1=1 ");
List<Object> params = new ArrayList<Object>();
String name = customer.getName();
if (name != null && !name.trim().isEmpty()) {
whereSql.append("and name like ?");
params.add("%" + name + "%");
}
String gender = customer.getGender();
if (gender != null && !gender.trim().isEmpty()) {
whereSql.append("and gender=?");
params.add(gender);
}
String phone = customer.getPhone();
if (phone != null && !phone.trim().isEmpty()) {
whereSql.append("and phone like ?");
params.add("%" + phone + "%");
}
String email = customer.getEmail();
if (email != null && !email.trim().isEmpty()) {
whereSql.append("and email like ?");
params.add("%" + email + "%");
}
Number num = (Number) qr.query(cntSql.append(whereSql).toString(), new ScalarHandler<>(), params.toArray());
pb.setTr(num.intValue());
StringBuilder sql = new StringBuilder("select * from t_customer ");
StringBuilder lmitSql = new StringBuilder(" limit ?,?");
params.add((pc - 1) * pr);
params.add(pr);
List<Customer> beanList = qr.query(sql.append(whereSql).append(lmitSql).toString(), new BeanListHandler<>(Customer.class), params.toArray());
pb.setBeanList(beanList);
return pb;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
咱们把查询结果放在list.jsp显示,显示页面咱们前面写好了,那咱们来运行一下;
很好,正确显示了。
接下来就是修改删除了。
修改删除入口我放在了列表页面,
c:url value=’/CustomerServlet?method=preEdit&id=${cstm.id}’
public String preEdit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
Customer customer = customerService.find(id);
request.setAttribute("customer", customer);
return "/edit.jsp";
}
咱们先经过查询咱们须要修改的客户id,经过数据库查询到客户信息,而后传到edit页面进行编辑。
CustomerServier.java
...
public Customer find(String id) {
return customerDao.find(id);
}
...
CustomerDao.java
...
public Customer find(String id) {
try {
String sql = "select * from t_customer where id=?";
return qr.query(sql, new BeanHandler<Customer>(Customer.class), id);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
...
,咱们来新建一个edit.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri ="http://java.sun.com/jsp/jstl/core"%> <html> <head> <title>Title</title> </head> <body> <h3 align="center">编辑客户</h3> <form action="<c:url value='/CustomerServlet'/>" method="post" > <input type="hidden" name="method" value="edit"/> <input type="hidden" name="id" value="${customer.id}"/> <table border="0" align="center" width="40%" style="margin-left: 100px"> <tr> <td width="100px">客户名称</td> <td width="40%"> <input type="text" name="name" value="${customer.name}"/> </td> <td align="left"> <label id="nameError" class="error"> </label> </td> </tr> <tr> <td>客户性别</td> <td> <input type="radio" name="gender" value="male" id="male" <c:if test="${customer.gender eq 'male'}"/>checked="checked"/> <label for="male">男</label> <input type="radio" name="gender" value="female" id="female" <c:if test="${customer.gender eq 'female'}"/> checked="checked"/> <label for="female">女</label> </td> <td> <label id="genderError"class="error"> </label> </td> </tr> <tr> <td>手机</td> <td> <input type="text" name="phone" id="phone" value="${customer.phone}"/> </td> <td> <label id="phoneError"class="error"> </label> </td> </tr> <tr> <td>邮箱</td> <td> <input type="text" name="email" id="email" value="${customer.email}"/> </td> <td> <label id="emailError"class="error"> </label> </td> </tr> <tr> <td>描述</td> <td> <textarea rows="5" cols="30" name="description">${customer.description}</textarea> </td> <td> <label id="discriptionError"class="error"> </label> </td> </tr> <tr> <td></td> <td> <input type="submit" name="submit" value="编辑客户"/> <input type="reset" name="reset"/> </td> </tr> </table> </form> </body> </html>
好了,咱们点击提交的时候会把修改后的用户信息存进表单调教给servlet的edit方法,咱们如今来实现edit方法:
...
public String edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Customer customer = CommonUtils.toBean(request.getParameterMap(), Customer.class);
customerService.edit(customer);
request.setAttribute("msg", "恭喜,编辑客户成功");
return "/msg.jsp";
}
...
好了,到这里,修改操做咱们也完成了,哈哈哈哈哈哈哈哈哈。那还剩下一个删除操做。
删除客户调用了servlet的删除方法:
c:url value=’/CustomerServlet?method=delete&id=${cstm.id}’
咱们如今来实现一下delete方法:
...
public String delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
customerService.delete(id);
request.setAttribute("msg", "恭喜,删除客户成功");
return "/msg.jsp";
}
...
,仍是和前面同样:
CustomerServier.java
...
public void delete(String id) {
customerDao.delete(id);
}
...
CustomerDao.java
...
public void delete(String id) {
try {
String sql = "delete from t_customer where id=?";
qr.update(sql, id);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
...
好了,删除咱们也作完了,这下大功告成,一个简单的客户管理系统就完成了。你们须要lib的点击这里: