话说:
各位读者朋友,晚上好!这一篇展示首页。

难度系数:★★★☆☆
建议用时:1天 实际用时1天
目录


  1. 工具类
  2. 首页面index.jsp
  3. 首页面样式
  4. 后端代码

首页面复杂点:
1.SQL语句复杂点,要统计下回复次数;

2.搜索。单独搜索简单,但是要实现在不同栏目下的搜索,就相对复杂些,而且不论搜索还是分栏目,分页都要带上;

1. 工具类

DBUtil 连接数据库
GetFormatTimeUtil 格式化时间
GetPreparedStatementUtil 获取PS对象,遍历参数
GetPropertyUtil 获取静态资源
GetStrToInt 字符串转int

DBUtil 连接数据库

package com.hmc.util;
/**
*
*2017年12月30日
*User:Meice
*下午8:35:12
*/import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;public class DBUtil {//封装连接数据库的方法//处理异常:java.sql.SQLNonTransientConnectionException: Could not create connection to database server.static  int retryCount = 5;  static  boolean transactionCompleted = false;  //1.加载驱动static {try {Class.forName(GetPropertyUtil.getVal("driver"));} catch (ClassNotFoundException e) {e.printStackTrace();}}//2.获取连接public static Connection getConn() {do {//分开放 尽量不要合并写在一块String url = GetPropertyUtil.getVal("url");String user = GetPropertyUtil.getVal("user");String password = GetPropertyUtil.getVal("password");try {Connection conn =   DriverManager.getConnection(url, user, password);return conn;} catch (SQLException e) {e.printStackTrace();String sqlState = e.getSQLState();if("08S01".equals(sqlState) || "40001".equals(sqlState)) {retryCount--;}else {retryCount = 0;}}return null;}while(!transactionCompleted && retryCount>0);}//3.关闭资源public static void closeConn(Connection conn,PreparedStatement ps,ResultSet rs) {//Alt + Shift + Z 抛出语句块异常try {if(rs != null) rs.close();if(ps != null) ps.close();if(conn != null) conn.close();} catch (SQLException e) {e.printStackTrace();}}}

GetFormatTimeUtil 格式化时间

package com.hmc.util;
import java.text.SimpleDateFormat;
import java.util.Date;/**
*
*2017年12月30日
*User:Meice
*下午9:44:05
*/
public class GetFormatTimeUtil {public static String getFormatTime(int TwelveOrTwentyFour) {Date date = new Date();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");if(TwelveOrTwentyFour == 12) {return sdf2.format(date);}else if(TwelveOrTwentyFour == 24){return sdf.format(date);}else {return null;}}}

GetPreparedStatementUtil 获取PS对象,遍历参数

package com.hmc.util;
/**
*
*2017年12月30日
*User:Meice
*下午9:04:45
*/import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;public class GetPreparedStatementUtil {//定义获取PrepatedStatement对象public static PreparedStatement getPs(Connection conn,PreparedStatement ps,String sql,Object... params) {try {ps =       conn.prepareStatement(sql);//这样有无参数都可以搞定if(params!= null) {for(int i=0;i<params.length;i++) {ps.setObject((i+1),params[i]);}}return ps;} catch (SQLException e) {e.printStackTrace();}return null;}}

GetPropertyUtil 获取静态资源

package com.hmc.util;import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;/**
*
*2017年12月30日
*User:Meice
*下午8:49:31
*/
public class GetPropertyUtil {//获取静态资源public static String getVal(String key) {Properties pro = new Properties();InputStream is;try {is = new FileInputStream("D:\\WorkSpace\\eclipse\\xiaomeibbs\\db.properties");pro.load(is);return pro.getProperty(key);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return null;}}

GetStrToInt 字符串转int

package com.hmc.util;
/**
*
*2018年1月1日
*User:Meice
*上午11:46:00
*/
public class GetStrToInt {public static int getInt(String str) {if(str!= null && !str.equals("")) {return Integer.parseInt(str);}return 0;}
}

这里要总结一下下:
1)连接数据库,读取配置文件的时候,如果直接把配置文件放到工程目录下,测试是没有问题的,但是一旦涉及Servlet,就会找不到,所以要写绝对路径。

2)封装的时候,不要仅仅考虑方便,比如获取PreparedStatement,要考虑到每次都要用一个新的对象,让外界提供Connection conn,PrepatedStatement
这样,每次调用,对象都不同,避免调用过程中,对象发生混乱!

3)获取时间的工具类可有可无。处理数据库时间方式多样,一般有这几种:

a.数据库时间设置为varchar(),实体类为String,用我写的工具类来添加数据;
b.数据库时间直接设置为Date,传值的时候直接new Date()即可;
c.数据库时间直接设置为Date或者datetime,直接在SQL语句中传值now();
d.数据库时间不要设置为timestamp.因为这个默认为now(),虽然根本都不用传值,但是只要数据发生变化,比如修改、删除,那么这个时间都会变成修改、删除的时间,这并不是我们想要的。

2. 首页面index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c" %>
<!--Author:Meice 2017年12月30日下午12:13:19 -->
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>小确幸论坛</title>
<!--  引入外部样式-->
<link href="css/textList.css"  rel="stylesheet" type="text/css"><style type="text/css">/* link visited hover active    love hate  */a:visited{color:gray;}a:hover{color: orange;}</style><!-- 如果当前栏目被选择,给一个样式 -->
<script type="text/javascript">function changeBgColor1() {//alert("进来了!");var a = document.getElementById("liOne");//a.setAttribute("background-color","orange");a.style.backgroundColor = "orange";}
</script></head>
<body>
<!--引入头部  --><jsp:include page="head.jsp"></jsp:include><!--搜索框的div  --><div id="search"><form action="textShow" method="get"><input type="text" name="search" style="width:300px;height:40px;"><input type="submit" value="搜索一下" style="width:60px;height:40px;"><input type="hidden" name="categoryId" value="${categoryId}"></form></div><!--登录后用户信息  --><div id="userInfo"><span class="userInfo">欢迎【${user.userNick}】!</span><br/><a href="userInfo" class="userInfo" style="color:orange;">个人中心</a><a href="login.jsp" class="userInfo">退出</a></div><!--栏目div  --><div id="category"><ul><!-- 前端不好,只能这样变化栏目背景色 --><c:if test="${categoryId==0 }"><li  style="background-color:rgb(104,189,69);"> <a href="textShow" onclick="changeBgColor1()">首页</a></li></c:if><c:if test="${categoryId!=0 }"><li >   <a href="textShow" onclick="changeBgColor1()">首页</a></li></c:if><c:if test="${categoryId ==1 }"><li id="liTwo" style="background-color:rgb(104,189,69);" >  <a href="textShow?categoryId=1">Java</a></li></c:if><c:if test="${categoryId !=1 }"><li id="liTwo"> <a href="textShow?categoryId=1">Java</a></li></c:if><c:if test="${categoryId ==2 }"><li   style="background-color:rgb(104,189,69);"><a href="textShow?categoryId=2">MySQL</a></li></c:if><c:if test="${categoryId !=2 }"><li><a href="textShow?categoryId=2">MySQL</a></li></c:if><c:if test="${categoryId ==3 }"><li  style="background-color:rgb(104,189,69);"><a href="textShow?categoryId=3">大数据</a></li></c:if><c:if test="${categoryId !=3 }"><li><a href="textShow?categoryId=3">大数据</a></li></c:if><c:if test="${categoryId == 4 }"><li style="background-color:rgb(104,189,69);"><a href="textShow?categoryId=4">人工智能</a></li></c:if><c:if test="${categoryId != 4 }"><li><a href="textShow?categoryId=4">人工智能</a></li></c:if><c:if test="${categoryId == 5 }"><li style="background-color:rgb(104,189,69);"><a href="textShow?categoryId=5">HTML5</a></li></c:if><c:if test="${categoryId != 5 }"><li><a href="textShow?categoryId=5">HTML5</a></li></c:if><c:if test="${categoryId == 6 }"><li  style="background-color:rgb(104,189,69);background-color: rgb();"><a href="textShow?categoryId=6">生活</a></li></c:if><c:if test="${categoryId !=6 }"><li><a href="textShow?categoryId=6">生活</a></li></c:if><c:if test="${categoryId == 7 }"><li  style="background-color:rgb(104,189,69);"><a href="textShow?categoryId=7">有趣有料</a></li></c:if><c:if test="${categoryId != 7 }"><li><a href="textShow?categoryId=7">有趣有料</a></li></c:if></ul></div><!--帖子列表div  --><div id="textList"><table border="1 solid green" width="90%" align="center"><thead><tr style="background-color: rgb(233,248,230);"><th>标题</th><th>作者</th><th>评论数量</th><th>发帖时间</th></tr></thead><tbody><!--遍历textList取值  --><c:if test="${ empty textList}"><tr><td colspan="4" style="color:red;font-weight:bolder;" align="center">It's a pity,未查询到数据奥~~</td></tr></c:if><c:forEach var="ListShow" items="${textList}"><c:if test="${!empty textList}"><tr><td><a href="textDetail?textId=${ListShow.textId}">${ListShow.title }</a></td><td align="center"><a href="#">${ListShow.user.userNick}</a></td><td align="center">${ListShow.replyCount }</td><td align="center">${ListShow.textTime}</td></tr></c:if></c:forEach><tr><td colspan="4" align="center" ><c:if test="${pageIndex>1 }"><button onclick="window.location.href='textShow?pageIndex=1&categoryId=${categoryId }&search=${search}'" style="width:50px;height:25px;" >首页</button><button onclick="window.location.href='textShow?pageIndex=${pageIndex-1}&categoryId=${categoryId }&search=${search}'">上一页</button></c:if><!--总页数要>10 才按照每页10条分页  --><c:if test="${totalPage>=10}"><!--处理前10页  --><c:if test="${pageIndex<=10 }"><c:forEach var="i" begin="1" end="10"><c:if test="${pageIndex==i}">${i}</c:if><c:if test="${pageIndex!=i }"><button onclick="window.location.href='textShow?pageIndex=${i}&categoryId=${categoryId }&search=${search}'" style="width:25px;height:25px;">${i}</button></c:if></c:forEach></c:if><!-- 处理大于10页 小于(totalPage-10)页 --><c:if test="${pageIndex>10 and pageIndex<(totalPage-4 )}"><c:forEach var="i" begin="${pageIndex-4 }" end="${pageIndex+5}"><c:if test="${pageIndex==i}">${i}</c:if><c:if test="${pageIndex!=i }"><button onclick="window.location.href='textShow?pageIndex=${i}&categoryId=${categoryId }&search=${search}'" style="width:25px;height:25px;">${i}</button></c:if></c:forEach></c:if><!-- 处理最后几页 --><c:if test="${pageIndex>=(totalPage-4) }"><c:forEach var="i" begin="${totalPage-9}" end="${totalPage}"><c:if test="${pageIndex==i}">${i}</c:if><c:if test="${pageIndex!=i }"><button onclick="window.location.href='textShow?pageIndex=${i}&categoryId=${categoryId }&search=${search}'" style="width:25px;height:25px;">${i}</button></c:if></c:forEach></c:if></c:if><!-- 总页数小于10  --><c:if test="${totalPage<10 }"><c:forEach var="i" begin="1" end="${totalPage}"><c:if test="${pageIndex==i}">${i}</c:if><c:if test="${pageIndex!=i }"><button onclick="window.location.href='textShow?pageIndex=${i}&categoryId=${categoryId }&search=${search}'" style="width:25px;height:25px;">${i}</button></c:if></c:forEach></c:if><c:if test="${pageIndex<totalPage }"><button onclick="window.location.href='textShow?pageIndex=${pageIndex+1}&categoryId=${categoryId }&search=${search}'">下一页</button><button onclick="window.location.href='textShow?pageIndex=${totalPage}&categoryId=${categoryId }&search=${search}'" style="width:50px;height:25px;" >末页</button></c:if>&nbsp;&nbsp;&nbsp;  <span style="color:orange;">${pageIndex }</span>/${totalPage}<!-- <div style="float:right;">`<form action="#" mehtod="get"><select id="goto" name="goto" ><option value="5">5</option><option value="10">10</option><option value="20">20</option> <input type="submit" value="goto"></form></div> --></td></tr></tbody></table></div><!--  引入尾部--><jsp:include page="foot.jsp"></jsp:include></body>
</html>

首页面后台是重点,前端分页是重点。

3.首页面样式
textList.css

@CHARSET "UTF-8";
/*--Author:Meice
2018年1月1日 下午4:02:50*//* 搜索框样式 */
#search{
/*  border:1px solid red; */width:450px;height:80px;margin: -70px 0px 0px 600px;}/*  登录信息样式*/
#userInfo{/* border: 1px solid red; */width: 200px;height: 60px;margin: -100px 0px 0px 1280px;
}/* 栏目样式 */
#category{/* border:1px solid red; */width:200px;height:300px;margin: 60px 0px 0px 70px;
}/* 帖子列表样式 */
#textList{/* border:1px solid red; */width:1200px;height:700px;margin: -300px 0px 0px 700px;float:right;
}/*
去除a 标签下划线*/a{text-decoration:none;/* 因为是蓝色字体,所以 */color:black;}/*设置li标签样式  */#category ul li{list-style:none;margin:15px;background-color: rgb(233,248,230);height:35px;width:100px;font-weight:bolder;}/* 登录信息字体样式  */
.userInfo{color:white;font-weight:bolder;font-size:15px;}

