1.建立index.jsp:
<%@ page language="java" pageEncoding="GBK"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<jsp:forward page="show.do"></jsp:forward>
</body>
</html>
2.showAction
package com.qi.action;
//1.此页面继承serlet 生成dopost dogest
//2.建立Interface 接口 DAO 包名:com.qi.dao
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 com.qi.dao.INewsdao;
import com.qi.domian.PageBean;
import com.qi.entity.NewsBean;
import com.qi.unit.DaoFactory;
public class ShowAction extends HttpServlet {
private static final long serialVersionUID = 1L;
// 16. 把dao定义在这里 减少Dao的定义次数
private INewsdao newsdao = DaoFactory.getNewsdao();
// 22.
private int rowsPerPage = 15;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//23.页码值 要看第几页
int pageNum=0;
try {
String ss=request.getParameter("page");
pageNum=Integer.valueOf(ss.trim());
} catch (Exception e) {
pageNum=1; //如果此处有问题 显示1
}
//pagenum>0需要传值
PageBean pages= new PageBean();
pages.setRowsPerPage(rowsPerPage);
if(pageNum>0)
pages.setPageNum(pageNum);
// 17.获取数据(请求转发获取数据 resquest)
try {
List<NewsBean> nlist = newsdao.selectAll(pages);//24.传入pages 再给Dao 中的接口 实现分别传入指
request.setAttribute("newList", nlist);
//28.分页工具条 传递相关数据
request.setAttribute("pages", pages);//29.在show.jsp中接受
request.getRequestDispatcher("show.jsp").forward(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
throw new ServletException(e);
}
}// 18.完成之后建立show.jsp 传送数据
// 19.show.jsp 建立完成之后创建分页Bean
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
// 23 重写init 方法 读取值
@Override
public void init() throws ServletException {
String ss = this.getServletConfig().getInitParameter("rowsPerPage");
try {
rowsPerPage = Integer.valueOf(ss.trim());
} catch (Exception e) {
rowsPerPage = 15;
}
}
}
3.package com.qi.dao;
//3.查询所有 但是写不下去 需要建立指Bean
//4.建立NewsBean 和catalogBean 包名:com.qi.entity
import java.util.List;
import com.qi.domian.PageBean;
import com.qi.entity.NewsBean;
public interface INewsdao {
//9。写这里 把NewsBeann 传入 qie 需要抛出异常
//24. 传入PageBean pages ----下来给实现传
List<NewsBean> selectAll(PageBean pages) throws Exception;
//10.完成之后定义INewsdao的实现 (和接口写在一个包里面)
// 接口 ---主外键Bean----实现接口 -----------工厂
}
4. 建立Bean
package com.qi.entity;
import java.io.Serializable;
public class CatalogBean implements Serializable {
private static final long serialVersionUID = -2518254904896712465L;
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.qi.entity;
//5.建立Bean desc +表名 看表的结果都有什么属性 在建Bean的属性
//6.一般先建立主键的 指bean 在建立外键的指Bean(都是主外键的表名称)且所有的Bean 都需要生成序列
import java.io.Serializable;
import java.sql.Date;
public class NewsBean implements Serializable {
private static final long serialVersionUID = 1419198365969358950L;
private Long id;
private String title;//新闻的标题
private Date pubdate;//发布时间
private String content;// 新闻内容
//7. 把主键的Bean 需要new过来 作为属性
private CatalogBean catalog=new CatalogBean();
//8.生成完方法后返回INewsDao
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getPubdate() {
return pubdate;
}
public void setPubdate(Date pubdate) {
this.pubdate = pubdate;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public CatalogBean getCatalog() {
return catalog;
}
public void setCatalog(CatalogBean catalog) {
this.catalog = catalog;
}
}
6.建立实现
package com.qi.dao;
//11.重写方法后开始复制工具类 及其资源文件配置 建立新的包 com.qi.unit
//12.复制驱动 获得驱动的字符串(建class browse 后 输入Driver 选择需要的驱动串 复制到properties)
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.qi.domian.PageBean;
import com.qi.entity.NewsBean;
import com.qi.unit.ConnectionManager;
public class NewsdaoImpl implements INewsdao {
@Override//26. 传值
public List<NewsBean> selectAll(PageBean pages) throws Exception {
//13.开始连接数据库
//14.数据库连接完成之后 建立工厂 建在unit包里面
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
List<NewsBean> res=new ArrayList<NewsBean>();
try {
conn=ConnectionManager.getConnection();
String sql="select n.*,c.name from t_news n left join t_catalog c on n.catalog_id=c.id where 1=1";
//27. 分页
if(pages!=null && pages.getRowsPerPage()>0){
if(pages.getPageNum()<1)
pages.setPageNum(1);//页码小于1的时候显示第一页
if(pages.getMaxPage()<1){//最大页码值小于1 需要知道总行数
String ss="select count(*)"+sql.substring(sql.indexOf("from"));
ps=conn.prepareStatement(ss);
rs=ps.executeQuery();
int rowsNum=0;
if(rs.next())
rowsNum=rs.getInt(1);//获取总行数
if(rowsNum<1)
return res;//总行数是空 返回
//求最大页码值
int maxPage=rowsNum/pages.getRowsPerPage();//总行数/每页行数
if(rowsNum%pages.getRowsPerPage()!=0)
maxPage++;
pages.setMaxPage(maxPage);
pages.setRowsNum(rowsNum);
}
if(pages.getPageNum()>pages.getMaxPage())
pages.setMaxPage(pages.getMaxPage());//页码数大于 最大页码数时 显示最大页码数
sql = "select * from (select t.*, rownum rn from (" + sql
+ ")t where rownum<=" + (pages.getPageNum()
* pages.getRowsPerPage()) + ")where rn>"
+ ((pages.getPageNum() - 1) * pages.getRowsPerPage());
// 28.此处写完之后开始写分页工具 在 ShowAction 中(48--50行左右)
}
ps=conn.prepareStatement(sql);
rs=ps.executeQuery();
while(rs.next()){
NewsBean temp= new NewsBean();
temp.setId(rs.getLong("id"));
temp.setContent(rs.getString("content"));
temp.getCatalog().setId(rs.getLong("id"));
temp.getCatalog().setName(rs.getString("name"));
temp.setTitle(rs.getString("title"));
temp.setPubdate(rs.getDate("pub_date"));;
res.add(temp);//写完建立工厂
}
} finally {
ConnectionManager.closeConnection(rs, ps, conn);
}
return res;
}
}
7 建立工厂
import com.qi.dao.INewsdao;
import com.qi.dao.NewsdaoImpl;
//15.注意都需要导包
//工厂完成后返回ShowAcion
public class DaoFactory {
public static INewsdao getNewsdao(){
return new NewsdaoImpl();
}
}
8.建工具类
package com.qi.unit;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
public class ConnectionManager {
private static final Properties ps = new Properties();
static {
loadProperties();
}
public static Connection getConnection() throws Exception {
String url = ps.getProperty("url");
String username = ps.getProperty("username");
String password = ps.getProperty("password");
return DriverManager.getConnection(url, username, password);
}
public static void closeConnection(ResultSet rs, Statement ps,
Connection conn) throws Exception {
try {
if (rs != null)
rs.close();
} finally {
try {
if (ps != null)
ps.close();
} finally {
if (conn != null)
conn.close();
}
}
}
private static void loadProperties() {
try {
if (ps.isEmpty()) {
InputStream is = ConnectionManager.class
.getResourceAsStream("database.properties");
ps.load(is);
String driverClassName = ps.getProperty("driver");
Class.forName(driverClassName);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
9.工具类的文件配置
drive=oracle.jdbc.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:EDUASK
username=COOPER
password=123456
10.分页用的pagebean
package com.qi.domian;
import java.io.Serializable;
//20.分页Bean 创建完成之后 设置xml
//21. 在<servlet>
//<init-param>
//<param-name>rowsPerPage</param-name>
//<param-value>2</param-value>
//<init-param>
// </servlet>
//22.在showAction中定义rowsPerPage
public class PageBean implements Serializable {
private static final long serialVersionUID = 7253524535008121623L;
private int pageNum;//页码数
private int rowsNum;//总行数
private int maxPage;//最大页码数
private int rowsPerPage=15;//每页显示数
//31 上下页 方法
public int getLastPage(){
if(pageNum>1)
return pageNum-1;
return 0;
}
//下一页
public int getNextPage(){
if(pageNum<maxPage)
return pageNum+1;
return 0;
}
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getRowsNum() {
return rowsNum;
}
public void setRowsNum(int rowsNum) {
this.rowsNum = rowsNum;
}
public int getMaxPage() {
return maxPage;
}
public void setMaxPage(int maxPage) {
this.maxPage = maxPage;
}
public int getRowsPerPage() {
return rowsPerPage;
}
public void setRowsPerPage(int rowsPerPage) {
this.rowsPerPage = rowsPerPage;
}
}
11.show.jsp 页面
<%@page import="com.qi.domian.PageBean"%>
<%@page import="java.util.List"%>
<%@page import="com.qi.entity.NewsBean"%>
<%@ page language="java" pageEncoding="GBK"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title><%=application.getInitParameter("appName")%>></title>
</head>
<body>
<table border="1">
<tr>
<th>新闻编号</th>
<th>新闻标题</th>
<th>发布时间</th>
<th>新闻类型</th>
</tr>
<%
Object obj=request.getAttribute("newList");
if(obj!=null &&((List) obj).size()>0){
List<NewsBean>nlist=(List<NewsBean>)obj;
for(NewsBean temp:nlist){
%><tr>
<td><%=temp.getId()%></td>
<td <%out.println(temp.getTitle());%>></td>
<td><%=temp.getPubdate()%></td>
<td><%=temp.getCatalog().getName()%></td>
</tr>
<%
}
//29.接受数据
//30.在上一页 下一页的时候 返回到 PageBean 写上下页的方法
Object oo=request.getAttribute("pages");
if(oo!=null && oo instanceof PageBean){
PageBean pages=(PageBean)oo;
if(pages.getMaxPage()>1){
%>
<tr>
<td colspan="4" align="rigth"><a href="show.do?page=1">第一页</a>
<%if(pages.getLastPage()>0) {%>
<a herf="show.do?page=<%=pages.getLastPage() %>">上一页</a>
<% }if( pages.getNextPage()>0){ %>
<a href="show.do?page=<%=pages.getNextPage() %>">下一页</a>
<%} %>
<a href="show.do?page=<%=pages.getMaxPage()%>">末 页</a></td>
</tr>
<%}else{
%><tr><td colspan=4>没有任何新闻信息</td></tr>)
<%
}
}}
%>
</table>
</body>
</html>
12.xml 文件配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>News_Catalog</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>appName</param-name>
<param-value>新闻管理系统</param-value>
</context-param>
<servlet>
<description></description>
<display-name>ShowAction</display-name>
<servlet-name>ShowAction</servlet-name>
<servlet-class>com.qi.action.ShowAction</servlet-class>
<init-param>
<param-name>rowsPerPage</param-name>
<param-value>2</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ShowAction</servlet-name>
<url-pattern>/show.do</url-pattern>
</servlet-mapping>
</web-app>
11111111111111111111111111111111111111111111111111111
13.表中要用的数据
create table t_catalog(
id bigint primary key auto_increment,
name varchar(32)not null
)engine=innodb default charsetutf8;
create table t_news(
id bigint primary ket auto_increment,
title varchar(30) not null,
pub_date timestamp default current_timestamp,
content varchar(300),
catlog_id bigint not null,
foreign key(catalog_id)references t_Catalog(id) on delete cascade
)engine=innodb default charsetutf8;
insert into t_catalog(name) values('财经新闻'),('体育新闻'),('军事新闻');
insert into t_news(title,catalog_id)values('股市崩盘',1)('房地产暴涨',2)('中国足球夺冠',2)('中印开战',3);