实体类:Book.java
package com.model;
import java.util.Date;
public class Book {
private int id;
private String name;
private Date publish_time;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getPublish_time() {
return publish_time;
}
public void setPublish_time(Date publish_time) {
this.publish_time = publish_time;
}
}
BookDao.java
package com.model;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class BookDao {
public ArrayList<Book> FindBookByPage(Page page) throws SQLException{
// MySQL select *from t_book limit currentRecord , pageSize
ArrayList<Book> bookls=new ArrayList<Book>();
Connection con=null;
PreparedStatement st=null;
ResultSet rs=null;
try{
con = JdbcUtils.getConnection();
st = con.prepareStatement("select *from t_book limit ?,?");
st.setInt(1, page.getCurrentRecord());
st.setInt(2, page.getPageSize());
rs = st.executeQuery();
while(rs.next()){
Book book = new Book();
book.setId(rs.getInt("id"));
book.setName(rs.getString("name"));
book.setPublish_time(rs.getTimestamp("publishtime"));
bookls.add(book);
}
}finally{
JdbcUtils.close(rs,st,con);
}
return bookls;
}
public int getBookNum() throws SQLException{
Connection con=null;
PreparedStatement st=null;
ResultSet rs=null;
int num =0;
try {
con = JdbcUtils.getConnection();
st = con.prepareStatement("select count(*) from t_book");
rs = st.executeQuery();
if(rs.next())
num = rs.getInt(1);
JdbcUtils.close(rs,st,con);
}finally {
JdbcUtils.close(rs,st,con);
}
return num;
}
}
BookDTO.java
package com.model;
public class BookDTO {
private int id;
private String name;
private String str_publish_time;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStr_publish_time() {
return str_publish_time;
}
public void setStr_publish_time(String str_publish_time) {
this.str_publish_time = str_publish_time;
}
}
JdbcUtils.java
package com.model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public final class JdbcUtils {
private static String url = "jdbc:mysql://localhost:3306/books";
private static String user = "root";
private static String password = "root";
private JdbcUtils() {
}
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError(e);
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
public static void close(ResultSet rs, PreparedStatement st, Connection conn) {
try {
if (rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (st != null)
st.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null)
try {
conn.close();
} catch (SQLException e) {
//todo log4j
e.printStackTrace();
}
}
}
}
}
Page.java
package com.model;
/*
* 这个Page 可以对所有的 实体进行分页显示
*
* curuentPage--->currentRecord
*
*
*/
public class Page {
private int totalRecord;//总的记录条数
private int totalPage;//总页数
private int currentPage=1;//当前页数
private int currentRecord;//当前记录的条数
private int pageSize=3 ;//每页显示的记录数量,这里默认每页显示6条
// MySQL select *from t_book limit currentRecord , pageSize
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage ) {
this.currentPage = currentPage;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalRecord,int pageSize) {
//如果总记录数除以每页显示条数可以整除,商就是总页码
if(totalRecord%pageSize == 0)
{
totalPage = totalRecord/pageSize;
}else
{
//如果总记录数除以每页显示条数不能整除,商加1才是总页码
totalPage = totalRecord/pageSize+1;
}
}
public int getCurrentRecord() {
return currentRecord;
}
public void setCurrentRecord(int currentPage,int pageSize) {
//该页的 第一条记录 =( 当前页号-1)*pageSize; 页号从0开始编制
this.currentRecord = (currentPage-1 )*pageSize;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalRecord() {
return totalRecord;
}
public void setTotalRecord(int totalRecord) {
this.totalRecord = totalRecord;
}
}
=============servlet================
Book_ShowServlet.java
package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONSerializer;
import com.model.Book;
import com.model.BookDTO;
import com.model.BookDao;
import com.model.Page;
@SuppressWarnings("serial")
public class Book_ShowServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
BookDao dao=new BookDao();
Page page=new Page();
try {
page.setTotalRecord(dao.getBookNum());
page.setCurrentPage(1);
page.setPageSize(6);
page.setTotalPage(page.getTotalRecord(), page.getPageSize());
page.setCurrentRecord(page.getCurrentPage(), page.getPageSize());
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String pageindex=request.getParameter("pagehash");
if(pageindex!=null){
int targetpage = Integer.parseInt(pageindex);
if(targetpage>=1&&targetpage<=page.getTotalPage()){
page.setCurrentPage(targetpage);
page.setCurrentRecord(page.getCurrentPage(), page.getPageSize());
}
}
ArrayList<Book> books = null;
try {
books = dao.FindBookByPage(page);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<BookDTO> bookdtos = BookToBookDTO(books);
String doc = JSONSerializer.toJSON(bookdtos).toString();
System.out.println("传送JSION"+doc);
PrintWriter out = response.getWriter();
out.print(doc);
}
private ArrayList<BookDTO> BookToBookDTO(ArrayList<Book> books) {
//把books 输出成xml文档
//String doc = JSONUtils.valueToString(books);
//books---->booksDTO
ArrayList<BookDTO> bookdtos = new ArrayList<BookDTO>();
for(int i=0;i<books.size();i++){
BookDTO dto =new BookDTO();
dto.setId(books.get(i).getId());
dto.setName(books.get(i).getName());
dto.setStr_publish_time(books.get(i).getPublish_time().toString());
bookdtos.add(dto);
}
return bookdtos;
}
}
LoginServlet.java
package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
//response.setCharacterEncoding("gb2312");
PrintWriter out = response.getWriter();
String type = request.getParameter("type");
if (type != null)
{
String isoname = request.getParameter("name");
// String name=new String(isoname.getBytes("iso8859-1"),"UTF-8");
String name = URLDecoder.decode(isoname, "UTF-8");
String password = request.getParameter("password");
if ("ajaxcheck".equals(type))
{
if (!name.equals("yzy"))
out.print("username " + name + " is not exgist");
}
if ("submit".equals(type))
{
//通过正则表达式 对密码进行验证
String errorMsg = "";
if (!Pattern.compile("^[0-9a-zA-Z\u4e00-\u9fa5]+$")
.matcher(password)
.matches())
{
errorMsg = "密码必须由数字字母组成";
response.sendRedirect("index.jsp?errorMsg=" + errorMsg);
}
else
{
if (name.equals("yzy") && password.equals("123"))
response.sendRedirect("show.jsp");
else
{
errorMsg = "用户名或密码错误";
response.sendRedirect("index.jsp?errorMsg=" + errorMsg);
}
}
}
}
}
}
================jsp===
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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">
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script>
$(function(){
$("#name").blur(function(){
var name=$("#name").val();
// var name=encodeURI($("#name").val());
// var name=encodeURI(encodeURI($("#name").val()));
// if(isChinaOrNumbOrLett(name))
$.post("LoginServlet",{ type:"ajaxcheck",name:name},function(data){$("#namecheck").text(data);} )
// else
// alert("用户名必须由汉字、字母、数字组成 ");
});
});
/*
用途:检查输入字符串是否只由汉字、字母、数字组成
输入:
value:字符串
返回:
如果通过验证返回true,否则返回false
*/
function isChinaOrNumbOrLett(s) {//判断是否是汉字、字母、数字组成
var regu = "^[0-9a-zA-Z\u4e00-\u9fa5]+$";
var re = new RegExp(regu);
if (re.test(s)) {
return true;
} else {
return false;
}
}
</script>
</head>
<body>
<center>
欢迎登陆FaceBook
<form action="LoginServlet?type=submit" method="post">
用户名;
<input type="text" name="name" id="name" />
<div id="namecheck"></div>
密 码:
<input type="password" name="password" />
<div id="passwordcheck"></div>
<%
String msg = request.getParameter("errorMsg");
if(msg!=null){
out.println(msg);
}
%>
<input type="submit" value="提交" />
</form>
<a href="/show.jsp"> aaa</a>
</center>
</body>
</html>
show.jsp
<%@ page language="java" import="java.util.*,com.model.*" pageEncoding="gb2312"%>
<%
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 'pageInfo.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">
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<STYLE>
A:hover { color:red; text-transform:uppercase; letter-spacing:1cm }
</STYLE>
<script>
var loadFinish = function(data)
{
var bookinfo = "";
var books = $.parseJSON(data);
for(var i=0;i<books.length;i++)
{
var book = books[i];
bookinfo = bookinfo+ book.id + book.name+book.str_publish_time +"<br/> " ;
}
$("#list").html(bookinfo);
}
$(function(){
//设置 超链接不可以使用
//$("a").css({disabled:disabled});
var hash = document.location.hash;
//如果不含有# 说明是第一次来的这个页面
if(!hash){showBooksInfo(1);}
$("#first").click(function(){ showBooksInfo(1);});
$("#next").click(function(){ showBooksInfo(parseInt( document.location.hash.split("#")[1])+1);});
$("#previous").click(function(){ showBooksInfo(parseInt( document.location.hash.split("#")[1])-1);});
} );
function showBooksInfo(int_pagehash)
{ //设置地址栏hash
document.location.hash = int_pagehash;
$.post("Book_ShowServlet",{pagehash:int_pagehash},loadFinish);
}
</script>
</head>
<body>
<div id="list">
</div>
<table>
<tr>
<td><a id="first" href="javascript:void(0)" >首页</a></td>
<td><a id="next" href="javascript:void(0)">下一页 </a></td>
<td><a id="previous" href="javascript:void(0)">上一页 </a></td>
</tr>
</table>
</body>
</html>
======jar===
json-lib-2.1.jar
ezorph-1.0.3.jar
jstl-1.2.jar
commons-beanutils-1.7.0.jar
commons-collections-3.2.jar
commons-lang-2.3.jar
commons-logging-1.0.4.jar
commons-logging-api-1.1.jar
standard.jar