首先引入自定义标签知识点:
自定义标签
1、封装逻辑的java
逻辑代码
输入页面的内容
2、用描述文件描述标签
注册有个标签
3、使用
引用标签库(taglib uri)
运用标签
接下来是自定义标签的一个小demo:
首先写好逻辑代码MyTag
package cn.com.demo.tags;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;
public class MyTag extends BodyTagSupport {
@Override
public int doEndTag() throws JspException {
//处理数据
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String dateString = format.format(date);
JspWriter out = this.pageContext.getOut();
try {
out.println(dateString);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return super.doEndTag();
}
}
接下来考虑到安全性,就在WEB-INF文件中创建tld子文件,再在其中创建XXX.tld,对写好的java代码绑定到一个标签中(例子中将写好的MyTag绑定到time:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>mytags</short-name>
<tag>
<name>time</name>
<tag-class>cn.com.demo.tags.MyTag</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
最后就可以在jsp中使用了,不过首先还是得先引入:
<%@taglib uri="/WEB-INF/tld/mytags.tld" prefix="m"%>
然后在代码中就可以直接像jsp标签那样使用了:
<body>
<m:time/>
</body>
现在开始实现分页的逻辑:
首先创建一个javaBean
package cn.com.demo.entity;
public class User {
private String username;
private int age;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
然后模拟已经连接数据库的逻辑:
package cn.com.demo.service;
import java.util.ArrayList;
import java.util.List;
import cn.com.demo.entity.User;
public class UserService {
public List<User> findByPage(int pageNo)
{
List<User> list = null;
int sumCount = this.findUserCount();
int first = (pageNo-1)*5;
int last = pageNo*5;
if(last>=sumCount)
{
last = sumCount;
}
list = new ArrayList<User>();
User user = null;
for(int i=first;i<=last;i++)
{
user = new User();
user.setAge(i);
user.setUsername("user"+i);
list.add(user);
}
return list;
}
public int findUserCount()
{
return 18;
}
public int findTotalPageNo()
{
int sumNo = 0;
int count = this.findUserCount();
sumNo = count/5;
if(sumNo%5!=0)
{
sumNo = sumNo+1;
}
return sumNo;
}
}
然后实现Servlet,其中需要向页面传3个值(总页数、当前页、当前查找的数据)
package cn.com.demo.servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.com.demo.entity.User;
import cn.com.demo.service.UserService;
public class SearchUserServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String pageNoStr = req.getParameter("pageNo");
int pageNo = 1;
try{
pageNo = Integer.parseInt(pageNoStr);
}catch (Exception e) {
// TODO: handle exception
}
UserService userService = new UserService();
//获取总页数
int sumPageNo = userService.findTotalPageNo();
if(pageNo>=sumPageNo)
{
pageNo = sumPageNo;
}
if(pageNo<=1)
{
pageNo = 1;
}
List<User> list = userService.findByPage(pageNo);
req.setAttribute("pageNo",pageNo);
req.setAttribute("sumPageNo", sumPageNo);
req.setAttribute("list",list);
req.getRequestDispatcher("index.jsp").forward(req, res);
}
}
最后是前端代码,使用Js来控制页码的变换:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<table>
<tr>
<td>用户名</td>
<td>年龄</td>
</tr>
<c:forEach items="${list}" var="user">
<tr>
<td>${user.username }</td>
<td>${user.age }</td>
</tr>
</c:forEach>
<tr align="center">
<td>
<a href="javascript:void" onclick="toFirst()">首页</a>
<a href="javascript:void" onclick="toPrev()">上一页</a>
<a href="javascript:void" onclick="toNext()">下一页</a>
<a href="javascript:void" onclick="toLast()">末页</a>
</td>
</tr>
</table>
</body>
<script type="text/javascript">
var pageNo = ${pageNo};
var sumPageNo = ${sumPageNo};
function toFirst(){
pageNo = 1;
toViewPage();
}
function toLast(){
pageNo = sumPageNo;
toViewPage();
}
function toNext(){
pageNo = pageNo+1;
if(pageNo>sumPageNo)
{
pageNo = sumPageNo;
}
toViewPage();
}
function toPrev(){
pageNo = pageNo-1;
if(pageNo<1)
{
pageNo =1 ;
}
toViewPage();
}
function toViewPage(){
location.href="searchUserServlet?pageNo="+pageNo+"&"+Math.random();
}
</script>
</html>
当解决上述两个问题时,就可以开始研究分页自定义标签的思路了,能够复用的部分就是“首页、上一页、下一页、末页”这控制分页的超链接,因为显示数据会因为数据库字段的不同而不同,所以不能够复用。所以创建一个自定义tag:
package cn.com.demo.tag;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;
public class PageTag extends BodyTagSupport {
private String pageNoName;
private String sumPageName;
private String url;
public String getPageNoName() {
return pageNoName;
}
public void setPageNoName(String pageNoName) {
this.pageNoName = pageNoName;
}
public String getSumPageName() {
return sumPageName;
}
public void setSumPageName(String sumPageName) {
this.sumPageName = sumPageName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public int doEndTag() throws JspException {
JspWriter out = this.pageContext.getOut();
try{
out.println("<a href='javascript:void' onclick='toFirst()'>首页</a>");
out.println(" <a href='javascript:void' onclick='toPrev()'>上一页</a>");
out.println(" <a href='javascript:void' onclick='toNext()'>下一页</a>");
out.println(" <a href='javascript:void' onclick='toLast()'>末页</a>");
out.println(" <script type='text/javascript'>");
Object value = pageContext.getRequest().getAttribute(this.pageNoName);
out.println(" var pageNo = "+value+";");
value = pageContext.getRequest().getAttribute(this.sumPageName);
out.println(" var sumPageNo = "+value+";");
out.println(" function toFirst(){");
out.println(" pageNo = 1;");
out.println(" toViewPage();");
out.println(" }");
out.println(" function toLast(){");
out.println(" pageNo = sumPageNo;");
out.println(" toViewPage();");
out.println(" }");
out.println("function toNext(){");
out.println("pageNo = pageNo+1;");
out.println("if(pageNo>sumPageNo)");
out.println("{");
out.println("pageNo = sumPageNo;");
out.println("}");
out.println("toViewPage();");
out.println("}");
out.println("function toPrev(){");
out.println("pageNo = pageNo-1;");
out.println("if(pageNo<1)");
out.println("{");
out.println(" pageNo =1 ;");
out.println("}");
out.println("toViewPage();");
out.println("}");
out.println("function toViewPage(){");
value = pageContext.getRequest().getAttribute(this.pageNoName);
out.println("location.href='"+url+"?"+this.pageNoName+"='+pageNo+'&'+Math.random();");
out.println("}");
out.println(" </script>");
}catch (Exception e) {
// TODO: handle exception
}
return super.doEndTag();
}
}
对其进行配置:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>matags</short-name>
<uri>http://mytags</uri>
<tag>
<name>page</name>
<tag-class>cn.com.demo.tag.PageTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>pageNoName</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<type>java.lang.String</type>
</attribute>
<attribute>
<name>sumPageName</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<type>java.lang.String</type>
</attribute>
<attribute>
<name>url</name>
<required>true</required>
<type>java.lang.String</type>
</attribute>
</tag>
</taglib>
最后页面就可以改为:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://mytags" prefix="t"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'tttttt.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<table>
<tr>
<td>用户名</td>
<td>年龄</td>
</tr>
<c:forEach items="${list}" var="user">
<tr>
<td>${user.username }</td>
<td>${user.age }</td>
</tr>
</c:forEach>
<tr align="center">
<td>
<t:page url="searchUserServlet" pageNoName="pageNo" sumPageName="sumPageNo"/>
</td>
</tr>
</table>
</body>
</html>