JavaWeb(八)——JSP(三)实际应用

数据的展示

准备一个index.jsp页面,提供新增数据,修改数据,删除数据的功能
准备数据库表存储页面信息
首先浏览器发送/index请求获取所有数据库相应数据再返回index.jsp展示所有数据
<body>
	<button  id="add">新增</button>
	<table border="1">
		  <thead>
			  <tr>
			    <th>#</th>
			    <th>姓名</th>
			    <th>年龄</th>
			    <th>性别</th>
			    <th>设置</th>
			  </tr>
		  </thead>
		  <tbody>
		  </tbody>
	</table>
</body>

首页

当前访问资源地址为/index时,跳转index.jsp展示所有数据
首页在数据库设计一个person表,
字段为id,varchar,主键,非自增
字段为name,varchar
字段为age,Integer
字段为sex,Integer

创建servlet处理/index请求
@WebServlet("/index")//返回数据库数据展示到index.jsp页面
public class PersonUI extends HttpServlet
protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//servlet层调用service层方法获取数据库数据
		PersonUIService service = new PersonUIService();
		List<Person> personList = null;
		try {
			personList = service.findAllPerson();
		} catch (SQLException e) {
			e.printStackTrace();
		}			
		// 将数据库的数据放到request域
		request.setAttribute("personList", personList);
		request.getRequestDispatcher("/login.jsp").forward(request, response);

	}
Person类为对应数据表的实体类
public class Person 
	private String id;
	private String name;
	private Integer sex;
	private Integer age;
service中调用dao层方法
public class PersonUIService {
	private PersonUIDao dao = new PersonUIDao();
	public List<Person> findAllPerson() throws SQLException {
		return dao.findAllperson();
	}
dao层操作数据库
private QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
public List<Person> findAllperson() throws SQLException {
		String sql = "select * from person";
		List<Person> person = runner.query(sql, new BeanListHandler<Person>(Person.class));
		return person;
	}
将数据返回到servlet并存入域对象
		personList = service.findAllPerson();
		// 将数据库的数据放到request域
		request.setAttribute("personList", personList);
		request.getRequestDispatcher("/login.jsp").forward(request, response);
在index.jsp页面解析数据,将域对象中的数据展示到表格对象的tbody标签中
对于servlet返回的数据可以jstl标签库的foreach标签来处理多个对象的集合数据
首先需要引入jstl的核心库
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
在<tbody>标签中解析返回的数据
<tbody>
	  	<c:forEach items="${personList}" var="per" varStatus="vs">  		
	  		<tr >	  			
	  			<td>${vs.count}</td><!-- 序号:当前第几次循环 -->
	  			<td>${per.name}</td><!-- 姓名 -->
	  			<td>${per.age}</td><!-- 年龄 -->
	  			<td>
	  				${per.sex==1?"男":"女" }<!-- 性别 -->
	  			</td>
	  			<td><!-- 编辑框的修改与删除按钮的添加 -->
	  				<p>
				      <button id="updata" width=50px  onclick="updata(${per.id})">
				      	<a href="${pageContext.request.contextPath}/updataUI?id=${per.id}"> 
				      	编辑</a>
				      </button>
				      <button id="del" width=50px>
				      	<a href="javascript:void(0);" onclick="delPerson('${per.id}')"> 	
				      	删除</a>
				      </button>
	    			</p>
	  			</td>
	  		</tr>
	  	</c:forEach>
	  </tbody>

list

页面展示数据如上
需要的jar包:
c3p0-0.9.1.2.jar ——c3p0数据源需要响应的jar包与xml文件
commons-beanutils-1.8.3.jar——实体类映射数据库字段需要的包
commons-dbutils-1.4.jar——数据库操作相关的包
commons-logging-1.1.1.jar——日志相关的包
jstl.jar——使用JSTL需要的jar包
mysql-connector-java-5.0.4-bin.jar——连接数据需要的驱动包
standard.jar——使用JSTL和EL表达式,要引入这个包

单条数据的添加

1.给新增按钮绑定单击事件
2.点击新增按钮跳转新增页面
3.获取新增页面填写的数据提交后台
4.提交按钮点击后跳转/index,查询所有数据后跳转index.jsp

绑定单击事件
index.jsp

<button  id="add">新增</button>
	......
</body>
<script src="jquery-1.8.3.js"></script>
<script>
//绑定单击事件添加数据
 $("#add").click(function(){
	 window.location.href = "${pageContext.request.contextPath}/addUI";
 }); 
/*   ${pageContext.request.contextPath}是当前项目名称路径*/
创建servlet处理/addUI的请求,只负责跳转页面和某些参数的携带
@WebServlet("/addUI")
public class AddUI extends HttpServlet
protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 跳转到列表页面
		request.getRequestDispatcher("/addUI.jsp").forward(request, response);
	}