4. 后端代码
因为搜索、分栏、及首页都是在同一个页面展示,而且有分页,尤其是分页的时候,点击要去调用一个Servlet,所以最好的处理方式是按照接收的参数(栏目Id,搜索内容)来确定调用不同的方法,但是用一个Servlet来写。

TextShowDao
TextShowDaoImpl

TextShowService
TextShowServiceImpl

TextShowServlet
TextSearchServlet

TextShowDao

package com.hmc.dao;import java.util.List;import com.hmc.pojo.Category;
import com.hmc.pojo.TextAll;
import com.hmc.pojo.TextShow;
import com.hmc.pojo.User;
import com.hmc.pojo.UserInfo;/**
*
*2018年1月1日
*User:Meice
*上午10:59:20
*/
public interface TextShowDao {//1.查询首页帖子方法List<TextShow> listText (String sql,Object... params);//2.根据帖子Id返回整个user对象User listUser(int textId);//3.根据帖子Id,首页显示个人中心List<UserInfo> listUserInfo(String sql,Object... params);//4.帖子详情显示方法List<TextAll> listAll(String sql,Object... params);
}

TextShowDaoImpl

package com.hmc.dao;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;import com.hmc.pojo.Category;
import com.hmc.pojo.Reply;
import com.hmc.pojo.Text;
import com.hmc.pojo.TextAll;
import com.hmc.pojo.TextShow;
import com.hmc.pojo.User;
import com.hmc.pojo.UserInfo;
import com.hmc.util.DBUtil;
import com.hmc.util.GetPreparedStatementUtil;
import com.mysql.cj.api.xdevapi.Result;/**
*
*2018年1月1日
*User:Meice
*上午11:00:23
*/
public class TextShowDaoImpl implements TextShowDao {//1.返回首页帖子列表@Overridepublic List<TextShow> listText(String sql, Object... params) {Connection conn = DBUtil.getConn();PreparedStatement ps = null;ResultSet rs = null;ps = GetPreparedStatementUtil.getPs(conn, ps, sql, params);List<TextShow> listText = new ArrayList<>();//执行查询try {rs =    ps.executeQuery();while(rs != null && rs.next()) {TextShow ts = new TextShow();int textId = rs.getInt("textId");String title = rs.getString("title");//根据textId获取整个用户对象//select userId from text where textId = ?int replyCount = rs.getInt("replyCount");String textTime = rs.getString("textTime");User user = listUser(textId);//System.out.println("第一个user对象 "+user);ts.setTextId(textId);ts.setTitle(title);ts.setUser(user);ts.setReplyCount(replyCount);ts.setTextTime(textTime);listText.add(ts);}return listText;} catch (SQLException e) {e.printStackTrace();}finally {DBUtil.closeConn(conn, ps, rs);}return null;}//2.根据帖子Id返回整个user对象@Overridepublic User listUser(int textId) {Connection conn = DBUtil.getConn();PreparedStatement ps = null;ResultSet rs2 = null;List<User> listUser = new ArrayList<>();String sql = "select userId from text where textId = ?";Object[] params = {textId};PreparedStatement   ps2 = GetPreparedStatementUtil.getPs(conn, ps, sql, params);try {rs2 =  ps2.executeQuery();int userId =0;if(rs2!= null && rs2.next()) {userId =    rs2.getInt("userId");}//根据userId,返回对象UserLoginDao uld = new UserLoginDaoImpl();String sql2 = "select * from user where userId = ?";Object[] params2 = {userId};List<User> listUser2 =  uld.listUser(sql2, params2);return listUser2.get(0);} catch (SQLException e) {e.printStackTrace();}finally {DBUtil.closeConn(conn, ps2, rs2);}return null;}//3.根据帖子Id,展示个人中心@Overridepublic List<UserInfo> listUserInfo(String sql, Object... params) {Connection conn = DBUtil.getConn();List<UserInfo> list = new ArrayList<>();PreparedStatement ps = null;PreparedStatement ps3 = GetPreparedStatementUtil.getPs(conn, ps, sql, params);try {ResultSet rs3 = ps3.executeQuery();while(rs3!= null && rs3.next()) {UserInfo ui = new UserInfo();Text text = new Text();text.setTextId(rs3.getInt("textId"));text.setTitle(rs3.getString("title"));text.setContext(rs3.getString("context"));text.setTextTime(rs3.getString("textTime"));text.setUserId(rs3.getInt("userId"));Category category = new Category();category.setCategoryId(rs3.getInt("categoryId"));category.setCategoryName(rs3.getString("categoryName"));ui.setText(text);ui.setCategory(category);list.add(ui);}return list;    } catch (SQLException e) {e.printStackTrace();}finally {DBUtil.closeConn(conn, ps3, null);}return null;}//4.显示帖子详情,四表联查@Overridepublic List<TextAll> listAll(String sql, Object... params) {Connection conn = DBUtil.getConn();List<TextAll> listAll = new ArrayList<>();System.out.println("进来了...");PreparedStatement ps = null;PreparedStatement ps4 = GetPreparedStatementUtil.getPs(conn, ps, sql, params);try {ResultSet rs4 = ps4.executeQuery();while(rs4 != null && rs4.next()) {TextAll ta = new TextAll();Text text = new Text();text.setTextId(rs4.getInt("textId"));text.setTitle(rs4.getString("title"));text.setContext(rs4.getString("context"));text.setTextTime(rs4.getString("textTime"));text.setUserId(rs4.getInt("userId"));text.setCategoryId(rs4.getInt("categoryId"));User user = new User();user.setUserId(rs4.getInt("userId"));//text.setUserId(user.getUserId()); //据说,这样会导致hashCode()重复调用,导致内存溢出!user.setUserName(rs4.getString("userName"));user.setUserNick(rs4.getString("userNick"));user.setLoginTime(rs4.getString("loginTime"));user.setRegisterTime(rs4.getString("registerTime"));Category category = new Category();category.setCategoryId(rs4.getInt("categoryId"));//text.setCategoryId(category.getCategoryId());category.setCategoryName(rs4.getString("categoryName"));Reply reply = new Reply();reply.setReplyId(rs4.getInt("replyId"));reply.setReplyContext(rs4.getString("replyContext"));reply.setReplyTime(rs4.getString("replyTime"));reply.setReplyCount(rs4.getInt("replyCount"));//reply.setTextId(text.getTextId());//reply.setUserId(user.getUserId());reply.setTextId(rs4.getInt("textId"));reply.setReplyCount(rs4.getInt("replyCount"));ta.setText(text);ta.setUser(user);ta.setCategory(category);ta.setReply(reply);listAll.add(ta);}return listAll;} catch (SQLException e) {e.printStackTrace();}finally {DBUtil.closeConn(conn, ps4, null);}return null;}//5.返回帖子总条目数public int getCountAll(String sql,Object... params) {int countAll = 0;//String sql = "select count(textId) countAll from text";Connection conn = DBUtil.getConn();PreparedStatement ps = null;ps = GetPreparedStatementUtil.getPs(conn, ps, sql, params);ResultSet rs = null;try {rs = ps.executeQuery();if(rs != null && rs.next()) {countAll = rs.getInt("countAll");}} catch (SQLException e) {e.printStackTrace();}finally {DBUtil.closeConn(conn, ps, rs);}return countAll;}}

代码有注释,就不在赘述。

TextShowService

package com.hmc.service;
/**
*
*2018年1月1日
*User:Meice
*上午10:58:08
*/import java.util.List;import com.hmc.pojo.Category;
import com.hmc.pojo.TextAll;
import com.hmc.pojo.TextShow;
import com.hmc.pojo.User;
import com.hmc.pojo.UserInfo;public interface TextShowService {//1.查询首页帖子方法List<TextShow> listText (String sql,Object... params);//2.根据帖子Id返回整个user对象User listUser(int textId);//3.根据帖子Id,返回整个Category对象  因为查,只有反射可以优化,只有把对象写固定List<UserInfo> listUserInfo(String sql,Object... params);//4.帖子详情显示方法List<TextAll> listAll(String sql,Object... params);}

TextShowServiceImpl

package com.hmc.service;import java.util.List;import com.hmc.dao.TextShowDaoImpl;
import com.hmc.pojo.Category;
import com.hmc.pojo.TextAll;
import com.hmc.pojo.TextShow;
import com.hmc.pojo.User;
import com.hmc.pojo.UserInfo;/**
*
*2018年1月1日
*User:Meice
*上午10:59:51
*/
public class TextShowServiceImpl implements TextShowService {//1.首页显示帖子@Overridepublic List<TextShow> listText(String sql, Object... params) {return new TextShowDaoImpl().listText(sql, params);}//2.根据textId返回user对象@Overridepublic User listUser(int textId) {return new TextShowDaoImpl().listUser(textId);}//3.根据帖子Id,个人中心显示内容@Overridepublic List<UserInfo> listUserInfo(String sql, Object... params) {return new TextShowDaoImpl().listUserInfo(sql, params);}//4.显示帖子详情(四表联查)@Overridepublic List<TextAll> listAll(String sql, Object... params) {return new TextShowDaoImpl().listAll(sql, params);}}

TextShowServlet

package com.hmc.controller;
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 org.hamcrest.core.Is;
import com.hmc.dao.TextShowDaoImpl;
import com.hmc.pojo.TextShow;
import com.hmc.service.TextShowService;
import com.hmc.service.TextShowServiceImpl;
import com.hmc.util.GetStrToInt;/**
*
*2018年1月1日
*User:Meice
*下午7:00:16
*/
public class TextShowServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {TextShowService tss = new TextShowServiceImpl();TextShowDaoImpl tsd = new TextShowDaoImpl();//1.接收参数//传递2个参数search 、 categoryId String search = req.getParameter("search");String categoryIdStr = req.getParameter("categoryId");int categoryId = GetStrToInt.getInt(categoryIdStr);System.out.println("search内容:"+search+"categoryId "+categoryId);//得到当前页pageIndex String pageIndexStr = req.getParameter("pageIndex");int pageIndex = GetStrToInt.getInt(pageIndexStr);/*** 分页* 分页五要素:* countAll 总条目数* pageSize 每页显示数目* totalPage 总页数 (countAll /pageSize)* pageIndex 当前页* offset 偏移量,从第几条数据开始显示,也就是limit ?  (pageindex-1)*pageSize*/int countAll =0;//查首页帖子总条目数String sqlCountAll = "select count(textId) countAll from text";countAll = new TextShowDaoImpl().getCountAll(sqlCountAll, null);int pageSize = 20;int totalPage =(int)Math.ceil((double) countAll/pageSize);System.out.println("总页数:"+totalPage);if(pageIndex ==0) {pageIndex = 1;}//页面传int offset  = (pageIndex-1)*pageSize;//limit offset,pageSize;//2.调用方法//定义全局的List<TextShow> textList 不论首页、搜索 、栏目都用同一个。分页只用做一次List<TextShow> textList = null;//执行首页查询方法if( search !=null && categoryId ==0) {//这是多余的判断/*if(search.equals("")) {search = "";}*///TODO  调用模糊查询方法System.out.println("调用模糊查询方法.....模糊查询进来了。。。。。。");String sqlSearch = "  select a.textId,a.title,a.userId,b.replyCount,a.textTime from (select t.textId,t.title,t.userId,t.textTime from text t left join user u on t.textId = u.userId) a "+ "left join (select r.textId, count(r.replyId) replyCount from reply  r group by textId) b "+ "on a.textId = b.textId where a.title like ? order by a.textId desc limit ?,?";System.out.println(sqlSearch);System.out.println("search内容:"+search);Object[] paramsSearch = {"%"+search+"%",offset,pageSize};textList = tss.listText(sqlSearch, paramsSearch);System.out.println("模糊查询结果:"+textList);System.out.println("模糊查询textList大小:"+textList.size());//改变总页数String sqlSearchCountAll = "select count(textId) countAll from text where title like ?";Object[] paramsSearchCountAll = {"%"+search+"%"};if(textList != null) {countAll = tsd.getCountAll(sqlSearchCountAll, paramsSearchCountAll);}totalPage =(int)Math.ceil((double) countAll/pageSize);System.out.println("模糊查询总页数:"+totalPage);}if(categoryId != 0) {//TODO 调用分栏目查询//如果在栏目下查询if(search != null &&!search.equals("")) {String sqlSearchByCategoryId = "select a.textId,a.title,a.userId,a.categoryId,b.replyCount,a.textTime \r\n" + "               from \r\n" + "               (select t.textId,t.title,t.userId,t.textTime,t.categoryId from text t left join user u on t.textId = u.userId) a\r\n" + "               left join  \r\n" + "               (select r.textId, count(r.replyId) replyCount from reply  r group by textId) b\r\n" + "               on \r\n" + "               a.textId = b.textId \r\n" + "               where a.categoryId = ? and a.title like ?\r\n" + "               order by \r\n" + "               a.textId desc \r\n" + "               limit ?,?";Object[] paramsSearchByCategoryId = {categoryId,"%"+search+"%",offset,pageSize};textList = tss.listText(sqlSearchByCategoryId, paramsSearchByCategoryId);//分栏目在查询总条目数String sqlSearchByCategoryIdCountAll = "select count(textId) countAll from text where title like ? and categoryId = ?";Object[] paramsSearchByCategoryIdCountAll = {"%"+search+"%",categoryId};countAll = tsd.getCountAll(sqlSearchByCategoryIdCountAll, paramsSearchByCategoryIdCountAll);totalPage = (int)Math.ceil((double) countAll/pageSize);}else {System.out.println("分栏查询进来了。。。。。。。");String sqlCategory = " select a.textId,a.title,a.userId,a.categoryId,b.replyCount,a.textTime \r\n" + "               from \r\n" + "               (select t.textId,t.title,t.userId,t.textTime,t.categoryId from text t left join user u on t.textId = u.userId) a\r\n" + "               left join  \r\n" + "               (select r.textId, count(r.replyId) replyCount from reply  r group by textId) b\r\n" + "               on \r\n" + "               a.textId = b.textId \r\n" + "               where a.categoryId = ?\r\n" + "               order by \r\n" + "               a.textId desc \r\n" + "               limit ?,?";Object[] paramsCategory = {categoryId,offset,pageSize};textList =  tss.listText(sqlCategory, paramsCategory);//变化总页数String sqlCategoryCountAll = "select count(textId) countAll from text where categoryId = ?";Object[] paramsCategoryCountAll = {categoryId};countAll = tsd.getCountAll(sqlCategoryCountAll, paramsCategoryCountAll);totalPage =(int)Math.ceil((double) countAll/pageSize);}}//其他情况全部调用首页查询if(search == null  && categoryId ==0) {String sql = "select a.textId,a.title,a.userId,b.replyCount,a.textTime from (select t.textId,t.title,t.userId,t.textTime from text t left join user u on t.textId = u.userId) a left join  (select r.textId, count(r.replyId) replyCount from reply  r group by textId) b on a.textId = b.textId "+ "order by a.textId desc limit ?,?";Object[] params = {offset,pageSize};textList =  tss.listText(sql, params);System.out.println("textList大小:"+textList.size());System.out.println(textList);}//当search categoryId 都有值的时候,怎么办??/*  if(categoryId != 0 && search != null &&! search.equals("")) {System.out.println("执行在分栏中搜索的方法。。。。");}*///3,传值及页面跳转System.out.println("实际传过去总条目数:"+countAll);req.setAttribute("textList", textList);req.setAttribute("countAll", countAll);req.setAttribute("pageSize", pageSize);req.setAttribute("totalPage", totalPage);req.setAttribute("pageIndex", pageIndex);//传过去search categoryId便于点击分页的时候,调用不同的方法  否则永远调用textShowreq.setAttribute("search", search);req.setAttribute("categoryId", categoryId);req.getRequestDispatcher("index.jsp").forward(req, resp);}
}   

TextSearchServlet

package com.hmc.controller;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.hmc.pojo.TextShow;
import com.hmc.service.TextShowService;
import com.hmc.service.TextShowServiceImpl;/**
*
*2018年1月7日
*User:Meice
*下午5:10:12
*/
public class TextSearchServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req, resp);}protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException ,IOException {//1.接收参数 search//传递1个参数searchString search = req.getParameter("search");//2.调用方法if(search != null) {if(search.equals("")) {search = "";}TextShowService tss = new TextShowServiceImpl();String sql = " select a.textId,a.title,a.userId,b.replyCount,a.textTime \r\n" + "               from \r\n" + "               (select t.textId,t.title,t.userId,t.textTime from text t left join user u on t.textId = u.userId) a\r\n" + "               left join  \r\n" + "               (select r.textId, count(r.replyId) replyCount from reply  r group by textId) b\r\n" + "               on \r\n" + "               a.textId = b.textId \r\n" + "               where a.title like ?\r\n" + "               order by \r\n" + "               a.textId desc \r\n" + "               limit ?,?";Object[] params = {};List<TextShow> textList =   tss.listText(sql, params);}//3.跳转页面};
}

哈哈,功能看起来不多,细节还是蛮多的。

呵呵呵,如果读者能坚持看到这里,那么我也就不用总结了。后面会专门发表一篇博客,来总结这个小项目。
下期预告:个人中心,再会!

小确幸BBS论坛-2-首页相关推荐

