用JavaEE写一个新闻管理系统
时间: 2023-09-21 18:09:44 浏览: 109
基于javaEE技术的新闻管理系统的设计与实现论文.docx
好的,以下是 JavaEE 新闻管理系统的代码示例:
1. 创建数据库表
首先需要创建一个新闻表,包括新闻ID、新闻标题、新闻内容、发布时间、修改时间等字段。
```sql
CREATE TABLE `news` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`content` text NOT NULL,
`create_time` datetime NOT NULL,
`update_time` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
```
2. 创建 Java 类
在 JavaEE 项目中,我们可以使用 Servlet 和 JSP 进行开发。首先创建一个 News 类,用于封装新闻信息。
```java
public class News {
private int id;
private String title;
private String content;
private Date createTime;
private Date updateTime;
// 省略 getter 和 setter 方法
}
```
3. 创建 DAO 类
创建一个 NewsDAO 类,用于与数据库进行交互,实现增删改查等操作。
```java
public class NewsDAO {
private Connection conn;
public NewsDAO(Connection conn) {
this.conn = conn;
}
// 添加新闻
public void addNews(News news) throws SQLException {
PreparedStatement pstmt = null;
String sql = "INSERT INTO news (title, content, create_time, update_time) VALUES (?, ?, ?, ?)";
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, news.getTitle());
pstmt.setString(2, news.getContent());
pstmt.setTimestamp(3, new Timestamp(news.getCreateTime().getTime()));
pstmt.setTimestamp(4, new Timestamp(news.getUpdateTime().getTime()));
pstmt.executeUpdate();
} finally {
if (pstmt != null) {
pstmt.close();
}
}
}
// 修改新闻
public void updateNews(News news) throws SQLException {
PreparedStatement pstmt = null;
String sql = "UPDATE news SET title=?, content=?, update_time=? WHERE id=?";
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, news.getTitle());
pstmt.setString(2, news.getContent());
pstmt.setTimestamp(3, new Timestamp(news.getUpdateTime().getTime()));
pstmt.setInt(4, news.getId());
pstmt.executeUpdate();
} finally {
if (pstmt != null) {
pstmt.close();
}
}
}
// 删除新闻
public void deleteNews(int id) throws SQLException {
PreparedStatement pstmt = null;
String sql = "DELETE FROM news WHERE id=?";
try {
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
pstmt.executeUpdate();
} finally {
if (pstmt != null) {
pstmt.close();
}
}
}
// 根据ID获取新闻
public News getNewsById(int id) throws SQLException {
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "SELECT * FROM news WHERE id=?";
try {
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
rs = pstmt.executeQuery();
if (rs.next()) {
News news = new News();
news.setId(rs.getInt("id"));
news.setTitle(rs.getString("title"));
news.setContent(rs.getString("content"));
news.setCreateTime(rs.getTimestamp("create_time"));
news.setUpdateTime(rs.getTimestamp("update_time"));
return news;
} else {
return null;
}
} finally {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
}
}
// 获取所有新闻
public List<News> getAllNews() throws SQLException {
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "SELECT * FROM news";
try {
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
List<News> newsList = new ArrayList<>();
while (rs.next()) {
News news = new News();
news.setId(rs.getInt("id"));
news.setTitle(rs.getString("title"));
news.setContent(rs.getString("content"));
news.setCreateTime(rs.getTimestamp("create_time"));
news.setUpdateTime(rs.getTimestamp("update_time"));
newsList.add(news);
}
return newsList;
} finally {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
}
}
}
```
4. 创建 Servlet 类
创建一个 NewsServlet 类,用于接收用户请求,调用 NewsDAO 类中的方法进行处理,并将结果返回给用户。
```java
@WebServlet(name = "NewsServlet", urlPatterns = {"/news"})
public class NewsServlet extends HttpServlet {
private Connection conn;
public void init() throws ServletException {
// 获取数据库连接
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8";
String username = "root";
String password = "root";
conn = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void destroy() {
// 关闭数据库连接
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if ("add".equals(action)) {
addNews(request, response);
} else if ("update".equals(action)) {
updateNews(request, response);
} else if ("delete".equals(action)) {
deleteNews(request, response);
} else if ("view".equals(action)) {
viewNews(request, response);
} else {
listNews(request, response);
}
}
// 添加新闻
private void addNews(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String title = request.getParameter("title");
String content = request.getParameter("content");
Date createTime = new Date();
Date updateTime = new Date();
News news = new News();
news.setTitle(title);
news.setContent(content);
news.setCreateTime(createTime);
news.setUpdateTime(updateTime);
NewsDAO newsDAO = new NewsDAO(conn);
try {
newsDAO.addNews(news);
response.sendRedirect(request.getContextPath() + "/news");
} catch (SQLException e) {
e.printStackTrace();
}
}
// 修改新闻
private void updateNews(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
String title = request.getParameter("title");
String content = request.getParameter("content");
Date updateTime = new Date();
News news = new News();
news.setId(id);
news.setTitle(title);
news.setContent(content);
news.setUpdateTime(updateTime);
NewsDAO newsDAO = new NewsDAO(conn);
try {
newsDAO.updateNews(news);
response.sendRedirect(request.getContextPath() + "/news");
} catch (SQLException e) {
e.printStackTrace();
}
}
// 删除新闻
private void deleteNews(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
NewsDAO newsDAO = new NewsDAO(conn);
try {
newsDAO.deleteNews(id);
response.sendRedirect(request.getContextPath() + "/news");
} catch (SQLException e) {
e.printStackTrace();
}
}
// 查看新闻
private void viewNews(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
NewsDAO newsDAO = new NewsDAO(conn);
try {
News news = newsDAO.getNewsById(id);
request.setAttribute("news", news);
request.getRequestDispatcher("/view.jsp").forward(request, response);
} catch (SQLException e) {
e.printStackTrace();
}
}
// 列出所有新闻
private void listNews(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
NewsDAO newsDAO = new NewsDAO(conn);
try {
List<News> newsList = newsDAO.getAllNews();
request.setAttribute("newsList", newsList);
request.getRequestDispatcher("/list.jsp").forward(request, response);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
5. 创建 JSP 页面
创建两个 JSP 页面,list.jsp 用于展示所有新闻,view.jsp 用于展示单个新闻的详细信息。
list.jsp:
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>新闻管理系统</title>
</head>
<body>
<h1>新闻列表</h1>
<p><a href="${request.contextPath}/news?action=add">添加新闻</a></p>
<table border="1">
<tr>
<th>ID</th>
<th>标题</th>
<th>创建时间</th>
<th>修改时间</th>
<th>操作</th>
</tr>
<c:forEach items="${newsList}" var="news">
<tr>
<td>${news.id}</td>
<td>${news.title}</td>
<td>${news.createTime}</td>
<td>${news.updateTime}</td>
<td>
<a href="${request.contextPath}/news?action=view&id=${news.id}">查看</a>
<a href="${request.contextPath}/news?action=update&id=${news.id}">编辑</a>
<a href="${request.contextPath}/news?action=delete&id=${news.id}" onclick="return confirm('确定删除该新闻吗?')">删除</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
```
view.jsp:
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>新闻管理系统</title>
</head>
<body>
<h1>${news.title}</h1>
<p>${news.content}</p>
<p>
<a href="${request.contextPath}/news?action=update&id=${news.id}">编辑</a>
<a href="${request.contextPath}/news?action=delete&id=${news.id}" onclick="return confirm('确定删除该新闻吗?')">删除</a>
</p>
</body>
</html>
```
6. 部署项目
将代码打成 WAR 包,部署到 Tomcat 或其他 JavaEE 容器中即可。访问 http://localhost:8080/news 即可查看新闻列表。
以上就是一个简单的 JavaEE 新闻管理系统的实现,仅供参考。
阅读全文