这个周学习了利用JDBC访问数据库,经过上个学期的实训,对一块并不陌生,这里有很多任务,现在就开始啦~
练习1、创建新闻系统数据库
(1)用户表结构及记录
(2)栏目表结构及记录
(3)评论表结构及记录
(4)新闻表结构及记录
练习2、实现管理员登录验证
管理员登录页面和用户名、密码文本框使用了课堂上的代码
使用JavaScript进行表单非空验证
非空验证效果如下
业务处理页面
获取登录页面表单数据
访问数据库查询用户名和密码是否正确
根据查询结果跳转到成功或失败页面
完成
练习3、显示新闻列表
需求说明:
管理员登录后,显示新闻列表
使用集合保存新闻
do_login代码
创建News实体类
创建NewsDao和NewsDaoImpl
public class NewsDaoImpl implements NewsDao {
@Override
public int insert(News news) {
//定义插入记录数
int count = 0;
// 获得数据库连接
Connection conn = ConnectionManager.getConnection();
// 定义SQL字符串
String strSQL = "INSERT INTO news (ntid,ntitle,nauthor,ncontent) VALUES (?,?,?,?)";
try {
// 创建预备语句对象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 设置占位符的值
pstmt.setInt(1,news.getNtid() );
pstmt.setString(2,news.getNtitle());
pstmt.setString(3,news.getNauthor());
pstmt.setString(4,news.getNcontent());
// 执行更新操作,插入新录
count = pstmt.executeUpdate();
// 关闭预备语句对象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionManager.closeConnection(conn);
}
// 返回插入记录数
return count;
}
@Override
public List<News> findAll() {
// 声明类别列表
List<News> newss = new ArrayList<News>();
// 获取数据库连接对象
Connection conn = ConnectionManager.getConnection();
// 定义SQL字符串
String strSQL = "SELECT * FROM news";
try {
// 创建语句对象
Statement stmt = conn.createStatement();
// 执行SQL,返回结果集
ResultSet rs = stmt.executeQuery(strSQL);
// 遍历结果集
while (rs.next()) {
// 创建类别实体
News news = new News();
// 设置实体属性
news.setNtid(rs.getInt("ntid"));
news.setNtitle(rs.getString("ntitle"));
news.setNauthor(rs.getString("nauthor"));
news.setNcontent(rs.getString("ncontent"));
// 将实体添加到类别列表
newss.add(news);
}
// 关闭结果集
rs.close();
// 关闭语句对象
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭数据库连接
ConnectionManager.closeConnection(conn);
}
// 返回类别列表
return newss;
}
}
创建NewsServlet类
package net.hw.servlet;
import net.hw.bean.News;
import net.hw.dao.impl.NewsDaoImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
@WebServlet("/news")
public class NewsServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
super.doPost(request, response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 创建主题服务对象
NewsDaoImpl newsDao = new NewsDaoImpl();
// 获取全部新闻主题
List<News> newss = newsDao.findAll();
// 获取session对象
HttpSession session = request.getSession();
// 把商品类别列表以属性的方式保存到session里
session.setAttribute("news", newss);
// 重定向到显示新闻主题页面(showNews.jsp)
response.sendRedirect(request.getContextPath() + "/showNews.jsp");
// 在服务器控制台输出测试信息
for (News news:newss) {
System.out.println(news);
}
}
}
数据库中的user表,admin为管理员
编写showNews.jsp
<%@ page import="net.hw.bean.User" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>新闻列表</title>
</head>
<body>
<%
User user = (User) session.getAttribute("LOGINED_USER");
if (user == null) {
// 在session里创建errMsg属性
session.setAttribute("errMsg", "要访问新闻列表页面,请先登录");
// 采用重定向,跳转到登录页面
response.sendRedirect("login.jsp");
} else if (!session.getAttribute("username").equals("admin")) {
session.setAttribute("Msg", "您不是管理员无法访问新闻列表页面");
response.sendRedirect("index.jsp");
} else {
// 删除session里的errMsg属性
if (session.getAttribute("errMsg") != null) {
session.removeAttribute("errMsg");
}
if (session.getAttribute("Msg") != null) {
session.removeAttribute("Msg");
}
}
%>
<div>
登录用户:<span style="color: red;">${username}</span>
<c:forEach var="i" begin="1" end="5">
</c:forEach>
</div>
<div class="title">
<h3>新闻列表</h3>
</div>
<div class="main">
<table>
<tr>
<th>新闻编号</th>
<th>新闻标题</th>
</tr>
<c:forEach var="news" items="${news}">
<tr align='center'>
<td>${news.ntid}</td>
<td width="500">
<a href="">${news.ntitle}</a>
</td>
</tr>
</c:forEach>
</table>
</div>
<%
String errMsg = (String) session.getAttribute("errMsg");
if (errMsg != null) {
// errMsg = new String(errMsg.getBytes("ISO-8859-1"), "utf-8");
out.println("<script>alert('" + errMsg + "')</script>");
}
String Msg = (String) session.getAttribute("Msg");
if (Msg != null) {
// errMsg = new String(errMsg.getBytes("ISO-8859-1"), "utf-8");
out.println("<script>alert('" + Msg + "')</script>");
}
%>
</body>
</html>
OK,现在进行测试
能正常访问
重新登录非管理员账号
进入新闻列表页面
练习4、显示新闻主题列表
需求说明:
将新闻主题以列表方式显示
显示新闻主题的名称
创建Topic实体类
创建TopicDao以及TopicDaoImpl
package net.hw.dao;
import net.hw.bean.Topic;
import java.util.List;
public interface TopicDao {
int insert(Topic topic);
List<Topic> findAll();
}
package net.hw.dao.impl;
import net.hw.bean.News;
import net.hw.bean.Topic;
import net.hw.dao.TopicDao;
import net.hw.dbutil.ConnectionManager;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class TopicDaoImpl implements TopicDao {
@Override
public int insert(Topic topic) {
//定义插入记录数
int count = 0;
// 获得数据库连接
Connection conn = ConnectionManager.getConnection();
// 定义SQL字符串
String strSQL = "INSERT INTO topic (tid,tname) VALUES (?,?)";
try {
// 创建预备语句对象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 设置占位符的值
pstmt.setInt(1, topic.getTid());
pstmt.setString(2, topic.getTname());
// 执行更新操作,插入新录
count = pstmt.executeUpdate();
// 关闭预备语句对象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionManager.closeConnection(conn);
}
// 返回插入记录数
return count;
}
@Override
public List<Topic> findAll() {
// 声明类别列表
List<Topic> topics = new ArrayList<Topic>();
// 获取数据库连接对象
Connection conn = ConnectionManager.getConnection();
// 定义SQL字符串
String strSQL = "SELECT * FROM topic";
try {
// 创建语句对象
Statement stmt = conn.createStatement();
// 执行SQL,返回结果集
ResultSet rs = stmt.executeQuery(strSQL);
// 遍历结果集
while (rs.next()) {
// 创建类别实体
Topic topic = new Topic();
// 设置实体属性
topic.setTid(rs.getInt("tid"));
topic.setTname(rs.getString("tname"));
// 将实体添加到类别列表
topics.add(topic);
}
// 关闭结果集
rs.close();
// 关闭语句对象
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭数据库连接
ConnectionManager.closeConnection(conn);
}
// 返回类别列表
return topics;
}
}
创建TopicServlet类
package net.hw.servlet;
import net.hw.bean.Topic;
import net.hw.dao.impl.TopicDaoImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
@WebServlet("/topic")
public class TopicServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 创建类别服务对象
TopicDaoImpl topicDao = new TopicDaoImpl();
// 获取全部商品类别
List<Topic> topics = topicDao.findAll();
// 获取session对象
HttpSession session = request.getSession();
// 把商品类别列表以属性的方式保存到session里
session.setAttribute("topic", topics);
// 重定向到显示商品类别页面(showCategory.jsp)
response.sendRedirect(request.getContextPath() + "/showTopic.jsp");
// 在服务器控制台输出测试信息
for (Topic topic:topics) {
System.out.println(topic);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
super.doPost(request, response);
}
}
创建showTopic.jsp
<%@ page import="net.hw.bean.Topic" %>
<%@ page import="net.hw.dao.TopicDao" %>
<%@ page import="net.hw.dao.impl.TopicDaoImpl" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<title>新闻主题列表</title>
<html>
<head>
</head>
<body>
<div>
<c:forEach var="i" begin="1" end="5">
</c:forEach>
</div>
<div>
<h3 align="center">新闻主题列表</h3>
</div>
<div>
<table align="center">
<tr>
<th>主题编号</th>
<th>新闻主题</th>
</tr>
<c:forEach var="topic" items="${topic}">
<tr align='center'>
<td>${topic.tid}</td>
<td width="150"><a href="">${topic.tname}</a></td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
启动服务,查看效果
练习5、添加新闻主题
需求说明:
新闻主题添加页面
主题名称
业务处理页面
获取主题名称
将主题保存到数据库中
保存成功后返回主题列表
1.在TopicDao数据访问接口中写添加新闻主题的方法
2.在TopicDaoImpl中实现添加方法
编写add_topic.jsp页面
<%@ page import="net.hw.bean.User" %>
<%@page contentType="text/html; charset=utf-8" %>
<html>
<head>
<title>添加新闻</title>
</head>
<body>
<%--利用session实现登录验证--%>
<%
User user = (User) session.getAttribute("LOGINED_USER");
if (user == null) {
// 在session里创建errMsg属性
session.setAttribute("errMsg", "要访问添加新闻主题页面,请先登录");
// 采用重定向,跳转到登录页面
response.sendRedirect("login.jsp");
} else if (!session.getAttribute("username").equals("admin")) {
session.setAttribute("Msg", "您不是管理员无法访问添加新闻主题页面");
response.sendRedirect("index.jsp");
} else {
// 删除session里的errMsg属性
if (session.getAttribute("errMsg") != null) {
session.removeAttribute("errMsg");
}
if (session.getAttribute("Msg") != null) {
session.removeAttribute("Msg");
}
}
%>
<h3 align="center">添加新闻</h3>
<form action="do_addtopic.jsp" method="post">
<table border="1" cellpadding="10" style="margin: 0px auto">
<tr>
<td align="center">主题编号</td>
<td><input type="text" name="tid"/></td>
</tr>
<tr>
<td align="center">新闻主题</td>
<td><input type="text" name="tname"/></td>
</tr>
<tr align="center">
<td colspan="2">
<input type="submit" value="提交"/>
<input type="reset" value="重置"/>
</td>
</tr>
</table>
</form>
<%
String Msg = (String) session.getAttribute("Msg");
if (Msg != null) {
// errMsg = new String(errMsg.getBytes("ISO-8859-1"), "utf-8");
out.println("<script>alert('" + Msg + "')</script>");
}
%>
</body>
</html>
编写do_addtopic.jsp页面
<%@ page import="java.net.URLEncoder" %>
<%@ page import="java.sql.*" %>
<%@ page import="net.hw.dbutil.ConnectionManager" %>
<%@ page import="net.hw.bean.Topic" %>
<%@ page import="net.hw.dao.TopicDao" %>
<%@ page import="net.hw.dao.impl.TopicDaoImpl" %>
<%@ page contentType="text/html;charset=utf-8" %>
<%
// 设置请求对象字符编码
request.setCharacterEncoding("utf-8");
// 获取表单提交的数据
String tname = request.getParameter("tname");
String tid = request.getParameter("tid");
// 创建新闻主题访问对象
TopicDao topicDao = new TopicDaoImpl();
// 创建新闻主题对象
Topic topic = new Topic();
// 设置新闻主题对象属性
topic.setTid(Integer.parseInt(tid));
topic.setTname(tname);
//
int count = topicDao.insert(topic);
if(count>0){
// 清除session里可能存在的errMsg属性
if (session.getAttribute("errMsg") != null) {
session.removeAttribute("errMsg");
}
// 采用重定向,跳转到新闻主题列表页面
response.sendRedirect("topic");
}else{
// 设置session里的errMsg属性
session.setAttribute("errMsg", "添加新闻主题失败!");
// 采用重定向,跳转到添加新闻主题页面
response.sendRedirect("add_topic");
}
%>
启动服务试试效果!
添加成功了!
练习6、实现发布新闻
需求说明:
实现新闻的发布
将发布内容保存到数据库中
图片上传功能暂不实现
在NewsDao数据访问接口中写添加新闻的方法
在NewsDaoImpl中实现添加新闻方法
编写add_news.jsp页面
<%@ page import="net.hw.bean.User" %>
<%@page contentType="text/html; charset=utf-8" %>
<html>
<head>
<title>添加新闻</title>
</head>
<body>
<%--利用session实现登录验证--%>
<%
User user = (User) session.getAttribute("LOGINED_USER");
if (user == null) {
// 在session里创建errMsg属性
session.setAttribute("errMsg", "要访问添加新闻页面,请先登录");
// 采用重定向,跳转到登录页面
response.sendRedirect("login.jsp");
} else if (!session.getAttribute("username").equals("admin")) {
session.setAttribute("Msg", "您不是管理员无法访问添加新闻页面");
response.sendRedirect("index.jsp");
} else {
// 删除session里的errMsg属性
if (session.getAttribute("errMsg") != null) {
session.removeAttribute("errMsg");
}
if (session.getAttribute("Msg") != null) {
session.removeAttribute("Msg");
}
}
%>
<h3 align="center">添加新闻</h3>
<form action="do_addnews.jsp" method="post">
<table border="1" cellpadding="10" style="margin: 0px auto">
<tr>
<td align="center">新闻编号</td>
<td><input type="text" name="ntid"/></td>
</tr>
<tr>
<td align="center">新闻标题</td>
<td><input type="text" name="ntitle"/></td>
</tr>
<tr>
<td align="center">新闻作者</td>
<td><input type="text" name="nauthor"/></td>
</tr>
<tr>
<td align="center">新闻内容</td>
<td><input type="text" name="ncontent"/></td>
</tr>
<tr align="center">
<td colspan="2">
<input type="submit" value="提交"/>
<input type="reset" value="重置"/>
</td>
</tr>
</table>
</form>
<%
String Msg = (String) session.getAttribute("Msg");
if (Msg != null) {
// errMsg = new String(errMsg.getBytes("ISO-8859-1"), "utf-8");
out.println("<script>alert('" + Msg + "')</script>");
}
%>
</body>
</html>
编写do_addnews.jsp页面
<%@ page import="java.net.URLEncoder" %>
<%@ page import="java.sql.*" %>
<%@ page import="net.hw.dbutil.ConnectionManager" %>
<%@ page import="net.hw.bean.Topic" %>
<%@ page import="net.hw.dao.TopicDao" %>
<%@ page import="net.hw.dao.impl.TopicDaoImpl" %>
<%@ page import="net.hw.dao.NewsDao" %>
<%@ page import="net.hw.dao.impl.NewsDaoImpl" %>
<%@ page import="net.hw.bean.News" %>
<%@ page contentType="text/html;charset=utf-8" %>
<%
// 设置请求对象字符编码
request.setCharacterEncoding("utf-8");
// 获取表单提交的数据
String ntid = request.getParameter("ntid");
String ntitle = request.getParameter("ntitle");
String nauthor = request.getParameter("nauthor");
String ncontent = request.getParameter("ncontent");
// 创建新闻访问对象
NewsDao newsDao = new NewsDaoImpl();
// 创建新闻对象
News news = new News();
// 设置新闻对象属性
news.setNtid(Integer.parseInt(ntid));
news.setNtitle(ntitle);
news.setNauthor(nauthor);
news.setNcontent(ncontent);
//
int count = newsDao.insert(news);
if(count>0){
// 清除session里可能存在的errMsg属性
if (session.getAttribute("errMsg") != null) {
session.removeAttribute("errMsg");
}
// 采用重定向,跳转到新闻列表页面
response.sendRedirect("news");
}else{
// 设置session里的errMsg属性
session.setAttribute("errMsg", "添加新闻失败!");
// 采用重定向,跳转到添加新闻主题页面
response.sendRedirect("add_news.jsp");
}
%>
启动服务,来试哈得不得行
添加成功了!啊终于完成了这个周的课后作业