  1. 小确幸BBS论坛-6-优化不止步!

    话说: 各位读者朋友,中午好!春节越来越近,归家心切丫! 前面一系列博客详细介绍了过程,但是没有复盘,这结尾的2篇博客就完成这件事. 这篇博客目标:优化小确幸论坛. 小确幸BBS论坛-1-5实现了最核 ...

  2. 小确幸BBS论坛-1-前期准备

    话说: 各位读者晚上好!终于到了2018!2018年的第一篇博客哈!前面中断了不少篇,并非作者怠惰了,确实感觉"拿不出手",嘿嘿.经过一段时间积累,这次就连续的发表一个系列吧--B ...

  3. 小确幸BBS论坛-3-个人中心

    话说: 各位读者朋友,晚上好!前面介绍了注册登录.首页,本篇介绍个人中心 难度系数:★★☆☆☆ 目录 1.页面展示 2.个人中心pojo 3.个人中心帖子列表.发帖.修改.删除 1.页面展示 user ...

  4. 冬日里的小确幸无非是美味在旁

    你的生活是怎样的呢?每个人可能都会有不同的回答,对待生活的方式也不近相同.一日三餐,对于奔波的人可能仔细地去运作完成. 美食,在很大程度上给予了我们幸福感,也决定了你的生活态度. 冬日里不管是早起的你 ...

