区块链技术博客
www.b2bchain.cn

新闻管理界面小练习

这篇文章主要介绍了新闻管理界面小练习的讲解,通过具体代码实例进行20996 讲解,并且分析了新闻管理界面小练习的详细步骤与相关技巧,需要的朋友可以参考下https://www.b2bchain.cn/?p=20996

本文实例讲述了2、树莓派设置连接WiFi,开启VNC等等的讲解。分享给大家供大家参考文章查询地址https://www.b2bchain.cn/7039.html。具体如下:

文章目录

  • 新闻管理界面小练习

新闻管理界面小练习

发布日期为系统当前时间,所有的新闻内容要求使用在线编辑器进行编辑
要求:
1.添加新闻:添加新闻时写清楚新闻的标题、作者、内容,默认情况下刚添加的新闻要经过管理员的审核,新闻发布时间为新闻的提交时间
注意:发布新闻的作者就是当前正在登陆的人员。所有管理员发布的新闻可以直接发布,就是管理发布的新闻的lockflag=1.所有的普通用户发布的新闻必须是lockflag=0.
2.修改新闻:将已有的信息进行显示,如果是管理员修改新闻,则可以控制新闻的锁定状态
普通用户用户只能查看到所有的已通过的新闻。普通的用户只能查看新闻以及修改和删除自己的新闻。新闻的内容不能显示的页面上,想要查看新闻的内容,点击新闻的标题跳转的一个单独的页面进行查看。

如果是管理员查看新闻的时候,要显示新闻的编号,新闻的标题,新闻的作者,新闻的发布时间以及操作,在操作中,如果是没有通过的新闻,则在操作中显示通过/删除
如果是通过的新闻,需要判断是否是自己发布的,如果是自己发布的,可以修改可以删除,如果是别人发布的只能删除。

查看新闻的时候要求按照新闻的发布时间降序排序

数据库

t_user1表:

/* Navicat MySQL Data Transfer  Source Server         : localhost_3306 Source Server Version : 50519 Source Host           : localhost:3306 Source Database       : test  Target Server Type    : MYSQL Target Server Version : 50519 File Encoding         : 65001  Date: 2020-11-18 19:00:01 */  SET FOREIGN_KEY_CHECKS=0;  -- ---------------------------- -- Table structure for t_user1 -- ---------------------------- DROP TABLE IF EXISTS `t_user1`; CREATE TABLE `t_user1` (   `userid` varchar(16) NOT NULL,   `password` varchar(16) NOT NULL,   `username` varchar(16) NOT NULL,   `flag` int(2) NOT NULL,   PRIMARY KEY (`userid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;  -- ---------------------------- -- Records of t_user1 -- ---------------------------- INSERT INTO `t_user1` VALUES ('13878978888', '123456', '张三', '1'); INSERT INTO `t_user1` VALUES ('13878978999', '123456', 'admin', '0');  

news表:

/* Navicat MySQL Data Transfer  Source Server         : localhost_3306 Source Server Version : 50519 Source Host           : localhost:3306 Source Database       : test  Target Server Type    : MYSQL Target Server Version : 50519 File Encoding         : 65001  Date: 2020-11-18 19:00:20 */  SET FOREIGN_KEY_CHECKS=0;  -- ---------------------------- -- Table structure for news -- ---------------------------- DROP TABLE IF EXISTS `news`; CREATE TABLE `news` (   `nid` int(3) NOT NULL AUTO_INCREMENT,   `title` varchar(100) NOT NULL,   `author` varchar(16) NOT NULL,   `pubdate` date NOT NULL,   `content` varchar(1000) NOT NULL,   `lockflag` int(2) NOT NULL,   PRIMARY KEY (`nid`) ) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8;  -- ---------------------------- -- Records of news -- ---------------------------- INSERT INTO `news` VALUES ('1', 'title1', 'admin', '2020-11-16', 'hello1', '0'); INSERT INTO `news` VALUES ('2', 'title2', 'admin', '2020-11-16', 'hello2', '0'); INSERT INTO `news` VALUES ('3', 'title3', '张三', '2020-11-16', 'hello3', '0'); INSERT INTO `news` VALUES ('4', 'title4', 'admin', '2020-11-16', 'hello4', '0'); INSERT INTO `news` VALUES ('5', 'title5', '张三', '2020-11-16', 'hello5', '0'); INSERT INTO `news` VALUES ('6', 'title6', 'admin', '2020-11-16', 'hello6', '0'); INSERT INTO `news` VALUES ('8', 'title8', '张三', '2020-11-16', 'hello8', '0'); INSERT INTO `news` VALUES ('9', 'title9', '张三', '2020-11-16', 'hello1', '0'); INSERT INTO `news` VALUES ('10', 'title10', 'admin', '2020-11-16', 'hello1', '0'); INSERT INTO `news` VALUES ('11', '你好', 'admin', '2020-11-16', 'hello', '0'); INSERT INTO `news` VALUES ('12', '你好1', '张三', '2020-11-16', 'nihao1', '0'); INSERT INTO `news` VALUES ('13', '11', 'admin', '2020-11-17', 'gg', '0'); INSERT INTO `news` VALUES ('14', '112', 'admin', '2020-11-17', 'qwertghj', '0'); INSERT INTO `news` VALUES ('15', 'hello12', '张三', '2020-11-18', 'hello13', '0');  

基于EL表达式和JSTL

addOrUpdate.jsp:

<%@page import="com.oracle.vo.News"%> <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core"%> <% 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="${requestScope.basePath}">          <title>My JSP 'add.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"> 	--> 	<script type="text/javascript"> 		function $(id){ 			return document.getElementById(id); 		} 		window.onload = function(){ 			var title = $("title"); 			var content = $("content"); 			var sp1 = $("sp1"); 			var btn_ok=$("btn_ok"); 			var btn_cancel = $("btn_cancel"); 			//对提交按钮设置点击事件 			if(btn_ok!=null&&btn_ok!=undefined){ 				btn_ok.onclick = function(){ 				//定义一个变量代表是否提交 				var flag=true; 				//获取title和content的value 				var titleValue = title.value; 				var contentValue = content.value; 				//判断值是否为空 				if(titleValue==null||titleValue==""){ 					sp1.innerHTML="<font color='red'>title不能为空</font>" 					flag=false; 					return; 				}else{ 					sp1.innerHTML="" 					flag=true; 				} 				if(contentValue==null||contentValue==""){ 					sp1.innerHTML="<font color='red'>content不能为空</font>" 					flag=false; 					return; 				}else{ 					sp1.innerHTML="" 					flag=true; 				} 				//判断是否能够提交 				if(flag==true){ 					var f1 = $("f1"); 					f1.submit(); 				} 			} 			} 			 			//对取消按钮设置点击事件 			btn_cancel.onclick = function(){ 				var f2 = $("f2"); 				f2.submit(); 			} 			 		} 	</script>   </head>         <body>    <c:if test="${requestScope.operator==null }">    		<c:redirect url="selectServlet"/>    </c:if>    <c:if test="${requestScope.operator!='add'&&requestScope.news==null }">    		<c:redirect url="selectServlet"/>    </c:if>    <form action="operator" method="POST" id="f1"> 	   <c:if test="${requestScope.operator=='update'}"> 	   		<input type="hidden" name="author" value="${sessionScope.username}"/> 			<input type="hidden" name="lockflag" value="${sessionScope.userflag}"/> 			<input type="hidden" name="operator" value="updateNews"/> 			<input type="hidden" name="nid" value="${requestScope.news.nid}"/> 			title:<input type="text" name="title" id="title" value="${requestScope.news.title}"/><span id="sp1"></span><br/> 			content:<textarea rows="10" cols="30" id="content" name="content">${requestScope.news.content}</textarea><br/> 			<input type="button" value="更新" id="btn_ok"/><input type="button" value="取消" id="btn_cancel"/> 	   </c:if> 	   <c:if test="${requestScope.operator=='add' }"> 	   		<input type="hidden" name="author" value="${sessionScope.username}"/> 			<input type="hidden" name="lockflag" value="${sessionScope.userflag}"/> 			<input type="hidden" name="operator" value="addNews"/> 			<input type="hidden" name="nid" value="${requestScope.news.nid}"/> 			title:<input type="text" name="title" id="title" value="${requestScope.news.title}"/><span id="sp1"></span><br/> 			content:<textarea rows="10" cols="30" id="content" name="content">${requestScope.news.content}</textarea><br/> 			<input type="button" value="更新" id="btn_ok"/><input type="button" value="取消" id="btn_cancel"/> 			 	   </c:if> 	   <c:if test="${requestScope.operator=='select'}"> 	   		title:<input type="text" name="title" id="title" value="${requestScope.news.title}" readonly="readonly"/><span id="sp1"></span><br/> 	   		content:<textarea rows="10" cols="30" id="content" name="content" readonly="readonly">${requestScope.news.content}</textarea><br/> 	   		<input type="button" value="返回" id="btn_cancel"/> 	   </c:if>    </form>    <form action="selectServlet" method="POST" id="f2">    </form>   </body> </html>  

index.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core"%> <% 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="${requestScope.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"> 	--> 	<script> 		function $(id){ 			return document.getElementById(id); 		} 		//当页面加载完毕 		window.onload = function(){ 			//获取页面的组件 			var userid = $("userid"); 			var password = $("password"); 			var sp1 = $("sp1"); 			var sp2 = $("sp2"); 			var btn_login = $("btn_login"); 			//对按钮设置点击事件 			btn_login.onclick = function(){ 				//定义一个变量代表表单是否可以提交 				var flag = true; 				//获取userid的value 				var useridValue = userid.value; 				//获取密码的value 				var passwordValue = password.value; 				//判断userid是否为空 				if(useridValue==null||useridValue==""){ 					flag=false; 					sp1.innerHTML = "<font color='red'>userid不能为空</font>"; 					return; 				}else{ 					flag=true; 					sp1.innerHTML = ""; 				} 				//判断password是否为空 				if(passwordValue==null||passwordValue==""){ 					flag=false; 					sp2.innerHTML = "<font color='red'>password不能为空</font>"; 					return; 				}else{ 					flag=true; 					sp2.innerHTML = ""; 				} 				//定义userid的正则表达式 				var useridReg = /(^1[3-9]d{9}$)|(^w[a-zA-Z0-9]{5,7}@[0-9a-zA-Z]{2,7}(.com|.cn|.net)$)/; 				//判断userid是否满足格式 				if(useridValue.match(useridReg)==null){ 					flag=false; 					sp1.innerHTML= "<font color='red'>userid的格式不正确</font>"; 					return; 				}else{ 					flag=true; 					sp1.innerHTML = ""; 				} 				 				//定义password的正则表达式 				var passwordReg = /d{6,16}/; 				//判断userid是否满足格式 				if(passwordValue.match(passwordReg)==null){ 					flag=false; 					sp2.innerHTML= "<font color='red'>password的格式不正确</font>"; 					return; 				}else{ 					flag=true; 					sp2.innerHTML = ""; 				} 				//判断是否能提交 				if(flag==true){ 					document.forms[0].submit(); 				} 			} 		} 	</script>   </head>      <body> 	 <%   		//获取错误信息的内容   		//String errorInfo = (String)request.getAttribute("errorInfo");   		/*   			EL表达式可以判定是否为空   		*/   		//判断得到的错误信息是否为空,比如我们第一次访问这个页面就可能是空   		//if(errorInfo==null){   		//	errorInfo="";   		//}    %>       <form action="check" method="POST">    	userid:<input type="text" name="userid" id="userid"/><span id="sp1">${requestScope.errorInfo}</span><br/>    	password:<input type="password" name="password" id="password"/><span id="sp2"></span><br/>    	<input type="button" value="登录" id="btn_login"/><input type="reset" value="重置"/>    </form>   </body> </html>  

showNews.jsp:

<%@page import="java.text.SimpleDateFormat"%> <%@page import="com.oracle.vo.News"%> <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core"%> <% 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="${requestScope.basePath }">          <title>My JSP 'showNews.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"> 	--> 	<script> 		window.onload = function(){ 			var deleteas = document.getElementsByName("deletea"); 			for(var i=0;i<deleteas.length;i++){ 				var deletea = deleteas[i]; 				 				deletea.onclick = function(){ 					 					var deleteTitle = this.getAttribute("title"); 					var flag = confirm("确定要删除"+deleteTitle+"吗??"); 					return flag; 				} 			} 			 		} 	</script> 	 	   </head>      <body>  	      <table border="1" align="center">      	<tr>      		<td colspan="5"><a href="operator?operator=add">添加新闻</a></td>      	</tr>      	<tr>      		<th>新闻的编号</th>      		<th>新闻的标题</th>      		<th>新闻的作者</th>      		<th>新闻的发布时间</th>      		<th>操作</th>      	</tr>      	<c:if test="${requestScope.news==null}">      		<tr>      			<td colspan="5">暂无数据</td>      		</tr>      	</c:if>      	<c:if test="${requestScope.news!=null}">      		<c:forEach items="${requestScope.news }" var="n">      			<tr> 					<td>${n.nid }</td> 					<td><a href="operator?operator=select&nid=${n.nid }">${n.title}</a></td> 					<td>${n.author }</td> 					<td>${n.pubdate }</td>      			<c:if test="${sessionScope.userflag==0 }">      				<c:if test="${n.getLockflag()==0}">      					<c:if test="${n.author==sessionScope.username }">      						<td><a href="operator?operator=update&nid=${n.nid }">修改</a>/<a href="operator?operator=delete&nid=${n.nid }" name="deletea" title="${n.title }">删除</a></td>      					</c:if>      					<c:if test="${n.author!=sessionScope.username }">      						<td><a href="operator?operator=delete&nid=${n.nid }" name="deletea" title="${n.title }">删除</a></td>      					</c:if>      				</c:if>      				<c:if test="${n.getLockflag()!=0}">      					<c:if test="${n.author==sessionScope.username }">      						<td><a href="operator?operator=update&nid=${n.nid }">修改</a>/<a href="operator?operator=delete&nid=${n.nid }" name="deletea" title="${n.title }">删除</a></td>      					</c:if>      					<c:if test="${n.author!=sessionScope.username }">      						<td><a href="operator?operator=pass&nid=${n.nid }">通过</a>/<a href="operator?operator=delete&nid=${n.nid }" name="deletea" title="${n.title }">删除</a></td>      					</c:if>      				</c:if>      			</c:if>      			<c:if test="${sessionScope.userflag!=0 }">      				<c:if test="${n.author==sessionScope.username }">      					<td><a href="operator?operator=update&nid=${n.nid }">修改</a>/<a href="operator?operator=delete&nid=${n.nid }" name="deletea" title="${n.title }">删除</a></td>      				</c:if>      				<c:if test="${n.author!=sessionScope.username }">      					<td>-</td>      				</c:if>      			</c:if>      			</tr>      		</c:forEach>      		<tr align="center">      			<td colspan="5">      				<a href="selectServlet?pn=1">首页</a>      				<a href="selectServlet?pn=${requestScope.pageNum-1}">上一页</a>      				<a href="selectServlet?pn=${requestScope.pageNum+1}">下一页</a>      				<a href="selectServlet?pn=${requestScope.totalPage}">尾页</a>      			</td>      		</tr>      	</c:if>     </table>   </body> </html>  

Dao类:

package com.oracle.dao;  import java.util.List;  public interface BaseDao<T> {  	public abstract void insert(T t); 	public abstract void update(T t); 	public abstract void delete(T t); 	public abstract T selectById(T t); 	public abstract List<T> selectAll(); }  
package com.oracle.dao;  import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.List;  import com.oracle.tools.DBTools; import com.oracle.vo.News;  public class NewsDao implements BaseDao<News> {  	@Override 	public void insert(News t) { 		String sql = "insert into news(title,author,pubdate,content,lockflag) values(?,?,?,?,?)"; 		DBTools.executeUpdate(sql, t.getTitle(),t.getAuthor(),t.getPubdate(),t.getContent(),t.getLockflag()); 	}  	@Override 	public void update(News t) { 		String sql = "update news set title=?,author=?,pubdate=?,content=?,lockflag=? where nid=?"; 		DBTools.executeUpdate(sql, t.getTitle(),t.getAuthor(),t.getPubdate(),t.getContent(),t.getLockflag(),t.getNid()); 	}  	@Override 	public void delete(News t) { 		String sql = "delete from news where nid=?"; 		DBTools.executeUpdate(sql, t.getNid()); 	}  	@Override 	public News selectById(News t) { 		News n = null; 		String sql = "select * from news where nid=?"; 		List<Object[]> objs = DBTools.executeQuery(sql, t.getNid()); 		if(objs!=null&&objs.size()>0){ 			Object[] obj = objs.get(0); 			int nid = (Integer)obj[0]; 			String title = (String)obj[1]; 			String author = (String)obj[2]; 			 			Date pubdate = (Date)obj[3]; 			String content = (String)obj[4]; 			int lockflag = (Integer)obj[5]; 			n = new News(nid, title, author, pubdate, content, lockflag); 		} 		return n; 	}  	@Override 	public List<News> selectAll() { 		// TODO Auto-generated method stub 		return null; 	} 	 	 	 	public List<News> selectNewsByPageAdmin(int flag,int pageNum,int num){ 		List<News> news = null; 		String sql = "select * from news limit ?,?"; 		if(flag==1){//flag如果为1则代表是普通用户,普通用户只能查询lockflag=0的新闻 			sql = "select * from news where lockflag=0 limit ?,?"; 			 		} 		List<Object[]> objs = DBTools.executeQuery(sql, (pageNum-1)*num,num); 		if(objs!=null&&objs.size()>0){ 			news = new ArrayList<News>(); 			for(int i=0;i<objs.size();i++){ 				Object[] obj = objs.get(i); 				int nid = (Integer)obj[0]; 				String title = (String)obj[1]; 				String author = (String)obj[2]; 				Date pubdate = (Date)obj[3]; 				String content = (String)obj[4]; 				int lockflag = (Integer)obj[5]; 				News n = new News(nid, title, author, pubdate, content, lockflag); 				news.add(n); 			} 			 		} 		return news; 	} 	public int getCountAdmin(int flag){ 		int count=0; 		String sql = "select count(*) from news "; 		if(flag==1){//flag如果为1则代表是普通用户,普通用户只能查询lockflag=0的新闻 			sql = "select count(*) from news where lockflag=0 "; 		} 		List<Object[]> objs = DBTools.executeQuery(sql, null); 		if(objs!=null&&objs.size()>0){ 			Object[] obj = objs.get(0); 			count = ((Long)obj[0]).intValue(); 				 		} 		return count; 		 	}  }  
package com.oracle.dao;  import java.util.List;  import com.oracle.tools.DBTools; import com.oracle.vo.User;  public class UserDao implements BaseDao<User>{  	@Override 	public void insert(User t) { 		 	}  	@Override 	public void update(User t) { 		// TODO Auto-generated method stub 		 	}  	@Override 	public void delete(User t) { 		// TODO Auto-generated method stub 		 	}  	@Override 	public User selectById(User t) { 		String sql = "select * from t_user1 where userid=?"; 		User user = null; 		List<Object[]> objs = DBTools.executeQuery(sql, t.getUserid()); 		if(objs!=null&&objs.size()>0){ 			Object[] obj = objs.get(0); 			String userid = (String)obj[0]; 			String password = (String)obj[1]; 			String username = (String)obj[2]; 			int flag = (Integer)obj[3]; 			user = new User(userid, password, username, flag); 		} 		return user; 	}  	@Override 	public List<User> selectAll() { 		// TODO Auto-generated method stub 		return null; 	}  }  

servlet类:

package com.oracle.servlet;  import java.io.IOException; import java.io.PrintWriter;  import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;  import com.oracle.dao.UserDao; import com.oracle.vo.User;  public class CheckServlet extends HttpServlet {  	/** 		 * The doGet method of the servlet. <br> 		 * 		 * This method is called when a form has its tag value method equals to get. 		 *  		 * @param request the request send by the client to the server 		 * @param response the response send by the server to the client 		 * @throws ServletException if an error occurred 		 * @throws IOException if an error occurred 		 */ 	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  		doPost(request, response); 	}  	/** 		 * The doPost method of the servlet. <br> 		 * 		 * This method is called when a form has its tag value method equals to post. 		 *  		 * @param request the request send by the client to the server 		 * @param response the response send by the server to the client 		 * @throws ServletException if an error occurred 		 * @throws IOException if an error occurred 		 */ 	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 		//获取提交的请求参数 		String userid = request.getParameter("userid"); 		String password = request.getParameter("password"); 		//判断请求参数是否为空 		if(userid==null||userid.trim().equals("")||password==null||password.trim().equals("")){ 			request.setAttribute("errorInfo", "请登录"); 			request.getRequestDispatcher("index.jsp").forward(request, response); 			return; 		}else{ 			//创建UserDao对象 			UserDao userDao = new UserDao(); 			//创建User对象 			User user = new User(); 			//对user对象设置userid为用户输入的userid 			user.setUserid(userid); 			//查询数据库是否存在此用户 			user = userDao.selectById(user); 			//判断如果查询的结果为空则证明用户不存在 			if(user==null){ 				request.setAttribute("errorInfo", "userid不存在"); 				request.getRequestDispatcher("index.jsp").forward(request, response); 				return; 			}else{ 				//判断用户输入的密码与查询到的用户的密码是否一致 				if(password.equals(user.getPassword())){ 					//获取HttpSession对象 					HttpSession session = request.getSession(); 					//向session方位存储用户名和用户的角色 					session.setAttribute("username", user.getUsername()); 					session.setAttribute("userflag", user.getFlag()); 					//将请求跳转到查询新闻的Servlet 					response.sendRedirect("selectServlet"); 				}else{ 					request.setAttribute("errorInfo", "密码不正确"); 					request.getRequestDispatcher("index.jsp").forward(request, response); 					return; 				} 				 			} 			 		} 		 	}  }  
package com.oracle.servlet;  import java.io.IOException; import java.io.PrintWriter; import java.util.Date;  import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;  import com.oracle.dao.NewsDao; import com.oracle.vo.News;  public class OperatorServlet extends HttpServlet {  	/** 		 * The doGet method of the servlet. <br> 		 * 		 * This method is called when a form has its tag value method equals to get. 		 *  		 * @param request the request send by the client to the server 		 * @param response the response send by the server to the client 		 * @throws ServletException if an error occurred 		 * @throws IOException if an error occurred 		 */ 	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  		doPost(request, response); 		 	}  	/** 		 * The doPost method of the servlet. <br> 		 * 		 * This method is called when a form has its tag value method equals to post. 		 *  		 * @param request the request send by the client to the server 		 * @param response the response send by the server to the client 		 * @throws ServletException if an error occurred 		 * @throws IOException if an error occurred 		 */ 	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  		//接收请求参数 		String operator = request.getParameter("operator"); 		//创建NewsDao对象 		NewsDao newsDao = new NewsDao(); 		//判断请求参数是否为空 		if(operator==null||operator.trim().equals("")){ 			//如果请求参数为空则跳转会查询的Servlet重新查询重新显示 			response.sendRedirect("selectServlet"); 			return; 		}else{ 			//如果operator不为空 			//判断operator是否是添加 			if(operator.equals("add")){ 				//如果是operator是添加,则跳转到添加页面 				request.setAttribute("operator", operator); 				request.getRequestDispatcher("addOrUpdate.jsp").forward(request, response); 				return; 			}else if(operator.equals("update")){ 				//如果operator是修改 				//获取传递的nid 				String id = request.getParameter("nid"); 				System.out.println("update:"+id); 				//判断nid是否为空 				if(id==null||!id.matches("\d+")){ 					//如果id为空或者id不满足需要的格式,跳转到查询页面重新查询 					response.sendRedirect("selectServlet"); 					return; 				} 				//将参数id转化为nid 				int nid = Integer.parseInt(id); 				//创建新闻对象 				News news = new News(); 				//设置nid 				news.setNid(nid); 				//查询新闻 				news = newsDao.selectById(news); 				//判断查询到的新闻是否存在 				if(news==null){ 					//如果新闻不存在,跳转到查询页面重新查询 					response.sendRedirect("selectServlet"); 					return; 				} 				//向request中添加参数 				request.setAttribute("operator", operator); 				request.setAttribute("news", news); 				request.getRequestDispatcher("addOrUpdate.jsp").forward(request, response); 				return; 				 			}else if(operator.equals("addNews")){ 				//接收请求参数 				String title = request.getParameter("title"); 				String author = request.getParameter("author"); 				String lf = request.getParameter("lockflag"); 				String content = request.getParameter("content"); 				News n = new News(0, title, author, new Date(), content, Integer.parseInt(lf)); 				newsDao.insert(n); 				response.sendRedirect("selectServlet"); 				return; 			}else if(operator.equals("updateNews")){ 				//接收请求参数 				String id = request.getParameter("nid"); 				String title = request.getParameter("title"); 				String author = request.getParameter("author"); 				String lf = request.getParameter("lockflag"); 				String content = request.getParameter("content"); 				News n = new News(Integer.parseInt(id), title, author, new Date(), content, Integer.parseInt(lf)); 				newsDao.update(n); 				response.sendRedirect("selectServlet"); 				return; 				 			}else if(operator.equals("select")){ 				//获取传递的nid 				String id = request.getParameter("nid"); 				//判断nid是否为空 				if(id==null||!id.matches("\d+")){ 					//如果id为空或者id不满足需要的格式,跳转到查询页面重新查询 					response.sendRedirect("selectServlet"); 					return; 				} 				//将参数id转化为nid 				int nid = Integer.parseInt(id); 				//创建新闻对象 				News news = new News(); 				//设置nid 				news.setNid(nid); 				//查询新闻 				news = newsDao.selectById(news); 				//判断查询到的新闻是否存在 				if(news==null){ 					//如果新闻不存在,跳转到查询页面重新查询 					response.sendRedirect("selectServlet"); 					return; 				} 				//向request中添加参数 				request.setAttribute("operator", operator); 				request.setAttribute("news", news); 				request.getRequestDispatcher("addOrUpdate.jsp").forward(request, response); 				return; 				 				 				 			}else if(operator.equals("delete")){ 				//获取传递的nid 				String id = request.getParameter("nid"); 				//判断nid是否为空 				if(id==null||!id.matches("\d+")){ 					//如果id为空或者id不满足需要的格式,跳转到查询页面重新查询 					response.sendRedirect("selectServlet"); 					return; 				} 				//将参数id转化为nid 				int nid = Integer.parseInt(id); 				//创建新闻对象 				News news = new News(); 				//设置nid 				news.setNid(nid); 				newsDao.delete(news); 				response.sendRedirect("selectServlet"); 				return; 				 			}else if(operator.equals("pass")){ 				//获取传递的nid 				String id = request.getParameter("nid"); 				//判断nid是否为空 				if(id==null||!id.matches("\d+")){ 					//如果id为空或者id不满足需要的格式,跳转到查询页面重新查询 					response.sendRedirect("selectServlet"); 					return; 				} 				//将参数id转化为nid 				int nid = Integer.parseInt(id); 				//创建新闻对象 				News news = new News(); 				//设置nid 				news.setNid(nid); 				news = newsDao.selectById(news); 				if(news==null){ 					response.sendRedirect("selectServlet"); 					return; 				} 				news.setLockflag(0); 				newsDao.update(news); 				response.sendRedirect("selectServlet"); 				return; 			} 		} 	}  }  
package com.oracle.servlet;  import java.io.IOException; import java.io.PrintWriter; import java.util.List;  import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;  import com.oracle.dao.NewsDao; import com.oracle.vo.News;  public class SelectServlet extends HttpServlet {  	/** 		 * The doGet method of the servlet. <br> 		 * 		 * This method is called when a form has its tag value method equals to get. 		 *  		 * @param request the request send by the client to the server 		 * @param response the response send by the server to the client 		 * @throws ServletException if an error occurred 		 * @throws IOException if an error occurred 		 */ 	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  		doPost(request, response); 	}  	/** 		 * The doPost method of the servlet. <br> 		 * 		 * This method is called when a form has its tag value method equals to post. 		 *  		 * @param request the request send by the client to the server 		 * @param response the response send by the server to the client 		 * @throws ServletException if an error occurred 		 * @throws IOException if an error occurred 		 */ 	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 		HttpSession session = request.getSession(); 		//获取用户的身份 		int userflag = (Integer)session.getAttribute("userflag"); 		//接收请求参数 		String pn = request.getParameter("pn"); 		if(pn==null||pn.trim().equals("")){ 			pn="1"; 		}else if(!pn.matches("\d+")){ 			pn="1"; 		} 		//定义一个变量代表当前页数 		int pageNum = Integer.parseInt(pn); 		//定义一个变量代表每一页查询的数量 		int num=5; 		//定义NewsDao对象 		NewsDao newsDao = new NewsDao(); 		//定义一个变量代表查询到的总数量 		int count = newsDao.getCountAdmin(userflag); 		//定义一个变量代表总页数 		int totalPage = 1; 		//判断总数量对num取值是否能除尽 		if(count%num==0){ 			totalPage=count/num; 		}else{ 			totalPage=(count/num)+1; 		} 		//判断总页数是否小于0 		if(totalPage<1){ 			totalPage=1; 		} 		//判断当前也是是否小于1或者大于总页数 		if(pageNum<1){ 			pageNum=1; 		}else if(pageNum>totalPage){ 			pageNum=totalPage; 		} 		//查询新闻 		List<News> news = newsDao.selectNewsByPageAdmin(userflag,pageNum, num); 		//将数据存储到request属性范围 		request.setAttribute("news", news); 		request.setAttribute("pageNum", pageNum); 		request.setAttribute("totalPage", totalPage); 		request.getRequestDispatcher("showNews.jsp").forward(request, response); 	}  }  

DBTools类:

package com.oracle.tools;  import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List;  public class DBTools {  	static{ 		try { 			Class.forName("com.mysql.jdbc.Driver"); 		} catch (ClassNotFoundException e) { 			// TODO Auto-generated catch block 			e.printStackTrace(); 		} 	} 	private static Connection conn = null; 	private static final String URL="jdbc:mysql://localhost:3306/test"; 	private static final String USER="root"; 	private static final String PASSWORD="root"; 	private static PreparedStatement pstat = null; 	private static ResultSet rs = null; 	public static Connection getConn(){ 		if(conn==null){ 			try { 				conn = DriverManager.getConnection(URL, USER, PASSWORD); 				conn.setAutoCommit(false); 			} catch (SQLException e) { 				// TODO Auto-generated catch block 				e.printStackTrace(); 			} 		} 		return conn; 	} 	public static void executeUpdate(String sql,Object...objs){ 		conn = getConn(); 		try { 			pstat = conn.prepareStatement(sql); 			if(objs!=null&&objs.length>0){ 				for(int i=0;i<objs.length;i++){ 					pstat.setObject(i+1, objs[i]); 				} 			} 			pstat.execute(); 			commit(); 		} catch (SQLException e) { 			// TODO Auto-generated catch block 			e.printStackTrace(); 			rollback(); 		} 		 		 	} 	 	public static List<Object[]> executeQuery(String sql,Object...objs){ 		List<Object[]> list = new ArrayList<Object[]>(); 		conn = getConn(); 		try { 			pstat = conn.prepareStatement(sql); 			if(objs!=null&&objs.length>0){ 				for(int i=0;i<objs.length;i++){ 					pstat.setObject(i+1, objs[i]); 				} 			} 			rs = pstat.executeQuery(); 			while(rs.next()){ 				Object[] obj = new Object[rs.getMetaData().getColumnCount()]; 				for(int i=0;i<obj.length;i++){ 					obj[i] = rs.getObject(i+1); 				} 				list.add(obj); 				 			} 		} catch (SQLException e) { 			// TODO Auto-generated catch block 			e.printStackTrace(); 			 		} 		return list; 	} 	public static void commit(){ 		if(conn!=null){ 			try { 				conn.commit(); 				close(); 			} catch (SQLException e) { 				// TODO Auto-generated catch block 				e.printStackTrace(); 			} 		} 	} 	public static void rollback(){ 		if(conn!=null){ 			try { 				conn.rollback(); 				close(); 			} catch (SQLException e) { 				// TODO Auto-generated catch block 				e.printStackTrace(); 			} 			 		} 	} 	 	public static void close(){ 		if(rs!=null){ 			try { 				rs.close(); 				rs=null; 			} catch (SQLException e) { 				// TODO Auto-generated catch block 				e.printStackTrace(); 			} 		} 		if(pstat!=null){ 			try { 				pstat.close(); 				pstat=null; 			} catch (SQLException e) { 				// TODO Auto-generated catch block 				e.printStackTrace(); 			} 		} 		if(conn!=null){ 			try { 				conn.close(); 				conn=null; 			} catch (SQLException e) { 				// TODO Auto-generated catch block 				e.printStackTrace(); 			} 		} 	} }  

VO实体类:

package com.oracle.vo;  import java.util.Date;  public class News {  	private int nid; 	private String title; 	private String author; 	private Date pubdate; 	private String content; 	private int lockflag; 	public News(){} 	 	public News(int nid, String title, String author, Date pubdate, String content, int lockflag) { 		super(); 		this.nid = nid; 		this.title = title; 		this.author = author; 		this.pubdate = pubdate; 		this.content = content; 		this.lockflag = lockflag; 	}  	public int getNid() { 		return nid; 	} 	public void setNid(int nid) { 		this.nid = nid; 	} 	public String getTitle() { 		return title; 	} 	public void setTitle(String title) { 		this.title = title; 	} 	public String getAuthor() { 		return author; 	} 	public void setAuthor(String author) { 		this.author = author; 	} 	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 int getLockflag() { 		return lockflag; 	} 	public void setLockflag(int lockflag) { 		this.lockflag = lockflag; 	} 	@Override 	public String toString() { 		return "News [nid=" + nid + ", title=" + title + ", author=" + author + ", pubdate=" + pubdate + ", content=" 				+ content + ", lockflag=" + lockflag + "]"; 	} 	 }  
package com.oracle.vo;  public class User {  	private String userid; 	private String password; 	private String username; 	private int flag; 	public User(){} 	public User(String userid,String password,String username,int flag){ 		this.setPassword(password); 		this.setUserid(userid); 		this.setUsername(username); 		this.setFlag(flag); 	} 	public String getUserid() { 		return userid; 	} 	public void setUserid(String userid) { 		this.userid = userid; 	} 	public String getPassword() { 		return password; 	} 	public void setPassword(String password) { 		this.password = password; 	} 	public String getUsername() { 		return username; 	} 	public void setUsername(String username) { 		this.username = username; 	} 	public int getFlag() { 		return flag; 	} 	public void setFlag(int flag) { 		this.flag = flag; 	} 	@Override 	public String toString() { 		return "User [userid=" + userid + ", password=" + password + ", username=" + username + ", flag=" + flag + "]"; 	} 	   }  

过滤器:

package com.oralce.filter;  import java.io.IOException;  import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse;  public class EncodingFilter implements Filter{  	private String encode = null; 	@Override 	public void destroy() { 		encode=null; 	}  	@Override 	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) 			throws IOException, ServletException { 		arg0.setCharacterEncoding(encode); 		arg1.setCharacterEncoding(encode); 		arg2.doFilter(arg0, arg1); 		 	}  	@Override 	public void init(FilterConfig arg0) throws ServletException { 		encode = arg0.getInitParameter("encode"); 		 	}  }  
package com.oralce.filter;  import java.io.IOException;  import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;  public class LoginFilter implements Filter{  	@Override 	public void destroy() { 		// TODO Auto-generated method stub 		 	}  	@Override 	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) 			throws IOException, ServletException { 		HttpServletRequest request = (HttpServletRequest)arg0; 		HttpServletResponse response = (HttpServletResponse)arg1; 		HttpSession session = request.getSession(); 		String username = (String)session.getAttribute("username"); 		if(username==null||username.trim().equals("")){ 			request.setAttribute("errorInfo", "请登录"); 			request.getRequestDispatcher("index.jsp").forward(request, response); 			return; 		}else{ 			arg2.doFilter(request, response); 		} 		 	}  	@Override 	public void init(FilterConfig arg0) throws ServletException { 		// TODO Auto-generated method stub 		 	}  }  

tion {
encode = arg0.getInitParameter(“encode”);

} 

}

 ```java package com.oralce.filter;  import java.io.IOException;  import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;  public class LoginFilter implements Filter{  	@Override 	public void destroy() { 		// TODO Auto-generated method stub 		 	}  	@Override 	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) 			throws IOException, ServletException { 		HttpServletRequest request = (HttpServletRequest)arg0; 		HttpServletResponse response = (HttpServletResponse)arg1; 		HttpSession session = request.getSession(); 		String username = (String)session.getAttribute("username"); 		if(username==null||username.trim().equals("")){ 			request.setAttribute("errorInfo", "请登录"); 			request.getRequestDispatcher("index.jsp").forward(request, response); 			return; 		}else{ 			arg2.doFilter(request, response); 		} 		 	}  	@Override 	public void init(FilterConfig arg0) throws ServletException { 		// TODO Auto-generated method stub 		 	}  }  

新闻管理界面小练习

本文转自互联网,侵权联系删除新闻管理界面小练习

赞(0) 打赏
部分文章转自网络,侵权联系删除b2bchain区块链学习技术社区 » 新闻管理界面小练习
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

b2b链

联系我们联系我们