声明:此项目为本人学生作品,作者本人水平有限,难免在代码中留下错误,难免出现bug!!!!!请自行百度,有问题可以在评论区留言,博主学业繁忙,随缘回复,代码经过测试后上传,已经是完整版,仅供参考,
项目二:新闻中心管理系统
1、项目来源及背景
为了能够更加迅速地向客户传递有关企业的新闻以及相关行业中最新的发展现状,以便于引导客户选择企业的相关产品和服务,一般在商务系统的开发中,都会设置相应的新闻中心模块。该新闻中心应该能够及时提供最新的资讯,并且应该在显示某条新闻的同时,列出所有的相关新闻,以便于客户在最短的时间内获得最新最全的信息。
此外,考虑到新闻的时效性,新闻中心管理系统中一般都需要提供良好的维护页面,即中心管理人员可以借助后台维护管理的页面实现对新闻内容实时的更新维护。
2、系统需求分析
2.1 需求描述
新闻中心管理系统主要是为了实现商务网站动态新闻实时显示的系统。一个典型的新闻中心管理系统一般都会提供新闻标题分类显示、新闻详细内容显示等功能。同时也要为新闻中心后台管理的管理员提供对应的新闻信息维护及管理的功能,包括添加新的新闻、编辑修改新闻、删除新闻等功能。
根据企业商务新闻的基本要求,本系统需要完成如下的主要任务:
(1)新闻标题信息分类显示:在进入新闻中心主页时,应该能够根据数据库中存放的信息分类显示最新的新闻标题。例如可以显示所有最新的标题信息。每个新闻标题都应该提供对应的超链接,单击后,就可以跳转到有关该新闻详细内容的页面上,以便用户对这条新闻有更详细的了解。
(2)新闻详细内容及相关新闻列表显示:当单击某个新闻标题后,可以查看该新闻的详细内容。同时提供与该新闻相关的新闻标题信息的显示,以便于查询与该新闻相关的其他信息(扩展)。
(3)新闻中心后台管理功能:新闻中心的管理员可以根据企业的服务需要随时向数据库中添加最新的新闻标题及相关内容。还可以删除不再需要的新闻标题及内容,以及对原有新闻做必要的修改。
2.2 系统用况图
图1 管理员用例图
图2 浏览者用例图
图3 系统类图
3、系统总体设计
3.1 系统总体功能结构
图4 系统层次结构图
3.2 功能描述
浏览者可以看到所有新闻的标题,点击新闻标题超链接,可以在页面中显示新闻标题、新闻类型、新闻作者、新闻内容、新闻发布时间、及相关新闻的标题,通过点击相关新闻标题超链接,就可以查看该相关新闻的详细信息。
图5 新闻中心管理系统前台活动图
只有合法身份的管理员才可以进行后台管理,系统的3个子模块(添加新闻、修改新闻、删除新闻)在操作上是平行的,其内在关系通过后续数据库的设计和程序流程来控制。
4、系统详细设计
4.1 系统数据设计
新闻基本信息表(newsdetail)用来保存和新闻相关的基本信息,是显示和维护新闻数据的依据。表1所示列出了该表中所包含的字段的描述信息。
表1 新闻基本信息表
后台管理员信息表(admin)记录了新闻中心管理员的相关信息,主要是登录系统后台时验证的依据。
表2 后台管理员信息表
4.2 目录和包结构设计
4.3 系统流程设计
以登录功能为例,文字描述、组件图描述
5、系统实现预览
5.1 前台
在地址栏中输入地址进入新闻中心首页,在该页面中显示了所有的新闻,并给出了各个新闻的标题,且针对标题文字提供了相应的超链接,以便用户查看新闻的具体内容。
图9 新闻中心首页
News_Center_Homepage
在图中单击“所有新闻”链接后,会显示系统中的新闻,如图所示。
图10 新闻中心文件列表
News_Center File_List
单击文件标题可以查看新闻的具体内容,如图所示。
图11 查看新闻详细信息
News_Details
单击“搜索新闻”可以进行新闻的搜索,如图所示。
图12 新闻搜索
News_Serach
输入要查询的关键字后单击“搜索新闻”即可列出新闻列表,单击新闻标题可以查看新闻内容。
图11 查看新闻详细信息
5.2 后台
点击“后台管理”超链接进入后台管理界面。在进入新闻管理主页后,首先要管理员输入账号密码后,就可以查看新闻、添加新闻、编辑新闻以及删除新闻。
图13 管理员登录界面
login
登录成功后,单击“所有新闻”链接可以查看所有新闻,如图所示。
图15 编辑新闻界面
Edit_News
新闻编辑完毕后,单击“编辑提交”即可完成新闻编辑。
点击“删除”链接,可以删除该新闻。
点击“添加新闻”链接,可以添加新闻,如图所示。
图16 添加新闻界面(有个小bug 获取id会变成0,要手动把id改成其他整数)
Add_News
本文将按照图示,展示代码
首先先展示配置类
环境:jdk1.8 IDEA Tomcat9
sql
/*
Navicat MySQL Data Transfer
Source Server : T
Source Server Version : 80031
Source Host : localhost:3306
Source Database : jdbc
Target Server Type : MYSQL
Target Server Version : 80031
File Encoding : 65001
Date: 2025-04-18 10:59:41
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `admin`
-- ----------------------------
DROP TABLE IF EXISTS `admin`;
CREATE TABLE `admin` (
`adminid` int NOT NULL AUTO_INCREMENT,
`adminname` varchar(50) NOT NULL,
`adminpass` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
PRIMARY KEY (`adminid`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb3;
-- ----------------------------
-- Records of admin
-- ----------------------------
INSERT INTO `admin` VALUES ('1', 'we', '123456');
-- ----------------------------
-- Table structure for `newsdetail`
-- ----------------------------
DROP TABLE IF EXISTS `newsdetail`;
CREATE TABLE `newsdetail` (
`id` int NOT NULL AUTO_INCREMENT,
`title` varchar(50) NOT NULL,
`content` varchar(4000) NOT NULL,
`author` varchar(50) NOT NULL,
`time` datetime(6) DEFAULT NULL,
`type` int DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb3;
-- ----------------------------
-- Records of newsdetail
-- ----------------------------
INSERT INTO `newsdetail` VALUES ('1', '2008年金融危机', '1', '转载', '2024-12-03 16:30:52.000000', '1');
INSERT INTO `newsdetail` VALUES ('2', '2024年暴雪', '2', '转载', '2024-12-02 22:29:56.000000', '2');
INSERT INTO `newsdetail` VALUES ('3', '2025月亮', '3', '转载', '2024-12-08 22:30:13.000000', '333');
INSERT INTO `newsdetail` VALUES ('4', '1936双十二', '4', '转载', '2024-11-06 03:34:50.000000', '1');
-- ----------------------------
-- Table structure for `stu`
-- ----------------------------
DROP TABLE IF EXISTS `stu`;
CREATE TABLE `stu` (
`id` varchar(255) NOT NULL,
`name` varchar(255) DEFAULT NULL,
`age` varchar(255) DEFAULT NULL,
`sex` varchar(255) DEFAULT NULL,
`class` varchar(255) DEFAULT NULL,
`tel` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
-- ----------------------------
-- Records of stu
-- ----------------------------
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 1. 加载根上下文(Service/DAO层) -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 2. 配置 Spring MVC 前端控制器 -->
<!-- 配置前端控制器 -->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置初始化参数,读取Spring MVC的配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
application.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mybatis-spring="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Enable component scanning for automatic bean detection自动扫描注解 -->
<!-- 固定写法:context命名空间标签,开启组件扫描 -->
<!-- base-package:可变,需替换为项目实际包路径(扫描范围) -->
<context:component-scan base-package="org.example">
<!-- 排除 Controller 和 Mapper -->
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
<context:exclude-filter type="annotation"
expression="org.apache.ibatis.annotations.Mapper"/>
</context:component-scan>
<!-- ====================================== 普通Bean定义(两种创建方式) ====================================== -->
<bean id="Admin" class="org.example.entity.Admin">
<property name="adminid" value="3"></property>
<property name="adminname" value="er"></property>
<property name="adminpass" value="123456"></property>
</bean>
<bean id="NewsDetail" class="org.example.entity.NewsDetail">
<!-- 固定写法:property标签,通过setter方法注入属性 -->
<!-- name:可变,对应类的属性名(首字母小写) -->
<!-- value:可变,属性值(字符串、基本类型等) -->
</bean>
<!-- ====================================== Mapper层扫描 ====================================== -->
<!-- Scan Mapper Files -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="org.example.mapper"/>
<property name="annotationClass" value="org.apache.ibatis.annotations.Mapper"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<!-- ====================================== Service层扫描 ====================================== -->
<!-- =====为什么不扫描service层,因为在spring-mvc。xml里面扫========== -->
<!-- ====================================== Spring JDBC与事务管理 ====================================== -->
<!-- 1. 配置数据源(固定写法:使用DriverManagerDataSource) -->
<!-- 可变:数据库连接参数(驱动、URL、用户名、密码需根据实际数据库修改) -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/> <!-- MySQL 8+驱动 -->
<property name="url" value="jdbc:mysql://127.0.0.1:3306/jdbc?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!-- 2. 配置JDBC模板(固定写法:依赖数据源) -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/> <!-- 引用数据源Bean -->
</bean>
<!-- 配置 SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 4. 事务管理器(固定写法:依赖数据源) -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--配置mybatis-->
<properties resource="db.properties"/>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!-- JDBC 驱动-->
<property name="driver" value="${mysql.driver}"/>
<!-- url数据库的 JDBC URL地址。-->
<property name="url" value="${mysql.url}"/>
<property name="username" value="${mysql.username}"/>
<property name="password" value="${mysql.password}"/>
</dataSource>
</environment>
</environments>
</configuration>
spring-mvc
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- 配置组件扫描 -->
<context:component-scan base-package="org.example.controller">
<!-- 确保排除其他层组件 -->
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Service"/>
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Repository"/>
</context:component-scan>
<!-- 配置MVC注解扫描 -->
<mvc:annotation-driven />
<!-- 静态资源默认servlet配置 -->
<mvc:default-servlet-handler/>
<!-- 配置视图解析器, -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/" /><!-- 前缀 -->
<property name="suffix" value=".jsp" /><!-- 后缀 -->
</bean>
</beans>
db.properties
mysql.driver=com.mysql.cj.jdbc.Driver
mysql.username=root
mysql.password=123456
mysql.url=jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC&useSSL=false
测试类
AdminDaoTest
import org.example.mapper.AdminDao;
import org.example.entity.Admin;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AdminDaoTest {
public static void main(String[] args) {
// 加载 Spring 配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
// 从 Spring 容器中获取 AdminDao 实例
AdminDao adminDao = context.getBean("adminDao", AdminDao.class);
// 定义测试用的用户名和密码
String adminname = "we";
String adminpass = "123456";
// 调用 checkLogin 方法进行测试
Admin admin = adminDao.checkLogin(adminname,adminpass);
// 根据返回结果输出信息
if (admin != null) {
System.out.println("mapper层注册成功");
System.out.println("登录成功");
} else {
System.out.println("登录失败,未找到匹配的管理员信息。");
}
}
}
AdminServiceTest
import org.example.service.impl.adminServiceimpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AdminServiceTest {
public static void main(String[] args) {
// 加载applicationContext.xml配置
ApplicationContext applicationContext=new
ClassPathXmlApplicationContext("application.xml");
adminServiceimpl adminServiceimpl=(adminServiceimpl)// 获取配置中的UserService实例
applicationContext.getBean("adminServiceimpl");
System.out.println(applicationContext.getBean("adminServiceimpl"));
System.out.println("service层注册成功");
}
}
DatabaseConnectionTest
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnectionTest {
public static void main(String[] args) {
// 数据库连接信息
String url = "jdbc:mysql://localhost:3306/jdbc";
String username = "root";
String password = "123456";
// 加载驱动程序
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("找不到数据库驱动程序!");
e.printStackTrace();
return;
}
// 建立数据库连接
try (Connection connection = DriverManager.getConnection(url, username, password)) {
System.out.println("数据库连接成功!");
} catch (SQLException e) {
System.out.println("数据库连接失败!");
e.printStackTrace();
}
}
}
TestAdmin
import org.example.entity.Admin;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestAdmin {
public static void main(String[] args) {
// 加载 Spring 配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
Admin admin = context.getBean("Admin",Admin.class);
System.out.println(admin);
System.out.println("entity层注册成功");
}
}
代码将按MVC框架介绍
entity层
package org.example.entity;
public class Admin {
private int adminid;
private String adminname;
private String adminpass;
public int getAdminid() {
return adminid;
}
public void setAdminid(int adminid) {
this.adminid = adminid;
}
public String getAdminname() {return adminname;}
public void setAdminname(String adminname) {
this.adminname = adminname;
}
public String getAdminpass() {
return adminpass;
}
public void setAdminpass(String adminpass) {
this.adminpass = adminpass;
}
}
package org.example.entity;
public class NewsDetail {
private int id;
private String title;
private String content;
private String author;
private String time;
private int type;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
@Override
public String toString() {
return "NewsDetail{" +
"id=" + id +
", title='" + title + '\'' +
", content='" + content + '\'' +
", author='" + author + '\'' +
", time='" + time + '\'' +
", type=" + type +
'}';
}
}
mapper 层
package org.example.mapper;
import org.apache.ibatis.annotations.*;
import org.example.entity.NewsDetail;
import java.util.List;
@Mapper
public interface AllDao {
//搜索全部 将其内部结果集合成一个列表 显示内容========
@Select("SELECT id,title,content,author,time,type FROM newsdetail")
public List<NewsDetail> getAllArticles();
//模糊搜索
@Select("SELECT * FROM newsdetail WHERE title LIKE CONCAT('%', #{title}, '%')")
public List<NewsDetail> searchArticlesByTitle(@Param("title") String title);
// 新增的插入文章数据到newsdetail表的方法
@Insert("INSERT INTO newsdetail (title, content,author, time,type ) VALUES (#{title}, #{content}, #{author},#{time},#{type})")
public int insertArticle(@Param("title") String title, @Param("content") String content, @Param("author") String author,@Param("time") String time, @Param("type") int type);
//View_All_News.jsp用于列出所有 不显示内容=============
@Select("SELECT id,title,type,author,time FROM newsdetail")
public List<NewsDetail> getAllView();
// 新增的删除方法,根据新闻标题删除对应记录
@Delete("DELETE FROM newsdetail WHERE title = #{title}")
public int deleteByTitle(@Param("title") String title);
// 新增的查询方法,根据新闻标题查询对应记录===========
@Select("SELECT title, author, type, time, content FROM newsdetail WHERE title = #{title}")
public List<NewsDetail> getNewsDetailByTitle(@Param("title")String title);
// 新增的更新方法,用于更新新闻记录
// 使用 id 作为更新条件
@Update("UPDATE newsdetail SET title=#{title}, author=#{author}, type=#{type}, time=#{time}, content=#{content} WHERE id=#{id}")
int updateNewsDetail(NewsDetail nd);
//detail===============
@Select("SELECT title, content, author, time, type FROM newsdetail WHERE title = #{title}")
public List<NewsDetail> detail(@Param("title")String title);
}
package org.example.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.example.entity.Admin;
@Mapper
public interface AdminDao {
@Select("select * from admin where adminname = #{adminname} and adminpass = #{adminpass}")
public Admin checkLogin( @Param("adminname") String adminname,
@Param("adminpass") String adminpass);
}
service层
package org.example.service;
import org.apache.ibatis.annotations.*;
import org.example.entity.NewsDetail;
import java.util.List;
public interface AllService {
//View_All_News.jsp用于列出所有
public List<NewsDetail> getAllView();
//模糊搜索
public List<NewsDetail> searchArticlesByTitle(String title);
//detail
public List<NewsDetail> detail(@Param("title")String title);
// 新增的更新方法,用于更新新闻记录
public int updateNewsDetail(NewsDetail nd);
// 新增的插入文章数据到newsdetail表的方法
public int insertArticle(String title, String content, String author,String time, int type);
// 新增的删除方法,根据新闻标题删除对应记录
public int deleteByTitle(@Param("title") String title);
}
package org.example.service.impl;
import org.example.entity.NewsDetail;
import org.example.mapper.AllDao;
import org.example.service.AllService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Collections;
import java.util.List;
@Service
public class AllServiceimpl implements AllService {
@Autowired
private AllDao allDao;
@Override
public List<NewsDetail> getAllView() {
return allDao.getAllView();
}
@Override
public List<NewsDetail> searchArticlesByTitle(String title) {
return allDao.searchArticlesByTitle(title);
}
@Override
public List<NewsDetail> detail(String title) {
return allDao.detail(title);
}
@Override
public int updateNewsDetail(NewsDetail nd) {
return allDao.updateNewsDetail(nd);
}
@Override
public int insertArticle(String title, String content, String author, String time, int type) {
return allDao.insertArticle(title,content,author,time,type);
}
@Override
public int deleteByTitle(String title) {
return allDao.deleteByTitle(title);
}
}
package org.example.service;
import org.apache.ibatis.annotations.Param;
import org.example.entity.Admin;
public interface AdminService {
public Admin checkLogin(String adminname,
String adminpass);
}
package org.example.service.impl;
import org.example.entity.Admin;
import org.example.mapper.AdminDao;
import org.example.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class adminServiceimpl implements AdminService {
@Autowired
private AdminDao adminDao;
@Override
public Admin checkLogin(String adminname, String adminpass) {
// 添加日志验证
System.out.println("DAO实例: " + adminDao);
return adminDao.checkLogin(adminname, adminpass);
}
}
controller层
package org.example.controller;
import org.example.entity.Admin;
import org.example.service.AdminService;
import org.example.service.AllService;
import org.example.service.impl.adminServiceimpl;
import org.example.service.impl.AllServiceimpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
@Controller
public class AdminController {
@Autowired
private AdminService adminService;
@GetMapping("/login") // 处理GET请求显示登录页面
public String showLoginForm() {
return "login";
}
@PostMapping("/login")
public String handleLogin(@RequestParam String adminname,
@RequestParam String adminpass,
HttpSession session,
Model model) {
// 1. 调用服务层验证登录
Admin admin =adminService.checkLogin(adminname,adminpass);
// 2. 判断查询结果
if (admin != null) {
// 登录成功:存储会话信息
session.setAttribute("currentAdmin", admin);
model.addAttribute("message", "登陆成功,请选择");
// 重定向到主页(避免表单重复提交)
return "Success";
} else {
// 登录失败:添加错误提示
model.addAttribute("errorMsg", "用户名或密码错误");
// 返回登录页面(注意这里用forward保持POST请求)
return "login";
}
}
}
package org.example.controller;
import org.apache.ibatis.annotations.Param;
import org.example.entity.NewsDetail;
import org.example.service.AllService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpSession;
import java.util.List;
@Controller
public class AllController {
@Autowired
private AllService allService;
@RequestMapping("/index")
public String index(){
return "News_Center_Homepage";
}
//==================================================================================
@GetMapping("/News_Center_File_List")
public String getAll(Model model) {
List<NewsDetail> temp = allService.getAllView();
System.out.println("查询结果: " + temp); // 检查日志输出
model.addAttribute("temp", temp);
return "News_Center_File_List"; // 返回视图名称
}
//==============================================================================
@GetMapping("/Serach")
public String get(){
return "News_Serach";
}
@PostMapping("/Serach")
public String searchArticlesByTitle(@RequestParam String title,
Model model,
HttpSession session){
List<NewsDetail> serachtitle =allService.searchArticlesByTitle(title);
// 将搜索关键字存入Session
session.setAttribute("keyword", title); // Key为"keyword",值为用户输入的title
System.out.println("查询结果: " + serachtitle); // 检查日志输出
model.addAttribute("temp",serachtitle);
return "News_Serach";
}
//==============================================================================
@RequestMapping("/detail")
public String detail(@RequestParam("title") String title,
Model model) {
List<NewsDetail> detail =allService.detail(title);
System.out.println("查询结果: " + detail); // 检查日志输出
model.addAttribute("temp3",detail);
return "News_Details";
}
//=============================================================
@GetMapping("/View_All_News")
public String usergetAll(Model model) {
List<NewsDetail> temp6 = allService.getAllView();
System.out.println("查询结果: " + temp6); // 检查日志输出
model.addAttribute("temp7", temp6);
return "View_All_News"; // 返回视图名称(如 expenditure-list.html)
}
//============================================================
@GetMapping("/Edit_News")
public String detail1(@RequestParam("title") String title,
Model model) {
List<NewsDetail> detail =allService.detail(title);
System.out.println("查询结果: " + detail); // 检查日志输出
model.addAttribute("temp8",detail);
return "Edit_News";
}
//=============================================================
@GetMapping("/Updata_News")
public String updateNews(
@RequestParam("title") String title,
@RequestParam("author") String author,
@RequestParam("type") int type,
@RequestParam("time") String time,
@RequestParam("content") String content,
@RequestParam("id") int id, // 必须传递id作为更新依据
Model model
) {
// 封装成对象
NewsDetail news = new NewsDetail();
news.setId(id);
news.setTitle(title);
news.setAuthor(author);
news.setType(type);
news.setTime(time);
news.setContent(content);
// 调用Service更新
int result = allService.updateNewsDetail(news);
if (result > 0) {
model.addAttribute("message", "更新成功");
} else {
model.addAttribute("message", "更新失败");
}
return "Success";
}
//============================================================
@GetMapping("/Add_News")
public String insertArticle2(){
return "Add_News";
}
@PostMapping("/Add_News")
public String insertArticle1(@RequestParam("title") String title,
@RequestParam("content") String content,
@RequestParam("author") String author,
@RequestParam("time") String time,
@RequestParam("type") int type,
Model model){
//验证传递的成功与否
int result =allService.insertArticle(title,content,author,time,type);
if (result > 0) {
model.addAttribute("message", "更新成功");
} else {
model.addAttribute("message", "更新失败");
}
return "Success";
}
// =====================================================
@GetMapping("/delete")
public String deleteByTitle1(@RequestParam("title") String title,
Model model ){
//验证删除成功与否
int result =allService.deleteByTitle(title);
if (result > 0) {
model.addAttribute("message", "删除成功");
} else {
model.addAttribute("message", "删除失败");
}
return "Success";
}
}
package org.example.controller;
import org.example.service.AdminService;
import org.example.service.impl.adminServiceimpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HealthCheck {
@Autowired
private AdminService testService;
@GetMapping("/check")
public String check() {
return testService != null ? "OK" : "Missing Bean";
}
@Autowired
private ApplicationContext context;
@GetMapping("/checks")
public String check1() {
boolean exists = context.containsBeanDefinition("adminServiceimpl");
return "通过名称检查: " + exists + "<br/>通过类型检查: " + (testService != null ? "OK" : "Missing Bean");
}
@GetMapping("/checkd")
public String check2() {
// 获取根上下文
ApplicationContext rootContext = context.getParent();
boolean rootHasBean = rootContext.containsBean("adminServiceimpl");
boolean mvcHasBean = context.containsBean("adminServiceimpl");
return "根上下文包含Bean: " + rootHasBean + "<br/>" +
"MVC上下文包含Bean: " + mvcHasBean;
}
@GetMapping("/checkBeans")
public String checkBeans() {
// 获取根上下文
ApplicationContext rootContext = context.getParent();
// 检查根上下文是否包含 adminServiceimpl
boolean rootHasBean = rootContext.containsBean("adminServiceimpl");
// 检查子上下文是否包含 adminServiceimpl
boolean mvcHasBean = context.containsBean("adminServiceimpl");
return "根上下文包含 adminServiceimpl: " + rootHasBean + "<br/>" +
"子上下文包含 adminServiceimpl: " + mvcHasBean;
}
}
Add_News.jsp
<%--
Created by IntelliJ IDEA.
User: qingzhou
Date: 2025/4/20
Time: 16:52
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>添加新闻</title>
<link rel="stylesheet" type="text/css" href="../css/Add_News.css">
</head>
<body>
<jsp:include page="Success.jsp"/>
<form action="Add_News" method="post">
<table align="center">
<tr>
<!-- 文本输入框 -->
<td>新闻标题</td>
<td><input type="text" name="title"></td>
</tr>
<tr>
<!-- 文本输入框 -->
<td>新闻内容</td>
<td><input type="text" name="content"></td>
</tr>
<tr>
<!-- 文本输入框 -->
<td>新闻类型</td>
<td><textarea name="type" cols="35" rows="15"></textarea></td>
</tr>
<tr>
<!-- 文本输入框 -->
<td>新闻作者</td>
<td><input type="text" name="author"></td>
</tr>
<tr>
<!-- 文本输入框 -->
<td>更新时间</td>
<td><input type="text" name="time"></td>
</tr>
<tr>
<td>操作</td>
<td><input type="submit" value="添加">
<!-- 重置按钮 -->
<input type="reset" value="取消">
</td></tr>
</table>
</form>
</body>
</html>
/* 让表格水平居中 */
table {
margin: 0 auto;
}
/* 设置文本输入框的宽度 */
input[type="text"] {
width: 300px;
}
/* 设置文本域的列数和行数 */
textarea {
cols: 35;
rows: 15;
}
Edit_News.jsp
<%--
Created by IntelliJ IDEA.
User: qingzhou
Date: 2025/4/20
Time: 15:54
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>编辑新闻</title>
<link rel="stylesheet" type="text/css" href="../css/Edit_News.css">
</head>
<body>
<h3>数据是否为空:${not empty temp8}</h3>
<form action="Updata_News" method="get">
<table class="res-table" style="margin: auto" >
<!-- //获取后端传来的值 -->
<c:forEach items="${temp8}" var="temp2">
<tr>
<td>新闻ID</td>
<td><input type="text" name="id" value="${temp2.id}"></td>
</tr>
<tr>
<td>新闻标题</td>
<td><input type="text" name="title" value="${temp2.title}"></td>
</tr>
<tr>
<td>新闻作者</td>
<td><input type="text" name="author" value="${temp2.author}"></td>
</tr>
<tr>
<td>新闻分类</td>
<td><input type="text" name="type" value="${temp2.type}"></td>
</tr>
<tr>
<td>发布时间</td>
<td><input type="text" name="time" value="${temp2.time}"></td>
</tr>
<tr>
<td>新闻内容</td>
<td><textarea name="content" cols="35" rows="15">${temp2.content}</textarea></td>
</tr>
</c:forEach>
<tr>
<td>操作</td>
<td>
<input type="submit" value="更新">
</td>
</tr>
</table>
</form>
</body>
</html>
login.jsp
<%--
Created by IntelliJ IDEA.
User: qingzhou
Date: 2025/4/19
Time: 14:58
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page isELIgnored="false" %>
<html>
<head>
<title>登录</title>
<link rel="stylesheet" type="text/css" href="../css/login.css">
</head>.
<body>
<form action="login" method="post">
<div class="box">
<h2>登录</h2>
<div class="ch1">
<label>账号</label>
<input type="text" class="text" name="adminname"/>
</div>
<div class="ch2">
<label>密码</label>
<input type="password" class="password" name="adminpass"/>${errorMsg}
</div>
<div class="ch">
<input type="submit" value="提交"> <input type="reset" value="重置">
<!-- type="submit"一定要写submit!!!!! -->
</div>
</div>
</form>
</body>
</html>
body {
background-color: pink;
}
.box {
text-align: center;
}
News_Center_File_List.jsp
<%--
Created by IntelliJ IDEA.
User: qingzhou
Date: 2025/4/20
Time: 9:59
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>新闻中心文件列表</title>
<link rel="stylesheet" type="text/css" href="../css/News_Center_File_List.css">
</head>
<body>
<jsp:include page="News_Center_Homepage.jsp"/>
<h3>数据是否为空:${not empty temp}</h3>
<table border="1">
<tr>
<th>ID</th>
<th>Title</th>
<th>Author</th>
<th>Time</th>
<th>Type</th>
</tr>
<c:forEach items="${temp}" var="news">
<tr>
<td>${news.id}</td>
<td>
<!-- 构造带参数的URL -->
<a href="<c:url value='/detail'>
<c:param name="title" value="${news.title}"/>
</c:url>">
${news.title}
</a>
</td>
<td>${news.author}</td>
<td>${news.time}</td>
<td>${news.type}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
table {
margin: 0 auto; /* 这行代码可以让块级元素(表格在这里属于块级元素)在水平方向上居中,即左右外边距自动分配,从而实现表格在页面中水平居中 */
}
News_Center_Homepage.jsp
<%--
Created by IntelliJ IDEA.
User: qingzhou
Date: 2025/4/19
Time: 15:02
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>新闻管理系统</title>
<link rel="stylesheet" type="text/css" href="../css/News_Center_Homepage.css">
</head>
<body>
<h1>新闻管理系统</h1>
<div>
<a class="" href="News_Center_File_List">所有新闻</a>
<a class="" href="Serach">搜索新闻</a>
<a class="" href="login">后台管理</a>
</div>
</body>
</html>
h1
{text-align:center;
color:orange}
div{
margin:0 auto;
text-align:center;
}
News_Details.jsp
<%--
Created by IntelliJ IDEA.
User: qingzhou
Date: 2025/4/20
Time: 10:56
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>新闻详细信息</title>
<link rel="stylesheet" type="text/css" href="../css/News_Details.css">
</head>
<body>
<jsp:include page="News_Center_Homepage.jsp"/>
<h3>数据是否为空:${not empty temp3}</h3>
<table style="text-align:center">
<!-- //request.setAttribute方法,将数组赋值给temp,注意setAttribute两个参数 键值对 -->
<c:forEach items="${temp3}" var="temp4">
<tr>
<td>新闻标题</td>
<td>${temp4.title}</td>
</tr>
<tr>
<td>新闻类型</td>
<td>${temp4.type}</td>
</tr>
<tr>
<td>新闻作者</td>
<td>${temp4.author}</td>
</tr>
<tr>
<td>新闻内容</td>
<td>${temp4.content}</td>
</tr>
<tr>
<td>发布时间</td>
<td>${temp4.time}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
table {
margin: 0 auto; /* 这行代码可以让块级元素(表格在这里属于块级元素)在水平方向上居中,即左右外边距自动分配,从而实现表格在页面中水平居中 */
}
News_Serach.jsp
<%--
Created by IntelliJ IDEA.
User: qingzhou
Date: 2025/4/19
Time: 15:05
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>新闻搜索</title>
<link rel="stylesheet" type="text/css" href="../css/News_Serach.css">
</head>
<body>
<form action="Serach" method="post">
关键字:<input type="text" name="title">
<input type="submit" value="提交">
</form>
<!-- 使用session将param获取的title存储,然后用setAttribute -->
<p>您搜索的关键字是:${sessionScope.keyword}</p><br>
<p>搜索结果如下:</p>
<table border="1" style="text-align:center">
<tr>
<th>新闻标题</th>
<th>作者</th>
<th>发布时间</th>
</tr>
<!-- //request.setAttribute方法,将数组赋值给temp,注意setAttribute两个参数 键值对 -->
<c:forEach items="${temp}" var="news">
<tr>
<td>
<!-- 构造带参数的URL -->
<a href="<c:url value='/detail'>
<c:param name="title" value="${news.title}"/>
</c:url>">
${news.title}
</a>
</td>
<td>${news.author}</td>
<td>${news.time}</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
table {
margin: 0 auto; /* 这行代码可以让块级元素(表格在这里属于块级元素)在水平方向上居中,即左右外边距自动分配,从而实现表格在页面中水平居中 */
}
Success.jsp
<%--
Created by IntelliJ IDEA.
User: qingzhou
Date: 2025/4/20
Time: 9:41
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page isELIgnored="false" %>
<html>
<head>
<title>后台管理系统</title>
<link rel="stylesheet" type="text/css" href="../css/Success.css">
</head>
<body>
<div class='1' >
<a href="View_All_News">所有新闻</a>
<a href="Add_News">添加新闻</a>
<a href="login">系统登录</a>
<a href="index">新闻主页</a>
<p style="text-align: center;">${message}</p>
</div>
</body>
</html>
h1
{text-align:center;
color:orange}
div{
margin:0 auto;
text-align:center;
}
View_All_News.jsp
<%--
Created by IntelliJ IDEA.
User: qingzhou
Date: 2025/4/20
Time: 11:58
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>所有新闻列表</title>
<link rel="stylesheet" type="text/css" href="../css/View_All_News.css">
</head>
<body>
<jsp:include page="Success.jsp"/>
<table class="res-table" style="margin: auto">
<caption>所有新闻列表</caption>
<tr class="res-tr">
<td>新闻标题</td>
<td>新闻作者</td>
<td>新闻分类</td>
<td>发布时间</td>
<td>是否编辑</td>
<td>是否移除</td>
</tr>
<!-- //表达式语言 用于遍历 -->
<c:forEach items="${temp7}" var="temp">
<tr>
<td>
<!-- 构造带参数的URL -->
<a href="<c:url value='/detail'>
<c:param name="title" value="${temp.title}"/>
</c:url>">
${temp.title}
</a>
</td>
<td>${temp.author}</td>
<td>${temp.type}</td>
<td>${temp.time}</td>
<td>
<form action="Edit_News" method="get">
<input type="hidden" name="title" value="${temp.title}">
<!-- 使用hidden参数 在request中携带参数title -->
<input type="submit" value="编辑">
</form>
</td>
<td>
<form action="delete" method="get">
<input type="hidden" name="title" value="${temp.title}">
<input type="submit" value="删除">
</form>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
/* 使表格水平居中 */
.res-table {
margin: 0 auto;
border-collapse: collapse; /* 合并表格边框 */
}
/* 表格单元格内文字水平和垂直居中 */
.res-table td {
text-align: center;
vertical-align: middle;
padding: 8px 12px; /* 可选:设置单元格内边距,使内容看起来更舒适 */
}
/* 表头文字加粗(可选) */
.res-tr td {
font-weight: bold;
}
完毕
有读不懂的可以跳转
jsp javabean servlet mysql 新闻管理系统_jsp+servlet+mysql新闻管理-CSDN博客
这边逻辑更顺畅