  5. 双11:天猫要“软着陆”,商家要“小确幸”

    世事如棋局局新,关关难过关关过.今年的双11,还是有不少变化的. 比如,满减的门槛降低.双11的满减变化,其实可以解读很多信息.2019年以及之前是"满400减50",2020年是 ...

  6. 计算机课堂热身游戏,童年小确幸 儿时电脑课里我们玩不腻的13个小游戏

    原标题:童年小确幸 儿时电脑课里我们玩不腻的13个小游戏 还记得小时候电脑课一到教室就是先开史莱姆之家下载小游戏到电脑裡来玩,因为那时候老师根本不给你网络上网, 但是那时候的小孩都很知足,只要随便一个 ...

  7. 华为盒子显示服务器繁忙,繁忙都市中的“小确幸”

    随着经济和网络的不断发展,现代人的生活被不断挤压,做不完的工作,赶不完的应酬和酒局,在繁忙的都市中似乎永远都慢不下来.走在下班回家的路上,想想自己已经有多久不曾好好读书:有多久没有完整看一部电影:又有 ...

  8. 飞利浦css5530+g评测,影院不开门,给生活多点小确幸,飞利浦CSS5235家庭影院开箱评测...

    原标题:影院不开门,给生活多点小确幸,飞利浦CSS5235家庭影院开箱评测 电影院已经停摆半年了,最后一次买电影票还是春节档,只是被自动退票了.最近的电影要么在电视上看,要么在电脑上看,视觉效果无法改 ...