addUI.jsp
在这里插入图片描述

<form id="myModal" action="${pageContext.request.contextPath}/addPerson">
	  <div>
	    <p>
	      <label for="modal-name">姓名</label>
	      <input type="text" id="modal-name" name="name" class="noneerror">
	      <span id="nameerror"></span>
	    </p>
	    <p>
	      <label for="modal-habit">年龄</label>
	      <input type="text" id="modal-age" name="age" class="noneerror">
	      <span id="ageerror"></span>
	    </p>
	    <p>
	      <label for="modal-sex" >性别</label>
	      <select name="sex" id="sel">
	      	<option value="" selected="selected">--请选择--</option>
	      	<option value="2"></option>
	      	<option value="1"></option>
	      </select>
	    </p>
	    <p>
	      <button id="modal-submit">提交</button>
	      <input type="reset" value="重置"/><br/>
	    </p>
	  </div>
</form>
可以得为文本框提供一些报错信息
<script src="jquery-1.8.3.js"></script>
<script>
	    //给姓名的文本框添加焦点失去事件  	
	 	 $("#modal-name").blur(function(){
	 		var name = $.trim($(this).val());//去除文本框内容的前后空格  
	 		if(name == ""){
	 			$("#nameerror").text("用户名不能为空"); 
	 			$("#nameerror").css("color","red");
	 		}
	 	 }); 	        
	    //给年龄的文本框添加焦点失去事件   	
	 	 $("#modal-age").blur(function(){
	 		var name = $.trim($(this).val());//去除文本框内容的前后空格  
	 		if(name == ""){
	 			$("#ageerror").text("年龄不能为空"); 
	 			$("#ageerror").css("color","red");
	 		}
	 	 }); 
	    //给文本框添加焦点获取事件,清除文本框的报错提示  
	    $(".noneerror").focus(function(){
	 			$("#nameerror").text(""); 
	 			$("#ageerror").text(""); 
	 	 }); 	  	   
</script>
新增数据后提交表单
<form id="myModal"  action="${pageContext.request.contextPath}/addPerson">
创建servlet处理/addPerson请求
@WebServlet("/addPerson")
public class AddPerson extends HttpServlet
protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1.设置请求中参数的编码
		request.setCharacterEncoding("UTF-8");
		// 2、获取表单数据
		Map<String, String[]> properties = request.getParameterMap();
		// 3、将数据封装到实体对象中
		Person person = new Person();
		try {
			BeanUtils.populate(person, properties);
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}
		// 4、手动设置表单中没有数据
		// private String id;
		person.setId(UUID.randomUUID().toString());
		// 5、传递数据给service层
		PersonUIService service = new PersonUIService();
		try {
			service.addPerson(person);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		// 发送/indexs请求查询所有数据后返回index.jsp展示所有数据
		request.getRequestDispatcher("/indexs").forward(request, response);
	}
servcie中调用dao方法
dao中操作数据库
private QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
public void addPerson(Person person) throws SQLException {
		String sql = "insert into person values(?,?,?,?)";
		runner.update(sql, person.getId(), person.getName(), person.getAge(), person.getSex());
	}
dao操作数据库后返回servlet执行后续代码,查询所有数据并展示

单条数据的修改

<tbody>
	  	<c:forEach items="${personList}" var="per" varStatus="vs">
	  		<tr >
	  			<td>${vs.count}</td><!-- 序号 -->
	  			<td>${per.name}</td>
	  			<td>${per.age}</td>
	  			<td>
	  				${per.sex==1?"男":"女" }
	  			</td>
	  			<td>
	  				<p>
				      <button id="updata" width=50px  onclick="updata(${per.id})">
				      	<a href="${pageContext.request.contextPath}/updataUI?id=${per.id}"> 
				      	编辑</a>
				      </button>
				      <button id="del" width=50px>
				      	<a href="javascript:void(0);" onclick="delPerson('${per.id}')"> 	
				      	删除</a>
				      </button>
	    			</p>
	  			</td>
	  		</tr>
	  	</c:forEach>
	  </tbody>