  9. 小确幸与大抱负:为何自拍类APP成为新宠?

    新春伊始,自拍美图类APP成了香饽饽. 专注于自拍P图的美图,于2017年登陆港股,目前市值达400多亿港元.就在近日,消息称专注于自拍P图的Faceu激萌被今日头条以3亿美金收购.无独有偶,早在今年 ...

  10. 小时候计算机课玩的那个兔子的游戏是什么,童年小确幸 儿时电脑课里我们玩不腻的13个小游戏...

    还记得小时候电脑课一到教室就是先开史莱姆之家下载小游戏到电脑裡来玩,因为那时候老师根本不给你网络上网, 但是那时候的小孩都很知足,只要随便一个小游戏都可以让人玩一个下午. 有时候懒的下载还会直接存在3 ...

最新文章

  1. Java HashMap的put操作(Java1.8)
  2. ubuntu下安装Thinkpad指纹识别系统
  3. 【解决办法】安装Exchange2010时报错 - “UserMailbox 必须强制使用Database”
  4. 创建委托登录模块(用于JBoss EAP 6.1)
  5. C#核心概念--装箱和拆箱(什么是装箱和拆箱)
  6. 对正则表达式又重新学了一遍,笔记方便以后查阅
  7. spring-102-spring全注解快速实现事务
  8. 力扣—— 79/212. 单词搜索
  9. ARM:供给中国 160 亿颗芯片,继续授权华为!
  10. idea调试代码步入用法
  11. 2022新版千月影视双端APP带H5功能开源程序支持当面付和易支付
  12. outlook邮件插入HTML格式内容调试
  13. java实时汇率的接口_基于JAVA的汇率换算接口调用代码实例
  14. Excel中根据输入内容 自动填充时间、自动增加边框、自动添加背景颜色
  15. UE4 打包设置全屏模式和窗口模式方法
  16. UDIMM、RDIMM和LRDIMM
  17. Shader 蔓藤生长动画
  18. 怎么把手机文件导入华为云服务器,华为手机如何上传数据到云服务器
  19. stm32f407zgt6的pdr_on引脚怎么接
  20. ol xyz 加载天地图_Openlayers3 加载百度地图,天地图

热门文章

  1. ojdbc maven
  2. 通过matlab语言来实现对硬币的计数问题
  3. 施乐s2110进入维修模式_施乐进入维修模式步骤
  4. 看漫画学python电子书-看漫画学Python:有趣、有料、好玩、好用(全彩版)
  5. 黑苹果 OC引导 big sur 主题分享
  6. 海康威视摄像头web端开发
  7. pkpm字体库下载_pkpm字体库转到cad
  8. 模糊控制算法在MATLAB/SIMULINK中的应用
  9. SQL server 2008 如何卸载干净
  10. SM4算法 C语言 (从OpenSSL库中分离算法:七)