1.在点击编辑按钮时,通过servlet跳转更新页面并将数据携带写入响应标签中
2.点击提交按钮去携带数据去后台做数据的修改操作
点击编辑按钮时,需要一个当前记录的id值,直接在跳转时携带
${pageContext.request.contextPath}/updataUI?id=${per.id} 
创建servlet处理请求
@WebServlet("/updataUI")
public class UpdataUI extends HttpServlet
		// 获取页面传递的id
		String id = request.getParameter("id");
		// 传递id去dao层查询商品信息
		PersonUIService service = new PersonUIService();
		Person person = null;
		try {
			person = service.findPersonById(id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		// 将信息回显页面
		request.setAttribute("person", person);
 		request.getRequestDispatcher("/updata.jsp").forward(request, response);
updata.jsp
数据回显时要注意下拉列表,多选按钮的状态
<form id="myModal" action="${pageContext.request.contextPath}/upatdaPerson">
	<input type="hidden" name="id" value="${person.id}">
	  <div>
	    <p>
	      <label for="modal-name">姓名</label>
	      <input type="text" id="modal-name" name="name" value="${person.name}"class="noneerror"/>
	      <span id="nameerror"></span>
	    </p>
	    <p>
	      <label for="modal-habit">年龄</label>
	      <input type="text" id="modal-age" name="age" value="${person.age}" class="noneerror">
	      <span id="ageerror"></span>
	    </p>
	    <p>
	      <label for="modal-sex" >性别</label>
	      <select name="sex" id="sel">
	      	<option value="" selected="selected">--请选择--</option>
	      	<option value="0"></option>
	      	<option value="1"></option>
	      </select>
	    </p>
	    <p>
	      <button id="modal-submit">提交</button>	      
	    </p>
	  </div>
</form>
<script src="jquery-1.8.3.js"></script>
<script>
   $(function(){
		//更改下拉列表的状态为当前记录的状态
		//通过id选中下拉对象的option标签中数值为value='${person.sex }'的jquery对象
		//通过prop将selected属性改为true
		$("#sel option[value='${person.sex }']").prop("selected",true);	
	});
</script>
数据修改后要根据id来修改数据库表的数据
所以需要一个id值
在数据回显时将id放入隐藏域随着form表单一起提交后台
<input type="hidden" name="id" value="${person.id}">
@WebServlet("/upatdaPerson")//处理更新操作的servlet
public class UpatdaPerson extends HttpServlet 
		// 1.设置请求中参数的编码
		request.setCharacterEncoding("UTF-8");

		// 2、获取数据
		Map<String, String[]> properties = request.getParameterMap();
		// 2、封装数据
		Person person = new Person();
		try {
			BeanUtils.populate(person, properties);
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}
		System.out.println("id: " + person.getId());
		// 3、传递数据给service层
		PersonUIService service = new PersonUIService();
		try {
			service.updataPerson(person);
		} catch (SQLException e) {
			e.printStackTrace();
		}

		// 修改数据后去数据库查询所有数据并展示到index.jsp
		request.getRequestDispatcher("/indexs").forward(request, response);

单条数据的删除

del

<td>
	<p>
	    <button id="updata" width=50px  onclick="updata(${per.id})">
	    	<a href="${pageContext.request.contextPath}/updataUI?id=${per.id}"> 编辑</a>
	    </button>
	    <button id="del" width=50px>
	    	<a href="javascript:void(0);" onclick="delPerson('${per.id}')"> 删除</a>
	    </button>
	</p>
</td>
1.点击删除按钮时,弹出一个确认框,根据弹出框的返回值来确定是否删除数据
2.删除数据时根据id值来删除
<script>

//删除数据 
function delPerson(id){
		var isDel = confirm("您确认要删除吗?");
		if(isDel){
			//要删除
			location.href = "${pageContext.request.contextPath}/delPerson?id="+id;
		}
}
</script>
创建servlet处理删除的请求
@WebServlet("/delPerson")
public class DelPerson extends HttpServlet
		// 获取要删除的id
		String id = request.getParameter("id");
		// 传递id到service层
		PersonUIService service = new PersonUIService();
		try {
			service.delPersonByPid(id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		request.getRequestDispatcher("/indexs").forward(request, response);

单条数据的查询

在展示的数据上方添加一个查询框
根据输入的数据去后台查询相应的记录

在这里插入图片描述

<form action="${pageContext.request.contextPath}/search">
		姓名:<input type="text" name="name" >
		年龄:<input type="text" name="age" >
		性别:<select name="sex" >
		      	<option value="" selected="selected">--请选择--</option>
		      	<option value="2"></option>
		      	<option value="1"></option>
	        </select>
	        <input type="submit" value="搜索">
</form>
标签name属性值要与实体类的属性一致

创建servlet处理${pageContext.request.contextPath}/search请求
@WebServlet("/search")
public class SearchServlet extends HttpServlet
protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		// 1、收集表单数据
		Map<String, String[]> properties = request.getParameterMap();		
		// 2、将散装的查询数据封装到一个实体中
		Person person = new Person();
		try {
			BeanUtils.populate(person, properties);
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}
		// 3、将实体传递给service层
		PersonUIService service = new PersonUIService();
		List<Person> personSearch = null;
		try {
			personSearch = service.findByPerson(person);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		//返回查询到的数据
		request.setAttribute("personList", personSearch);

		request.getRequestDispatcher("/login.jsp").forward(request, response);
	}
service调用dao层方法
dao层操作数据库
//根据条件来拼接SQL
public List<Person> findByPerson(Person person) throws SQLException {
		// 定义一个存储实际参数的容器
		List<String> list = new ArrayList<String>();
		String sql = "select * from person where 1=1";
		if (person.getName() != null && !person.getName().trim().equals("")) {
			sql += " and name like ? ";
			list.add("%" + person.getName().trim() + "%");
		}
		if (person.getAge() != null && !person.getAge().toString().trim().equals("0")) {
			sql += " and age=? ";
			list.add(person.getAge().toString());
		}
		if (person.getSex() != null && !person.getSex().toString().trim().equals("0")) {
			sql += " and sex=? ";
			list.add(person.getSex().toString().trim());
		}
		//查看拼接的字段值
		System.out.println(list.toString());
		List<Person> personList = runner.query(sql, new BeanListHandler<Person>(Person.class), list.toArray());
		return personList;
	}
返回数据到servlet,servlet直接数据返回给index.jsp
index.jsp负责将数据展示,只需要将存入域对象的参数与前面展示数据的servlet存入的参数一致即可
request.setAttribute("personList", personSearch);
request.getRequestDispatcher("/index.jsp").forward(request, response);
<tbody>
 	<c:forEach items="${personList}" var="per" varStatus="vs">
  		<tr >
  			<td>${vs.count}</td><!-- 序号 -->
  			<td>${per.name}</td>
  			<td>${per.age}</td>
  			<td>
  				${per.sex==1?"男":"女" }
  			</td>
  			<td>
  				<p>
			      <button id="updata" width=50px  onclick="updata(${per.id})">
			      	<a href="${pageContext.request.contextPath}/updataUI?id=${per.id}"> 
			      	编辑</a>
			      </button>
			      <button id="del" width=50px>
			      	<a href="javascript:void(0);" onclick="delPerson('${per.id}')"> 	
			      	删除</a>
			      </button>
    			</p>
  			</td>
  		</tr>
  	</c:forEach>
  </tbody>

分页操作

在这里插入图片描述
1.创建处理分页请求/page的servlet

@WebServlet("/page")
public class PageServlet extends HttpServlet
在servlet中,初次访问就将当前页设置为1,这个参数是page.jsp传递的
// 初次访问当前页是第一页
String currentPageStr = request.getParameter("currentPage");
if (currentPageStr == null) {
	currentPageStr = "1";
}
// 当前页数,将字符串转为int
int currentPage = Integer.parseInt(currentPageStr);
每页显示多少条记录
// 每页默认显示5条数据
int currentCount = 5;
去service层查询分页数据
PersonUIService service = new PersonUIService();
PageBean<Person> pageBean = null;
try {
	pageBean = service.findPageBean(currentPage, currentCount);
} catch (SQLException e) {
	e.printStackTrace();
}
2.在service中处理分页的逻辑
public PageBean<Person> findPageBean(int currentPage, int currentCount)
2.1将分页相关封装为一个PageBean
public class PageBean<Person> {
	// 当前页
	private int currentPage;
	// 当前页显示的条数
	private int currentCount;
	// 总条数
	private int totalCount;
	// 总页数
	private int totalPage;
	// 每页显示的数据
	private List<Person> productList = new ArrayList<Person>();
2.2封装一个PageBean返回给servlet
// 封装一个PageBean并返回
PageBean<Person> pageBean = new PageBean();
这个PageBean中存储了数据库查询后返回分页的数据
需要手动一一为这个PageBean赋值
// 1、当前页private int currentPage;
pageBean.setCurrentPage(currentPage);
// 2、当前页显示的条数private int currentCount;
pageBean.setCurrentCount(currentCount);
// 3、总记录的条数private int totalCount;去数据库查询
int totalCount = dao.getTotalCount();
pageBean.setTotalCount(totalCount);
// 4、总页数private int totalPage; 总记录数/每页显示的记录数向上取整
int totalPage = (int) Math.ceil(1.0 * totalCount / currentCount);
// Math.ceil向上取整
// int类型 / int类型 结果仍是int
// double类型 / int类型结果还是 double类型
pageBean.setTotalPage(totalPage);
// 5、每页显示的数据private List<T> productList = new ArrayList<T>();
// 当前页第一行数据条数 = (当前页数 - 1) * 每页显示的记录数
int index = (currentPage - 1) * currentCount;
// 根据当前页的记录数与每页显示的记录数去数据库查询所有的数据并返回
List<Person> personList = dao.findPersonListForPageBean(index, currentCount);
//
pageBean.setProductList(personList);
return pageBean;//返回给servlet的数据
3.dao层分页查询数据库
private QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
// 分页查询的SQL
public List<Person> findPersonListForPageBean(int index, int currentCount) throws SQLException {
	// 分页查询的SQL
	String sql = "select * from person limit ?,?";
	return runner.query(sql, new BeanListHandler<Person>(Person.class), index, currentCount);

}
4.servlet查询的数据存入域对象返回到page.jsp中
request.setAttribute("pageBean", pageBean);
request.getRequestDispatcher("/page.jsp").forward(request, response);
5.page.jsp中解析数据
5.1解析返回的记录数据
<c:forEach items="${pageBean.productList}" var="per" varStatus="vs">
 		<tr >
 			<td>${vs.count}</td><!-- 序号 -->
 			<td>${per.name}</td>
 			<td>${per.age}</td>
 			<td>
 				${per.sex==1?"男":"女" }
 			</td>
 			<td>
 				<p>
		      <button id="updata" width=50px  onclick="updata(${per.id})">
		      	<a href="${pageContext.request.contextPath}/updataUI?id=${per.id}"> 
		      	编辑</a>
		      </button>
		      <button id="del" width=50px>
		      	<a href="javascript:void(0);" onclick="delPerson('${per.id}')"> 	
		      	删除</a>
		      </button>
   			</p>
 			</td>
 		</tr>
</c:forEach>
5.2判断当前页是否为第一页
<!-- 上一页 -->
<!-- 判断当前页是否是第一页 -->
<ul class="pagination" style="text-align: center; margin-top: 10px;">
<c:if test="${pageBean.currentPage==1 }"><!--如果当前页数为1,就是当前页  -->
	<li class="disabled">
		<a href="javascript:void(0);" aria-label="Previous">
			<span aria-hidden="true">&laquo;</span>
			<!-- 当前页不允许跳转 -->
		</a>
	</li>
</c:if>
<c:if test="${pageBean.currentPage!=1 }"><!-- 不是当前页 -->
	<li>
		<a href="${pageContext.request.contextPath }/page?currentPage=${pageBean.currentPage-1}" aria-label="Previous">
			<span aria-hidden="true">&laquo;</span>
			<!-- 可以跳转,并将点击的页数作为参数携带 -->
		</a>
	</li>
</c:if>
5.3判断是否为最后一页
<!-- 判断当前页是否是最后一页 -->
<c:if test="${pageBean.currentPage==pageBean.totalPage }">
<!-- 当前页等于总页数即为最后一页 -->
	<li class="disabled">
		<a href="javascript:void(0);" aria-label="Next"> 
			<span aria-hidden="true">&raquo;</span>
			<!-- 最后一页不允许跳转 -->
		</a>
	</li>
</c:if>
<c:if test="${pageBean.currentPage!=pageBean.totalPage }">
	<li>
		<a href="${pageContext.request.contextPath }/page?currentPage=${pageBean.currentPage+1}" aria-label="Next"> 
			<span aria-hidden="true">&raquo;</span>
		</a>
	</li>
</c:if>
5.4当前页
<c:forEach begin="1" end="${pageBean.totalPage }" var="page">
<!-- 判断当前页 -->
	<c:if test="${pageBean.currentPage==page }">
	<!-- 如果是当前页,当前页数无法跳转 -->
		<li class="active"><a href="javascript:void(0);">${page}</a></li>
	</c:if>
	<c:if test="${pageBean.currentPage!=page }">
		<li><a href="${pageContext.request.contextPath }/page?currentPage=${page}">${page}</a></li>
	</c:if>

</c:forEach>
示例图如下

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值