SSM(spring+springmvc+mybatis)实战:新闻发布管理系统2

68 篇文章 0 订阅
40 篇文章 0 订阅

新建maven项目

 

 

 数据库

drop table if exists s_role;
create table s_role(
	roleId int primary key comment '角色ID',
	roleName varchar(20) not null comment '角色名'
) comment '角色表';
insert into s_role values(1,'管理员');
insert into s_role values(2,'信息员');

drop table if exists s_user;
create table s_user(
	userId int auto_increment primary key comment '用户ID',
	userName varchar(30) not null comment '用户姓名',
	loginName varchar(30) not null comment '登录账号',
	userPwd varchar(30) not null comment '密码',
	tel varchar(20) comment '电话',
	registerTime timestamp default CURRENT_TIMESTAMP comment '注册日期',
	status char(1) not null comment '注册状态,1未启用,2已启用,3被禁用',
	roleId int not null comment '角色ID --foreign key(roleId) references s_role(roleId)'
) comment '用户表';
insert into s_user values (null,'无嗔','admin','1234','13300000000','2020-01-01','2',1);
insert into s_user values (null,'无贪','user1','1234','13800000000','2020-01-01','2',2);

drop table if exists s_category;
create table s_category(
	categoryId int primary key comment '类别ID',
	categoryName varchar(20) not null comment '类别名称'
) comment '新闻类别表';
insert into s_category values (1,'今日头条');
insert into s_category values (2,'综合资讯');
insert into s_category values (3,'国内新闻');
insert into s_category values (4,'国际新闻');

drop table if exists s_news;
create table s_news(
		newsId int auto_increment primary key comment '新闻ID',
		title varchar(60) not null comment '新闻标题',
		contentTitle varchar(120) not null comment '新闻内容标题',
		titlePicUrl varchar(120) comment '标题图路径',
		content text not null comment '新闻内容',
		contentAbstract varchar(300) comment '内容摘要',
		keywords varchar(100) comment '关键词',
		author varchar(30) not null comment '作者来源',
		publishTime timestamp default CURRENT_TIMESTAMP comment '发布时间',
		clicks int comment '浏览次数',
		publishStatus char(1) not null comment '发布状态,1发布,2撤销',
		categoryId int not null comment '类别id --foreign key(categoryId) references s_category(categoryId)',
		userId int not null comment '用户id --foreign key(userId) references s_user(userId)'
) comment '新闻表';
insert into s_news values (null,'新闻标题','内容标题','路径','新闻内容','内容摘要','关键词','作者','2020-01-01',999,'1',3,1);

导入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.shrimpking</groupId>
    <artifactId>springtest14</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>t01</module>
        <module>t02-newspublish</module>
        <module>t03</module>
    </modules>

    <dependencies>
        <dependency>
            <groupId>aopalliance</groupId>
            <artifactId>aopalliance</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.2</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version> 1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.3</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.2.4</version>
        </dependency>
        <dependency>
            <groupId>ognl</groupId>
            <artifactId>ognl</artifactId>
            <version>3.1.12</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.22</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>2.1.1</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.8</version>
        </dependency>
        <dependency>
            <groupId>org.apache.taglibs</groupId>
            <artifactId>taglibs-standard-impl</artifactId>
            <version>1.2.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.taglibs</groupId>
            <artifactId>taglibs-standard-spec</artifactId>
            <version>1.2.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>
</project>

配置文件

db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimeZone=UTC
jdbc.username=root
jdbc.password=mysql123
jdbc.maxTotal=30
jdbc.maxIdle=10
jdbc.initialSize=5

log4j.properties

log4j.rootLogger=ERROR,stdout
log4j.logger.com.shrimpking=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

applicationContext.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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!-- 读取db.properties   -->
    <context:property-placeholder location="classpath:db.properties"/>
    <!-- dbcp数据源   -->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="maxTotal" value="${jdbc.maxTotal}"/>
        <property name="maxIdle" value="${jdbc.maxIdle}"/>
        <property name="initialSize" value="${jdbc.initialSize}"/>
    </bean>
    <!--事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- 通知   -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="create*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.shrimpking.service.*.*(..))"/>
    </aop:config>
    <!-- 开启事务注解   -->
<!--    <tx:annotation-driven transaction-manager="transactionManager"/>-->
    <!--配置mybatis工厂-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>
    <!-- 配置mapper扫描器   -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.shrimpking.mapper"/>
    </bean>
    <!-- 扫描service   -->
    <context:component-scan base-package="com.shrimpking.service"/>
</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>

    <!--  起别名  -->
    <typeAliases>
        <package name="com.shrimpking.pojo"/>
    </typeAliases>

</configuration>

springmvc-config.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: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.xsd">

    <!-- 指定需要扫描的包   -->
    <context:component-scan base-package="com.shrimpking.controller"/>
    <!-- 配置注解驱动  -->
    <mvc:annotation-driven/>
    <!-- 静态资源放行   -->
    <mvc:resources mapping="/js/**" location="/WEB-INF/js/"/>
    <mvc:resources mapping="/css/**" location="/WEB-INF/css/"/>
    <mvc:resources mapping="/images/**" location="/WEB-INF/images/"/>
    <mvc:interceptors>
        <mvc:interceptor>
            <!-- 配置拦截器的生效路径           -->
            <mvc:mapping path="/**"/>
            <mvc:exclude-mapping path="/getIndex"/>
            <mvc:exclude-mapping path="/findNewsByCategoryIdPage"/>
            <mvc:exclude-mapping path="/findFrontNewsByNewsId"/>
            <bean class="com.shrimpking.interceptor.LoginInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>
    <!-- 视图解析器   -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

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">

    <!-- 配置加载spring文件的监听器   -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 编码过滤器,解决中文乱码   -->
    <filter>
        <filter-name>encoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- 配置前端过滤器   -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-config.xml</param-value>
        </init-param>
        <!-- 服务器启动时立即加载springmvc配置       -->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!-- /表示拦截所有请求,jsp除外       -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

代码

pojo实体类

User.java

package com.shrimpking.pojo;

import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/7/17 11:24
 * 用户类
 */
public class User
{
    private Integer userId;
    private String userName;
    private String loginName;
    private String userPwd;
    private String tel;
    //注册或修改用户时间
    private Date registerTime;
    //用户状态 ,1未启用,2启用,3被禁用
    private String status;
    private Integer roleId;
    private String roleName;

    public Integer getUserId()
    {
        return userId;
    }

    public void setUserId(Integer userId)
    {
        this.userId = userId;
    }

    public String getUserName()
    {
        return userName;
    }

    public void setUserName(String userName)
    {
        this.userName = userName;
    }

    public String getLoginName()
    {
        return loginName;
    }

    public void setLoginName(String loginName)
    {
        this.loginName = loginName;
    }

    public String getUserPwd()
    {
        return userPwd;
    }

    public void setUserPwd(String userPwd)
    {
        this.userPwd = userPwd;
    }

    public String getTel()
    {
        return tel;
    }

    public void setTel(String tel)
    {
        this.tel = tel;
    }

    public Date getRegisterTime()
    {
        return registerTime;
    }

    public void setRegisterTime(Date registerTime)
    {
        this.registerTime = registerTime;
    }

    public String getStatus()
    {
        return status;
    }

    public void setStatus(String status)
    {
        this.status = status;
    }

    public Integer getRoleId()
    {
        return roleId;
    }

    public void setRoleId(Integer roleId)
    {
        this.roleId = roleId;
    }

    public String getRoleName()
    {
        return roleName;
    }

    public void setRoleName(String roleName)
    {
        this.roleName = roleName;
    }

    @Override
    public String toString()
    {
        return "User{" + "userId=" + userId + ", userName='" + userName + '\'' + ", loginName='" + loginName + '\'' + ", userPwd='" + userPwd + '\'' + ", tel='" + tel + '\'' + ", registerTime=" + registerTime + ", status='" + status + '\'' + ", roleId=" + roleId + ", roleName='" + roleName + '\'' + '}';
    }
}

Role.java

package com.shrimpking.pojo;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/7/17 11:24
 * 角色类
 */
public class Role
{
    private Integer roleId;
    private String roleName;
    private List<User> userList;

    public Integer getRoleId()
    {
        return roleId;
    }

    public void setRoleId(Integer roleId)
    {
        this.roleId = roleId;
    }

    public String getRoleName()
    {
        return roleName;
    }

    public void setRoleName(String roleName)
    {
        this.roleName = roleName;
    }

    public List<User> getUserList()
    {
        return userList;
    }

    public void setUserList(List<User> userList)
    {
        this.userList = userList;
    }

    @Override
    public String toString()
    {
        return "Role{" + "roleId=" + roleId + ", roleName='" + roleName + '\'' + ", userList=" + userList + '}';
    }
}

Category.java

package com.shrimpking.pojo;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/7/18 9:52
 * 新闻类别实体类
 */
public class Category
{
    private Integer categoryId;
    private String categoryName;

    public Integer getCategoryId()
    {
        return categoryId;
    }

    public void setCategoryId(Integer categoryId)
    {
        this.categoryId = categoryId;
    }

    public String getCategoryName()
    {
        return categoryName;
    }

    public void setCategoryName(String categoryName)
    {
        this.categoryName = categoryName;
    }

    @Override
    public String toString()
    {
        return "Category{" + "categoryId=" + categoryId + ", categoryName='" + categoryName + '\'' + '}';
    }
}

News.java

package com.shrimpking.pojo;

import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/7/18 9:54
 * 新闻实体类
 */
public class News
{
    private Integer newsId;
    private String title;
    private String contentTitle;
    private String titlePicUrl;
    private String content;
    private String contentAbstract;
    private String keywords;
    private String author;
    private Date publishTime;
    private Integer clicks;
    //发布状态,1发布,2撤稿
    private String publishStatus;
    private Integer categoryId;
    //新闻类别名称,为了方便列表显示,增加此属性,
    private String categoryName;
    private Integer userId;

    public Integer getNewsId()
    {
        return newsId;
    }

    public void setNewsId(Integer newsId)
    {
        this.newsId = newsId;
    }

    public String getTitle()
    {
        return title;
    }

    public void setTitle(String title)
    {
        this.title = title;
    }

    public String getContentTitle()
    {
        return contentTitle;
    }

    public void setContentTitle(String contentTitle)
    {
        this.contentTitle = contentTitle;
    }

    public String getTitlePicUrl()
    {
        return titlePicUrl;
    }

    public void setTitlePicUrl(String titlePicUrl)
    {
        this.titlePicUrl = titlePicUrl;
    }

    public String getContent()
    {
        return content;
    }

    public void setContent(String content)
    {
        this.content = content;
    }

    public String getContentAbstract()
    {
        return contentAbstract;
    }

    public void setContentAbstract(String contentAbstract)
    {
        this.contentAbstract = contentAbstract;
    }

    public String getKeywords()
    {
        return keywords;
    }

    public void setKeywords(String keywords)
    {
        this.keywords = keywords;
    }

    public String getAuthor()
    {
        return author;
    }

    public void setAuthor(String author)
    {
        this.author = author;
    }

    public Date getPublishTime()
    {
        return publishTime;
    }

    public void setPublishTime(Date publishTime)
    {
        this.publishTime = publishTime;
    }

    public Integer getClicks()
    {
        return clicks;
    }

    public void setClicks(Integer clicks)
    {
        this.clicks = clicks;
    }

    public String getPublishStatus()
    {
        return publishStatus;
    }

    public void setPublishStatus(String publishStatus)
    {
        this.publishStatus = publishStatus;
    }

    public Integer getCategoryId()
    {
        return categoryId;
    }

    public void setCategoryId(Integer categoryId)
    {
        this.categoryId = categoryId;
    }

    public String getCategoryName()
    {
        return categoryName;
    }

    public void setCategoryName(String categoryName)
    {
        this.categoryName = categoryName;
    }

    public Integer getUserId()
    {
        return userId;
    }

    public void setUserId(Integer userId)
    {
        this.userId = userId;
    }

    @Override
    public String toString()
    {
        return "News{" + "newsId=" + newsId + ", title='" + title + '\'' + ", contentTitle='" + contentTitle + '\'' + ", titlePicUrl='" + titlePicUrl + '\'' + ", content='" + content + '\'' + ", contentAbstract='" + contentAbstract + '\'' + ", keywords='" + keywords + '\'' + ", author='" + author + '\'' + ", publishTime=" + publishTime + ", clicks=" + clicks + ", publishStatus='" + publishStatus + '\'' + ", categoryId=" + categoryId + ", categoryName='" + categoryName + '\'' + ", userId=" + userId + '}';
    }
}

Mapper层

UserMapper.java

package com.shrimpking.mapper;

import com.shrimpking.pojo.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/7/17 11:30
 */
public interface UserMapper
{
    //查询所有用户
    public List<User> selectUserList(@Param("keywords") String keywords, @Param("userListRoleId") Integer userListRoleId);

    //通过账号和密码查询用户
    public User findUser(@Param("loginName") String loginName, @Param("password") String password);

    //通过用户id查询用户
    public User getUserByUserId(Integer userId);

    //通过用户登录名查询用户,用于判断用户名是否存在
    public User getUserByLoginName(String loginName);

    //添加用户
    public int addUser(User user);

    //更新用户
    public int updateUser(User user);

    //删除用户
    public int deleteUser(Integer userId);

    //设置用户状态 1未启用,2启用,3禁用
    public int setUserStatus(User user);

}

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.shrimpking.mapper.UserMapper">

    <!--  查询所有用户  -->
    <select id="selectUserList" parameterType="string" resultType="user">
        select
        u.userId,
        u.userName,
        u.loginName,
        u.userPwd,
        u.tel,
        u.registerTime,
        u.status,
        u.roleId,
        r.roleName
        from s_user as u,s_role as r
        where
            u.roleId = r.roleId
            <if test="keywords != null and keywords != ''">
                and (
                    u.userName like concat('%',#{keywords},'%') or
                    u.loginName like concat('%',#{keywords},'%')
                )
            </if>
            <if test="userListRoleId != null and userListRoleId != ''">
                and (u.roleId=#{userListRoleId})
            </if>

        order by u.registerTime desc
    </select>

    <!-- 公共字段   -->
    <sql id="common_sql">
      select userId,userName,loginName,userPwd,tel,registerTime,status,roleId
      from s_user
    </sql>

    <!-- 通过账号和密码查询用户   -->
    <select id="findUser" parameterType="string" resultType="user">
        <include refid="common_sql"/>
        where loginName=#{loginName} and userPwd=#{password} limit 0,1
    </select>

    <!--通过用户id查询用户-->
    <select id="getUserByUserId" parameterType="integer" resultType="user">
        <include refid="common_sql"/>
        where userId=#{userId}
    </select>

    <!-- 通过用户登录名查询用户,用于判断用户名是否存在   -->
    <select id="getUserByLoginName" parameterType="string" resultType="user">
        <include refid="common_sql"/>
        where loginName=#{loginName} limit 0,1
    </select>

    <!-- 添加用户   -->
    <insert id="addUser" parameterType="user">
        insert into s_user(
            userName,
            loginName,
            userPwd,
            tel,
            registerTime,
            status,
            roleId
        ) values (
            #{userName},
            #{loginName},
            #{userPwd},
            #{tel},
            #{registerTime},
            #{status},
            #{roleId}
        )
    </insert>

    <!-- 更新用户   -->
    <update id="updateUser" parameterType="user">
        update s_user
        <set>
            registerTime=#{registerTime},
            status=#{status},
            <if test="userName != null and userName !=''">
                userName=#{userName},
            </if>
            <if test="userPwd != null and userPwd !=''">
                userPwd=#{userPwd},
            </if>
            <if test="tel != null and tel != ''">
                tel=#{tel},
            </if>
            <if test="roleId != null and roleId != ''">
                roleId=#{roleId},
            </if>
        </set>
        where userId=#{userId}
    </update>

    <!-- 删除用户   -->
    <delete id="deleteUser" parameterType="integer">
        delete from s_user where userId=#{userId}
    </delete>

    <!-- 设置用户状态 1未启用,2启用,3禁用  -->
    <update id="setUserStatus" parameterType="user">
        update s_user set status=#{status} where userId=#{userId}
    </update>
</mapper>

RoleMapper.java

package com.shrimpking.mapper;

import com.shrimpking.pojo.Role;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/7/17 11:29
 */
public interface RoleMapper
{
    //获取所有角色信息 角色列表
    public List<Role> selectRoleList();
}

RoleMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.shrimpking.mapper.RoleMapper">

    <!--  获取所有角色信息 角色列表  -->
    <select id="selectRoleList" resultType="role">
        select roleId,roleName from s_role
    </select>

</mapper>

NewsMapper.java

package com.shrimpking.mapper;

import com.shrimpking.pojo.News;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/7/18 10:07
 */
public interface NewsMapper
{
    //获取当前类别的新闻数量
    public int selectNewsCount(
            @Param("keywords") String keywords,
            @Param("newsListCategoryId") Integer newsListCategoryId
    );

    //获取当前类别的新闻列表
    public List<News> selectNewsList(
            @Param("keywords") String keywords,
            @Param("newsListCategoryId") Integer newsListCategoryId,
            @Param("startRows") Integer startRows,
            @Param("pageSize") Integer pageSize
    );

    //根据新闻id查询
    public News selectNewsByNewsId(Integer newsId);

    //添加新闻
    public int addNews(News news);

    //更新新闻
    public int updateNews(News news);

    //删除新闻
    public int deleteNews(Integer newsId);

    //设置新闻状态,1发布,2撤稿
    public int setNewsStatus(News news);
}

NewsMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.shrimpking.mapper.NewsMapper">

    <!-- 获取当前类别的新闻数量   -->
    <select id="selectNewsCount" parameterType="string"
            resultType="integer">
        select count(*) from s_news as n
        <where>
            <if test="keywords != null and keywords !=''">
                and (
                    n.title like concat('%',#{keywords},'%') or
                    n.keywords like concat('%',#{keywords},'%')
                )
            </if>
            <if test="newsListCategoryId != null and newsListCategoryId !=''">
                and (n.categoryId=#{newsListCategoryId})
            </if>
        </where>
    </select>

    <sql id="common_sql">
        select
        n.newsId,
        n.title,
        n.contentTitle,
        n.titlePicUrl,
        n.content,
        n.contentAbstract,
        n.keywords,
        n.author,
        n.publishTime,
        n.clicks,
        n.publishStatus,
        n.categoryId,
        n.userId,
        c.categoryName
        from s_news n,s_category c
        where n.categoryId = c.categoryId
    </sql>

    <!-- 获取当前类别的新闻列表   -->
    <select id="selectNewsList" parameterType="string"
            resultType="news">
        <include refid="common_sql"/>
        <if test="keywords != null and keywords != ''">
            and (
                n.title like concat('%',#{keywords},'%') or
                n.keyword like concat('%',#{keywords},'%')
            )
        </if>
        <if test="newsListCategoryId != null and newsListCategoryId !=''">
            and (n.categoryId=#{newsListCategoryId})
        </if>
        order by n.publishTime desc
    </select>

    <!--据新闻id查询-->
    <select id="selectNewsByNewsId" parameterType="integer"
            resultType="news">
        <include refid="common_sql"/>
        and n.newsId=#{newsId}
    </select>

    <!-- 添加新闻   -->
    <insert id="addNews" parameterType="news">
        insert into s_news(
            title,
            contentTitle,
            titlePicUrl,
            content,
            contentAbstract,
            keywords,
            author,
            publishTime,
            publishStatus,
            categoryId,
            userId
        ) values (
            #{title},
            #{contentTitle},
            #{titlePicUrl},
            #{content},
            #{contentAbstract},
            #{keywords},
            #{author},
            #{publishTime},
            #{publishStatus},
            #{categoryId},
            #{userId}
        )
    </insert>

    <!-- 更新新闻   -->
    <update id="updateNews" parameterType="news">
        update s_news
        <set>
            publishTime=#{publishTime},
            publishStatus=#{publishStatus},
            title=#{title},
            contentTitle=#{contentTitle},
            titlePicUrl=#{titlePicUrl},
            content=#{content},
            contentAbstract=#{contentAbstract},
            keywords=#{keywords},
            author=#{author},
            categoryId=#{categoryId},
            userId=#{userId}
        </set>
        where newsId=#{newsId}
    </update>

    <!-- 删除新闻   -->
    <delete id="deleteNews" parameterType="integer">
        delete from s_news where newsId=#{newsId}
    </delete>

    <!--  设置新闻状态,1发布,2撤稿  -->
    <update id="setNewsStatus" parameterType="news">
        update s_news set publishStatus=#{publishStatus} where newsId=#{newsId}
    </update>

</mapper>

CategoryMapper.java

package com.shrimpking.mapper;

import com.shrimpking.pojo.Category;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/7/18 10:05
 */
public interface CategoryMapper
{
    //查询所有新闻类别
    public List<Category> selectCategoryList();

    //根据类别id查询新闻类别
    public Category selectCategoryById(Integer categoryId);
}

CategoryMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.shrimpking.mapper.CategoryMapper">

    <!-- 查询所有新闻类别   -->
    <select id="selectCategoryList" resultType="category">
        select categoryId,categoryName from s_category
    </select>

    <!-- 根据类别id查询新闻类别   -->
    <select id="selectCategoryById" parameterType="integer"
            resultType="category">
        select categoryId,categoryName from s_category where categoryId=#{categoryId}
    </select>

</mapper>

service层

UserService.java

package com.shrimpking.service;

import com.shrimpking.pojo.User;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/7/17 12:23
 * 用户service层接口
 */
public interface UserService
{
    public List<User> getUserList(String keywords, Integer userListRoleId);
    public User getUser(String loginName, String password);
    public User getUserByUserId(Integer userId);
    public User getUserByLoginName(String loginName);
    public int addUser(User user);
    public int editUser(User user);
    public int deleteUser(Integer userId);
    public int setUserStatus(User user);
}

UserServiceImpl.java

package com.shrimpking.service.impl;

import com.shrimpking.mapper.UserMapper;
import com.shrimpking.pojo.User;
import com.shrimpking.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/7/17 12:31
 * 用户service接口实现类
 */
@Service
public class UserServiceImpl implements UserService
{
    //自动注入
    @Autowired
    private UserMapper userMapper;

    //查询所有用户
    @Override
    public List<User> getUserList(String keywords, Integer userListRoleId)
    {
        return userMapper.selectUserList(keywords,userListRoleId);
    }

    //通过用户名和密码查询用户
    @Override
    public User getUser(String loginName, String password)
    {
        return userMapper.findUser(loginName,password);
    }

    //通过id查询用户
    @Override
    public User getUserByUserId(Integer userId)
    {
        return userMapper.getUserByUserId(userId);
    }

    //通过登录名查询用户
    @Override
    public User getUserByLoginName(String loginName)
    {
        return userMapper.getUserByLoginName(loginName);
    }

    //添加用户
    @Override
    public int addUser(User user)
    {
        return userMapper.addUser(user);
    }

    //更新用户
    @Override
    public int editUser(User user)
    {
        return userMapper.updateUser(user);
    }

    //删除用户
    @Override
    public int deleteUser(Integer userId)
    {
        return userMapper.deleteUser(userId);
    }

    //设置用户状态
    @Override
    public int setUserStatus(User user)
    {
        return userMapper.setUserStatus(user);
    }
}

RoleService.java

package com.shrimpking.service;

import com.shrimpking.pojo.Role;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/7/17 12:21
 * 角色service层接口
 */
public interface RoleService
{
    //获取角色列表
    public List<Role> getRoleList();
}

RoleServiceImpl.java

package com.shrimpking.service.impl;

import com.shrimpking.mapper.RoleMapper;
import com.shrimpking.pojo.Role;
import com.shrimpking.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/7/17 12:27
 * 角色service接口实现类
 */
@Service
public class RoleServiceImpl implements RoleService
{
    //自动注入
    @Autowired
    private RoleMapper roleMapper;

    //获取角色列表
    @Override
    public List<Role> getRoleList()
    {
        List<Role> roleList = roleMapper.selectRoleList();
        return roleList;
    }
}

NewsService.java

package com.shrimpking.service;

import com.shrimpking.pojo.News;
import com.shrimpking.utils.PageBean;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/7/18 11:09
 */
public interface NewsService
{
    //获取当前类别的新闻列表
    public PageBean<News> getNewsByPage(
            String keywords,
            Integer newsListCategoryId,
            Integer currentPage,
            Integer pageSize
    );
    //根据新闻id查询
    public News getNewsByNewsId(Integer newsId);
    //添加新闻
    public int addNews(News news);
    //更新新闻
    public int editNews(News news);
    //删除新闻
    public int deleteNews(Integer newsId);
    //设置新闻状态,1发布,2撤稿
    public int setNewsStatus(News news);
}

NewsServiceImpl.java

package com.shrimpking.service.impl;

import com.shrimpking.mapper.NewsMapper;
import com.shrimpking.pojo.News;
import com.shrimpking.service.NewsService;
import com.shrimpking.utils.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/7/18 11:17
 */
@Service
public class NewsServiceImpl implements NewsService
{
    @Autowired
    private NewsMapper newsMapper;

    @Override
    public PageBean<News> getNewsByPage(String keywords, Integer newsListCategoryId, Integer currentPage, Integer pageSize)
    {
        //获取当前类别的新闻数量
        int count = newsMapper.selectNewsCount(keywords,newsListCategoryId);
        //求总页数
        int totalPage = (int) Math.ceil(count * 1.0 /pageSize);

        List<News> newsList = newsMapper.selectNewsList(keywords, newsListCategoryId, (currentPage-1)*pageSize, pageSize);

        PageBean<News> pageBean = new PageBean<>();
        pageBean.setCount(count);
        if(currentPage==0)
        {
            currentPage=1;
        }
        pageBean.setCurrentPage(currentPage);
        pageBean.setList(newsList);
        pageBean.setPageSize(pageSize);
        pageBean.setTotalPage(totalPage);
        return pageBean;
    }

    @Override
    public News getNewsByNewsId(Integer newsId)
    {
        return newsMapper.selectNewsByNewsId(newsId);
    }

    @Override
    public int addNews(News news)
    {
        return newsMapper.addNews(news);
    }

    @Override
    public int editNews(News news)
    {
        return newsMapper.updateNews(news);
    }

    @Override
    public int deleteNews(Integer newsId)
    {
        return newsMapper.deleteNews(newsId);
    }

    @Override
    public int setNewsStatus(News news)
    {
        return newsMapper.setNewsStatus(news);
    }
}

CategoryService.java

package com.shrimpking.service;

import com.shrimpking.pojo.Category;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/7/18 11:07
 */
public interface CategoryService
{
    //查询所有类别列表
    public List<Category> getCategoryList();
    //根据id查询
    public Category getCategoryById(Integer categoryId);
}

CategroyServiceImpl.java

package com.shrimpking.service.impl;

import com.shrimpking.mapper.CategoryMapper;
import com.shrimpking.pojo.Category;
import com.shrimpking.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/7/18 11:15
 */
@Service
public class CategoryServiceImpl implements CategoryService
{
    //自动注入
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> getCategoryList()
    {
        return categoryMapper.selectCategoryList();
    }

    @Override
    public Category getCategoryById(Integer categoryId)
    {
        return categoryMapper.selectCategoryById(categoryId);
    }
}

Controller层

UserController.java

package com.shrimpking.controller;

import com.shrimpking.pojo.Role;
import com.shrimpking.pojo.User;
import com.shrimpking.service.RoleService;
import com.shrimpking.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/7/17 12:42
 * 用户控制类
 */
@Controller
public class UserController
{
    //自动注入
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    //查询所有用户
    @RequestMapping("/findUserList")
    public String findUserList(String keywords, Integer userListRoleId, Model model)
    {
        //获取角色列表
        List<Role> roleList = roleService.getRoleList();
        model.addAttribute("roleList",roleList);
        //获取用户列表
        List<User> userList = userService.getUserList(keywords, userListRoleId);
        model.addAttribute("userList",userList);
        model.addAttribute("keywords",keywords);
        model.addAttribute("userListRoleId",userListRoleId);

        return "user/user_list";
    }

    //转向添加用户
    @RequestMapping("/toAddUser")
    public String toAddUser(Model model)
    {
        //获取角色列表,用户添加页面的下拉列表
        List<Role> roleList = roleService.getRoleList();
        model.addAttribute("roleList",roleList);
        return "user/add_user";
    }

    //判断登录账号是否存在
    @RequestMapping("/checkLoginName")
    @ResponseBody
    public User checkLoginName(@RequestBody User user)
    {
        User checkUser = userService.getUserByLoginName(user.getLoginName());
        if(checkUser != null)
        {
            //登录账号已存在
            return checkUser;
        }
        else
        {
            checkUser = new User();
            checkUser.setUserId(0);
            return checkUser;
        }
    }

    //添加用户
    @RequestMapping(value = "/addUser",method = RequestMethod.POST)
    public String addUser(User user,Model model)
    {
        //获取角色列表
        List<Role> roleList = roleService.getRoleList();
        model.addAttribute("roleList",roleList);
        model.addAttribute("user",user);
        //检查登录账号是否已存在
        User checkUser = userService.getUserByLoginName(user.getLoginName());
        if(checkUser != null)
        {
            //登录账号已存在,重新回到添加用户页面
            model.addAttribute("checkUserLoginNameMsg","登录账号已存在,请重新输入");
            return "user/add_user";
        }
        else
        {
            //登录账号可用
            Date date = new Date();
            user.setRegisterTime(date);
            //默认设置用户为2启用状态
            user.setStatus("2");
            int rows = userService.addUser(user);
            if(rows > 0)
            {
                //添加成功,转到用户列表页面
                return "redirect:findUserList";
            }
            else
            {
                //添加失败,重新回到添加用户页面
                return "user/add_user";
            }
        }

    }

    //转向修改用户页面
    @RequestMapping("/toEditUser")
    public String toEditUser(Integer userId,Model model)
    {
        User user = userService.getUserByUserId(userId);
        if(user != null)
        {
            model.addAttribute("user",user);
            List<Role> roleList = roleService.getRoleList();
            model.addAttribute("roleList",roleList);
            return "user/edit_user";
        }
        else
        {
            return "redirect:findUserList";
        }
    }

    //修改用户
    @RequestMapping(value = "/editUser",method = RequestMethod.POST)
    public String editUser(User user,Model model)
    {
        Date date = new Date();
        user.setRegisterTime(date);
        user.setStatus("2");
        int rows = userService.editUser(user);
        if(rows > 0)
        {
            return "redirect:findUserList";
        }
        else
        {
            List<Role> roleList = roleService.getRoleList();
            model.addAttribute("roleList",roleList);
            return "user/edit_user";
        }
    }

    //删除用户
    @RequestMapping("/deleteUser")
    @ResponseBody
    public User deleteUser(@RequestBody User user,Model model)
    {
        int rows = userService.deleteUser(user.getUserId());
        if(rows > 0)
        {
            return user;
        }
        else
        {
            //设置userId为0,表示失败
            user.setUserId(0);
            return user;
        }
    }

    //禁用用户
    @RequestMapping("/disableUser")
    @ResponseBody
    public User disableUser(@RequestBody User user,Model model)
    {
        int rows = userService.setUserStatus(user);
        if(rows > 0)
        {
            return user;
        }
        else
        {
            user.setUserId(0);
            return user;
        }
    }

    //启用用户
    @RequestMapping("/enableUser")
    @ResponseBody
    public User enableUser(@RequestBody User user,Model model)
    {
        int rows = userService.setUserStatus(user);
        if(rows > 0)
        {
            return  user;
        }
        else
        {
            user.setUserId(0);
            return user;
        }
    }

    //
    @RequestMapping("/toLogin")
    public String toLogin()
    {
        return "login";
    }

    //用户登录
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(String loginName, String password, Model model, HttpSession session)
    {
        User user = userService.getUser(loginName, password);
        if(user != null)
        {
            if(user.getStatus().equals("2"))
            {
                //用户被启用,可以登录后台
                session.setAttribute("login_user",user);
                return "main";
            }
            else
            {
                model.addAttribute("msg","账号未启用或被禁用");
                return "login";
            }
        }
        else
        {
            //账号或密码错误,不可以登录后台
            model.addAttribute("msg","账号或密码错误,请重新登录");
            return "login";
        }
    }

    //退出登录
    @RequestMapping("/logout")
    public String logout(HttpSession session)
    {
        //清空session
        session.invalidate();
        return "login";
    }
}

NewsController.java

package com.shrimpking.controller;

import com.shrimpking.pojo.Category;
import com.shrimpking.pojo.News;
import com.shrimpking.service.CategoryService;
import com.shrimpking.service.NewsService;
import com.shrimpking.utils.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/7/18 11:31
 * 新闻控制类
 */
@Controller
public class NewsController
{
    //自动注入
    @Autowired
    private NewsService newsService;
    //自动注入
    @Autowired
    private CategoryService categoryService;

    //查询新闻分页
    @RequestMapping("/findNewsByPage")
    public String findNewsByPage(
            String keywords,
            Integer newsListCategoryId,
            @RequestParam(defaultValue = "1") Integer currentPage,
            @RequestParam(defaultValue = "10") Integer pageSize,
            Model model
    )
    {
        //获取类别列表
        List<Category> categoryList = categoryService.getCategoryList();
        model.addAttribute("categoryList",categoryList);

        PageBean<News> pageBean = newsService.getNewsByPage(keywords, newsListCategoryId, currentPage, pageSize);
        model.addAttribute("pageBean",pageBean);
        model.addAttribute("keywords",keywords);
        model.addAttribute("newsListCategoryId",newsListCategoryId);
        model.addAttribute("currentPage",currentPage);
        model.addAttribute("pageSize",pageSize);
        return "news/news_list";
    }

    //设置新闻状态,publishStatus ,1发布,2撤稿
    @RequestMapping("/setNewsStatus")
    @ResponseBody
    public News setNewsStatus(@RequestBody News news,Model model)
    {
        int rows = newsService.setNewsStatus(news);
        if(rows > 0)
        {
            //成功
            return news;
        }
        else
        {
            //失败
            news.setNewsId(0);
            return news;
        }
    }

    //转向添加新闻
    @RequestMapping("/toAddNews")
    public String toAddNews(Model model)
    {
        //获取新闻类别列表
        List<Category> categoryList = categoryService.getCategoryList();
        model.addAttribute("categoryList",categoryList);
        return "news/add_news";
    }

    //添加新闻
    @RequestMapping(value = "/addNews",method = RequestMethod.POST)
    public String addNews(News news,Model model)
    {
        Date date = new Date();
        news.setPublishTime(date);
        //默认新闻为发布状态
        news.setPublishStatus("1");
        news.setUserId(1);
        for (int i = 0; i < 10; i++)
        {
            newsService.addNews(news);
        }
        int rows = newsService.addNews(news);
        if(rows > 0)
        {
            //添加成功,转向用户列表页面
            return "redirect:findNewsByPage";
        }
        else
        {
            //失败
            List<Category> categoryList = categoryService.getCategoryList();
            model.addAttribute("categoryList",categoryList);
            model.addAttribute("news",news);
            return "news/add_news";
        }
    }

    //修改新闻
    @RequestMapping(value = "/editNews",method = RequestMethod.POST)
    public String editNews(News news,Model model)
    {
        Date date = new Date();
        news.setPublishTime(date);
        //设置新闻状态,为发布
        news.setPublishStatus("1");
        news.setUserId(1);
        int rows = newsService.editNews(news);
        if(rows > 0)
        {
            //成功
            return "redirect:findNewsByPage";
        }
        else
        {
            //失败
            List<Category> categoryList = categoryService.getCategoryList();
            model.addAttribute("categoryList",categoryList);
            model.addAttribute("news",news);
            return "news/edit_news";
        }
    }

    //转向修改新闻页面
    @RequestMapping("/toEditNews")
    public String toEditNews(Integer newsId, Model model)
    {
        News news = newsService.getNewsByNewsId(newsId);
        if(news != null)
        {
            //获取类别列表
            List<Category> categoryList = categoryService.getCategoryList();
            model.addAttribute("categoryList",categoryList);
            model.addAttribute("news",news);
        }
        return "news/edit_news";
    }

    //删除新闻
    @RequestMapping("/delNews")
    @ResponseBody
    public News delNews(@RequestBody News news,Model model)
    {
        int rows = newsService.deleteNews(news.getNewsId());
        if(rows > 0)
        {
            //成功
            return news;
        }
        else
        {
            //失败
            news.setNewsId(0);
            return news;
        }
    }

    //根据新闻类别id查询新闻分页,用于前台首页
    @RequestMapping("/getIndex")
    public String getIndex(
            HttpServletRequest request,
            HttpServletResponse response,
            String keywords,
            Integer newsListCategoryId,
            @RequestParam(defaultValue = "1") Integer currentPage,
            @RequestParam(defaultValue = "10") Integer pageSize,
            Model model
    ) throws ServletException,IOException
    {
        //获取新闻类别为1的新闻分页
        PageBean<News> pb1 = newsService.getNewsByPage(keywords, 1, currentPage, pageSize);
        model.addAttribute("pb1",pb1);
        //获取欣慰类别为2的新闻分页
        PageBean<News> pb2 = newsService.getNewsByPage(keywords, 2, currentPage, pageSize);
        model.addAttribute("pb2",pb2);
        return "../../first";
    }

    //根据新闻类别id查询新闻分页,用户新闻列表页
    @RequestMapping("/findNewsByCategoryIdPage")
    public String findNewsByCategoryIdPage(
            HttpServletRequest request,
            HttpServletResponse response,
            String keywords,
            Integer newsListCategoryId,
            @RequestParam(defaultValue = "1") Integer currentPage,
            @RequestParam(defaultValue = "10") Integer pageSize,
            Model model
    )
    {
        //获取类别
        Category category = categoryService.getCategoryById(newsListCategoryId);
        model.addAttribute("category",category);

        PageBean<News> pb = newsService.getNewsByPage(keywords, newsListCategoryId, currentPage, pageSize);
        model.addAttribute("pb", pb);
        model.addAttribute("newsListCategoryId",newsListCategoryId);
        model.addAttribute("currentPage",currentPage);
        model.addAttribute("pageSize",pageSize);
        return "../../list";
    }

    //查询新闻,用于前台新闻内容页
    @RequestMapping("/findFrontNewsByNewsId")
    public String findFrontNewsByNewsId(Integer newsId,Model model)
    {
        News news = newsService.getNewsByNewsId(newsId);
        if(news != null)
        {
            model.addAttribute("news",news);
        }
        return "../../detail";
    }

}

Interceptor拦截器

LoginInterceptor.java

package com.shrimpking.interceptor;

import com.shrimpking.pojo.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/7/18 16:19
 */
public class LoginInterceptor implements HandlerInterceptor
{
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception
    {
        //获取请求的url
        String url = httpServletRequest.getRequestURI();
        if(url.indexOf("/login") >= 0)
        {
            return true;
        }
        if(url.indexOf("/toLogin") >= 0)
        {
            return true;
        }
        HttpSession session = httpServletRequest.getSession();
        User user = (User) session.getAttribute("login_user");
        //判断session中是否有用户数据,如果有,表示已登录,放行
        if(user != null)
        {
            return true;
        }
        httpServletRequest.setAttribute("msg","您还没有登录,请先登录");
        httpServletRequest.getRequestDispatcher("/toLogin").forward(httpServletRequest,httpServletResponse);

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception
    {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception
    {

    }
}

jsp页面

login.jsp

<%--
  Created by IntelliJ IDEA.
  User: user1
  Date: 2023/7/17
  Time: 15:28
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>login</title>
</head>
<body>
    <h3>用户登录</h3>
    <form action="${pageContext.request.contextPath}/login" method="post" onsubmit="return checkValue">
        <p>${msg}</p>
        <div>
            账号:<input type="text" name="loginName" id="loginName" placeholder="输入登录账号"><br>
            密码:<input type="password" name="password" id="password" placeholder="密码"><br>

            <button>登录</button>
        </div>
    </form>
    <script>
        function checkValue() {
            var str = document.getElementById("loginName").value;
            if (str.length < 1) {
                alert("请输入账号");
                document.getElementById("loginName").focus();
                return false;
            }
            str = document.getElementById("password").value;
            if (str.length < 1)
            {
                alert("请输入密码");
                document.getElementById("password").focus();
                return false;
            }
            return true;
        }
    </script>
</body>
</html>

main.jsp

<%--
  Created by IntelliJ IDEA.
  User: user1
  Date: 2023/7/17
  Time: 11:22
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h2><a href="${pageContext.request.contextPath}/logout">注销退出</a></h2>
    <p><a href="${pageContext.request.contextPath}/findUserList">用户列表</a></p>
    <p><a href="${pageContext.request.contextPath}/findNewsByPage">新闻列表</a></p>

</body>
</html>

user_list.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%--
  Created by IntelliJ IDEA.
  User: user1
  Date: 2023/7/17
  Time: 12:48
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="${pageContext.request.contextPath}/js/jQuery-3.4.1.js"></script>
</head>
<body>
    <div>
        <ul>
            <li><a href="${pageContext.request.contextPath}/toAddUser">添加用户</a></li>
            <li><a href="${pageContext.request.contextPath}/logout">注销退出</a></li>
        </ul>
    </div>
    <div>
        <form action="${pageContext.request.contextPath}/findUserList" method="post" id="userListForm" name="ff">
            <ul>
                <li>
                    <label for="keywords">搜索关键词</label>
                    <input type="text" name="keywords" id="keywords" placeholder="这里输入姓名或登录账号">
                </li>
                <li>
                    <label for="">角色:</label>
                    <select name="userListRoleId" id="userListRoleId">
<%--                        <option>--请选择--</option>--%>
                        <c:forEach items="${roleList}" var="r">
                            <option value="${r.roleId}"
                                    <c:if test="${r.roleId eq userListRoleId}">
                                        selected="selected"
                                    </c:if> >${r.roleName}</option>
                        </c:forEach>
                    </select>
                </li>
                <li>
                    <input type="submit" value="查询">
                </li>
            </ul>
        </form>
    </div>
    <div>
        <table border="1">
            <thead>
                <tr>
                    <th>用户姓名</th>
                    <th>登录账号</th>
                    <th>联系电话</th>
                    <th>注册时间</th>
                    <th>用户角色</th>
                    <th>审核状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <c:if test="${!empty userList}">
                    <c:forEach items="${userList}" var="user">
                        <tr>
                            <td>${user.userName}</td>
                            <td>${user.loginName}</td>
                            <td>${user.tel}</td>
                            <td><fmt:formatDate value="${user.registerTime}" pattern="yyyy-MM-dd HH:mm:ss"/></td>
                            <td>${user.roleName}</td>
                            <td>
                                <c:if test="${user.status== '2'}" var="flag">
                                    已启用
                                </c:if>
                                <c:if test="${not flag}">
                                    未启用或被禁用
                                </c:if>
                            </td>
                            <td>
                                <a href="${pageContext.request.contextPath}/toEditUser?userId=${user.userId}">修改</a>&nbsp;&nbsp;|
                                <c:if test="${user.loginName !='admin'}">
                                    <c:if test="${user.status == '2'}" var="status_flag">
                                        <a href="#" onclick="disableUser(${user.userId})">禁用</a>&nbsp;&nbsp;|
                                    </c:if>
                                    <c:if test="${not status_flag}">
                                        <a href="#" onclick="enableUser(${user.userId})">启用</a>&nbsp;&nbsp;|
                                    </c:if>
                                    &nbsp;&nbsp;
                                    <a href="#" onclick="del(${user.userId})">删除</a>
                                </c:if>
                            </td>
                        </tr>
                    </c:forEach>
                </c:if>
                <c:if test="${empty userList}">
                    <div>
                        <tr>
                            <td colspan="7" align="center">暂无用户</td>
                        </tr>
                    </div>
                </c:if>
            </tbody>
        </table>
    </div>
    <script type="text/javascript">
        //禁用用户
        function disableUser(userId) {
            $.ajax({
                url:"${pageContext.request.contextPath}/disableUser",
                type:"post",
                data:JSON.stringify({userId:userId,status:3}),
                contentType:"application/json;charset=utf-8",
                dataType:"json",
                success:function (data) {
                    if(data != null)
                    {
                        if(data.userId > 0){
                            alert("禁用成功!");
                            window.location.reload();
                        }
                        else
                        {
                            alert("禁用失败!");
                            window.location.reload();
                        }
                    }
                }
            });
        }

        //启用用户
        function enableUser(userId) {
            $.ajax({
                url:"${pageContext.request.contextPath}/enableUser",
                type:"post",
                data:JSON.stringify({userId:userId,status:2}),
                contentType:"application/json;charset=utf-8",
                dataType:"json",
                success:function (data) {
                    if(data != null)
                    {
                        if(data.userId > 0)
                        {
                            alert("启用成功!");
                            window.location.reload();
                        }
                        else
                        {
                            alert("启用失败!");
                            window.location.reload();
                        }
                    }
                }
            });
        }

        //删除用户
        function del(userId) {
            if (window.confirm("您确定要删除吗?"))
            {
                $.ajax({
                    url:"${pageContext.request.contextPath}/deleteUser",
                    type:"post",
                    data:JSON.stringify({userId:userId}),
                    contentType:"application/json;charset=utf-8",
                    dataType:"json",
                    success:function (data) {
                        if(data != null){
                            if(data.userId > 0){
                                alert("删除成功!");
                                window.location.reload();
                            }
                            else {
                                alert("删除失败");
                                window.location.reload();
                            }
                        }
                    }
                });
            }
        }


    </script>
</body>
</html>

add_user.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: user1
  Date: 2023/7/17
  Time: 12:59
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>添加用户</title>
</head>
<body>
    <h3>添加用户</h3>
    <form action="${pageContext.request.contextPath}/addUser" method="post" name="ff" onsubmit="return checkValue()">
        登录账号:<input type="text" name="loginName" id="loginName"><span style="color: red">${checkUserLoginNameMsg}</span><br>
        登录密码:<input type="password" name="userPwd" id="userPwd"><br>
        用户姓名:<input type="text" name="userName" id="userName"><br>
        联系电话:<input type="text" name="tel" id="tel"><br>
        用户角色:
        <select name="roleId" id="roleId">
            <option>--请选择--</option>
            <c:forEach items="${roleList}" var="r">
                <option value="${r.roleId}">${r.roleName}</option>
            </c:forEach>
        </select><br>
        <input type="submit" value="确认添加">&nbsp;&nbsp;
        <input type="button" onclick="goback()" value="返回用户列表">
    </form>
    <script>
        function goback() {
           window.location.href="${pageContext.request.contextPath}/findUserList";
        }

        function checkValue() {
            var str = document.getElementById("loginName").value;
            if (str.length < 1) {
                alert("请输入登录账号");
                document.getElementById("loginName").focus();
                return false;
            }
            str = document.getElementById("userPwd").value;
            if (str.length < 1)
            {
                alert("请输入密码");
                document.getElementById("userPwd").focus();
                return false;
            }
            if(str.length > 0 && str.length < 3)
            {
                alert("密码长度应大于等于4位");
                document.getElementById("userPwd").focus();
                return false;
            }
            str = document.getElementById("userName").value;
            if(str.length < 1)
            {
                alert("请输入用户名");
                document.getElementById("userName").focus();
                return false;
            }
            str = document.getElementById("tel").value;
            if(str.length < 1)
            {
                alert("请输入联系电话");
                document.getElementById("tel").focus();
                return false;
            }
            str = document.getElementById("roleId").value;
            if(str === '--请选择--')
            {
                alert("请选择用户角色");
                return false;
            }
            return true;
        }
    </script>
</body>
</html>

edit_user.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: user1
  Date: 2023/7/17
  Time: 15:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>修改用户</title>
</head>
<body>
    <h3>修改用户</h3>
<form action="${pageContext.request.contextPath}/editUser" method="post" name="ff" onsubmit="return checkValue()">
    <input type="hidden" name="userId" id="userId" value="${user.userId}"><br>
    登录账号:<input type="text" name="loginName" id="loginName" value="${user.loginName}" disabled="disabled"><br>
    登录密码:<input type="password" name="userPwd" id="userPwd" value="${user.userPwd}"><br>
    用户姓名:<input type="text" name="userName" id="userName" value="${user.userName}"><br>
    联系电话:<input type="text" name="tel" id="tel" value="${user.tel}"><br>
    用户角色:
    <select name="roleId" id="roleId">
        <option>--请选择--</option>
        <c:forEach items="${roleList}" var="r">
            <option value="${r.roleId}"
            <c:if test="${r.roleId eq user.roleId}">selected="selected"</c:if> >
                    ${r.roleName}</option>
        </c:forEach>
    </select><br>
    <input type="submit" value="确认修改">&nbsp;&nbsp;
    <input type="button" onclick="goback()" value="返回用户列表">
</form>
<script>
    function goback() {
        window.location.href="${pageContext.request.contextPath}/findUserList";
    }

    function checkValue() {
        var str = document.getElementById("loginName").value;
        if (str.length < 1) {
            alert("请输入登录账号");
            document.getElementById("loginName").focus();
            return false;
        }
        str = document.getElementById("userPwd").value;
        if (str.length < 1)
        {
            alert("请输入密码");
            document.getElementById("userPwd").focus();
            return false;
        }
        if(str.length > 0 && str.length < 3)
        {
            alert("密码长度应大于等于4位");
            document.getElementById("userPwd").focus();
            return false;
        }
        str = document.getElementById("userName").value;
        if(str.length < 1)
        {
            alert("请输入用户名");
            document.getElementById("userName").focus();
            return false;
        }
        str = document.getElementById("tel").value;
        if(str.length < 1)
        {
            alert("请输入联系电话");
            document.getElementById("tel").focus();
            return false;
        }
        str = document.getElementById("roleId").value;
        if(str === '--请选择--')
        {
            alert("请选择用户角色");
            return false;
        }
        return true;
    }
</script>
</body>
</html>

news_list.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%--
  Created by IntelliJ IDEA.
  User: user1
  Date: 2023/7/18
  Time: 11:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>新闻列表</title>
    <script src="${pageContext.request.contextPath}/js/jQuery-3.4.1.js"></script>
</head>
<body>
    <div>
        <ul>
            <li>
                <a href="${pageContext.request.contextPath}/toAddNews">添加新闻</a>
            </li>
            <li><a href="${pageContext.request.contextPath}/logout">注销退出</a></li>
        </ul>
    </div>
    <div>
        <form action="${pageContext.request.contextPath}/findNewsByPage" method="post" id="newsListForm" name="ff">
            <ul>
                <li>
                    <label for="keywords">搜索关键词</label>
                    <input type="text" name="keywords" id="keywords" value="${keywords}" placeholder="这里输入标题或关键词">
                </li>
                <li>
                    <label for="newsListCategoryId">新闻类别</label>
                    <select name="newsListCategoryId" id="newsListCategoryId">
                        <c:forEach items="${categoryList}" var="c">
                            <option value="${c.categoryId}"
                            <c:if test="${c.categoryId eq newsListCategoryId}">
                                selected="selected"
                            </c:if> >${c.categoryName}</option>
                        </c:forEach>
                    </select>
                </li>
                <li>
                    <input type="submit" value="查询">
                </li>
            </ul>
        </form>
    </div>
    <div>
        <table border="1">
            <thead>
                <tr>
                    <th>新闻标题</th>
                    <th>新闻类别</th>
                    <th>发布时间</th>
                    <th>发布状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <c:if test="${!empty pageBean.list}">
                    <c:forEach items="${pageBean.list}" var="news">
                        <tr>
                            <td>${news.title}</td>
                            <td>${news.categoryName}</td>
                            <td>
                                <fmt:formatDate value="${news.publishTime}" pattern="yyyy-MM-dd HH:mm:ss"/>
                            </td>
                            <td>
                                <c:if test="${news.publishStatus== '1'}" var="flag">
                                    已发布
                                </c:if>
                                <c:if test="${not flag}">
                                    已撤稿
                                </c:if>
                            </td>
                            <td>
                                <a href="${pageContext.request.contextPath}/toEditNews?newsId=${news.newsId}">修改</a>
                                &nbsp;&nbsp;
                                <c:if test="${news.publishStatus=='2'}" var="status_flag">
                                    &nbsp;|&nbsp;<a href="#" onclick="upNews(${news.newsId})">发布</a>
                                </c:if>
                                <c:if test="${not status_flag}">
                                    &nbsp;|&nbsp; <a href="#" onclick="downNews(${news.newsId})">撤稿</a>
                                </c:if>
                                |&nbsp;&nbsp;
                                <a href="#" onclick="delNews(${news.newsId})">删除</a>
                            </td>
                        </tr>
                    </c:forEach>
                    <tr>
                        <td colspan="5">
                            <div>
                                第${pageBean.currentPage}页
                                &nbsp;&nbsp; 共${pageBean.totalPage}页
                                &nbsp;&nbsp; 共${pageBean.count}条新闻
                                <div>
                                    <c:if test="${pageBean.currentPage==1}">
                                        首页&nbsp;&nbsp;上一页
                                    </c:if>
                                    <c:if test="${pageBean.currentPage > 1}">
                                        <a href="#" onclick="fy(1)">首页</a>
                                        <a href="#" onclick="fy(${pageBean.currentPage-1})">上一页</a>
                                    </c:if>
                                    <c:if test="${pageBean.currentPage < pageBean.totalPage}">
                                        <a href="#" onclick="fy(${pageBean.currentPage+1})">下一页</a>
                                        <a href="#" onclick="fy(${pageBean.totalPage})">尾页</a>
                                    </c:if>
                                    <c:if test="${pageBean.currentPage== pageBean.totalPage}">
                                        下一页&nbsp;&nbsp;尾页
                                    </c:if>
                                    &nbsp;&nbsp;跳转至
                                    <input type="text" style="height: 22px;width:30px" value="${gotoPageNo}" name="gotoPageNo" id="gotoPageNo">
                                    <a href="#" onclick="validate()">跳转</a>
                                </div>
                            </div>
                        </td>
                    </tr>
                </c:if>
                <c:if test="${empty pageBean.list}">
                    <div>
                        <tr>
                            <td colspan="5" align="center">暂无新闻</td>
                        </tr>
                    </div>
                </c:if>
            </tbody>
        </table>
    </div>
    <script>
        //翻页
        function fy(gotoPageNo) {
            var form = document.getElementById("newsListForm");
            form.action = "${pageContext.request.contextPath}/findNewsByPage?currentPage=" + gotoPageNo;
            form.submit();
        }

        //跳转验证
        function validate() {
            var totalPage = ${pageBean.totalPage};
            var gotoPageNo = document.getElementById("gotoPageNo").value;
            if(gotoPageNo > totalPage || gotoPageNo <= 0)
            {
                alert("输入页码有误!");

            }
            else
            {
                fy(gotoPageNo);
            }
        }

        //新闻发布
        function upNews(newsId) {
            $.ajax({
                url:"${pageContext.request.contextPath}/setNewsStatus",
                type:"post",
                data:JSON.stringify({newsId:newsId,publishStatus:1}),
                contentType:"application/json;charset=utf-8",
                dataType:"json",
                success:function (data) {
                    if(data != null){
                        if(data.newsId > 0){
                            alert("发布成功");
                            window.location.reload();
                        }
                        else
                        {
                            alert("发布失败!");
                            window.location.reload();
                        }
                    }
                }
            });
        }

        //新闻撤稿
        function downNews(newsId) {
            $.ajax({
                url:"${pageContext.request.contextPath}/setNewsStatus",
                type:"post",
                data:JSON.stringify({newsId:newsId,publishStatus:2}),
                contentType:"application/json;charset=utf-8",
                dataType:"json",
                success:function (data) {
                    if(data != null){
                        if(data.newsId > 0){
                            alert("撤稿成功");
                            window.location.reload();
                        }
                        else
                        {
                            alert("撤稿失败");
                            window.location.reload();
                        }
                    }
                }
            });
        }

        //删除新闻
        function delNews(newsId) {
            if(window.confirm("你确定要删除吗?"))
            {
                $.ajax({
                    url:"${pageContext.request.contextPath}/delNews",
                    type:"post",
                    data:JSON.stringify({newsId:newsId}),
                    contentType:"application/json;charset=utf-8",
                    dataType:"json",
                    success:function (data) {
                        if(data != null){
                            if(data.newsId > 0){
                                alert("删除成功");
                                window.location.reload();
                            }
                            else
                            {
                                alert("删除失败");
                                window.location.reload();
                            }

                        }
                    }
                });
            }

        }

    </script>
</body>
</html>

add_news.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: user1
  Date: 2023/7/18
  Time: 11:47
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>添加新闻</title>
</head>
<body>
    <h3>添加新闻</h3>
    <form action="${pageContext.request.contextPath}/addNews" method="post" name="ff" onsubmit="return checkValue()">
        新闻标题:<input type="text" id="title" name="title"><br>
        新闻类别:
        <select name="categoryId" id="categoryId">
            <option>--请选择--</option>
            <c:forEach items="${categoryList}" var="c">
                <option value="${c.categoryId}">${c.categoryName}</option>
            </c:forEach>
        </select><br>
        新闻内容页标题:<input type="text" name="contentTitle" id="contentTitle"><br>
        内容摘要:<br>
        <textarea id="contentAbstract" name="contentAbstract" cols="100" rows="2" style="width:800px;height: 50px;"></textarea><br>
        新闻内容:<br>
        <textarea id="content" name="content" cols="100" rows="4" style="width: 800px;height: 100px;"></textarea><br>
        关键词:<input type="text" name="keywords" id="keywords"><br>
        作者来源:<input type="text" id="author" name="author"><br>
        <input type="submit" value="确认发布">
        &nbsp;&nbsp;<input type="button" onclick="goback()" value="返回新闻列表">
    </form>
    <script>
        //
        function goback(){
            window.location.href="${pageContext.request.contextPath}/findNewsByPage";
        }

        function checkValue() {
            var str = document.getElementById("title").value;
            if(str.length < 1)
            {
                alert("请输入新闻标题");
                document.getElementById("title").focus();
                return false;
            }

            var str = document.getElementById("categoryId").value;
            if(str === '--请选择--')
            {
                alert("请选择新闻类别");
                document.getElementById("categoryId").focus();
                return false;
            }

            var str = document.getElementById("contentTitle").value;
            if(str.length < 1)
            {
                alert("请输入新闻内容页标题");
                document.getElementById("contentTitle").focus();
                return false;
            }

            var str = document.getElementById("contentAbstract").value;
            if(str.length < 1)
            {
                alert("请输入内容摘要");
                document.getElementById("contentAbstract").focus();
                return false;
            }

            var str = document.getElementById("content").value;
            if(str.length < 1)
            {
                alert("请输入新闻内容");
                document.getElementById("content").focus();
                return false;
            }

            var str = document.getElementById("keywords").value;
            if(str.length < 1)
            {
                alert("请输入关键词");
                document.getElementById("keywords").focus();
                return false;
            }

            var str = document.getElementById("author").value;
            if(str.length < 1)
            {
                alert("请输入作者来源");
                document.getElementById("author").focus();
                return false;
            }
            return  true;
        }
    </script>
</body>
</html>

edit_news.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: user1
  Date: 2023/7/18
  Time: 11:56
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>修改新闻</title>
</head>
<body>
    <h3>修改新闻</h3>
<form action="${pageContext.request.contextPath}/editNews" method="post" name="ff" onsubmit="return checkValue()">
    <input type="hidden" name="newsId" id="newsId" value="${news.newsId}"><br>
    新闻标题:<input type="text" id="title" name="title" value="${news.title}"><br>
    新闻类别:
    <select name="categoryId" id="categoryId">
        <option>--请选择--</option>
        <c:forEach items="${categoryList}" var="c">
            <option value="${c.categoryId}"
                    <c:if test="${c.categoryId eq news.categoryId}">
                        selected="selected"
                    </c:if> >${c.categoryName}</option>
        </c:forEach>
    </select><br>
    新闻内容页标题:<input type="text" name="contentTitle" id="contentTitle" value="${news.contentTitle}"><br>
    内容摘要:<br>
    <textarea id="contentAbstract" name="contentAbstract" cols="100" rows="2" style="width:800px;height: 50px;">${news.contentAbstract}</textarea><br>
    新闻内容:<br>
    <textarea id="content" name="content" cols="100" rows="4" style="width: 800px;height: 100px;">${news.content}</textarea><br>
    关键词:<input type="text" name="keywords" id="keywords" value="${news.keywords}"><br>
    作者来源:<input type="text" id="author" name="author" value="${news.author}"><br>
    <input type="submit" value="确认修改">
    &nbsp;&nbsp;<input type="button" onclick="goback()" value="返回新闻列表">
</form>
<script>
    //
    function goback(){
        window.location.href="${pageContext.request.contextPath}/findNewsByPage";
    }

    function checkValue() {
        var str = document.getElementById("title").value;
        if(str.length < 1)
        {
            alert("请输入新闻标题");
            document.getElementById("title").focus();
            return false;
        }

        var str = document.getElementById("categoryId").value;
        if(str === '--请选择--')
        {
            alert("请选择新闻类别");
            document.getElementById("categoryId").focus();
            return false;
        }

        var str = document.getElementById("contentTitle").value;
        if(str.length < 1)
        {
            alert("请输入新闻内容页标题");
            document.getElementById("contentTitle").focus();
            return false;
        }

        var str = document.getElementById("contentAbstract").value;
        if(str.length < 1)
        {
            alert("请输入内容摘要");
            document.getElementById("contentAbstract").focus();
            return false;
        }

        var str = document.getElementById("content").value;
        if(str.length < 1)
        {
            alert("请输入新闻内容");
            document.getElementById("content").focus();
            return false;
        }

        var str = document.getElementById("keywords").value;
        if(str.length < 1)
        {
            alert("请输入关键词");
            document.getElementById("keywords").focus();
            return false;
        }

        var str = document.getElementById("author").value;
        if(str.length < 1)
        {
            alert("请输入作者来源");
            document.getElementById("author").focus();
            return false;
        }
        return  true;
    }
</script>
</body>
</html>

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: user1
  Date: 2023/7/17
  Time: 10:55
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <a href="${pageContext.request.contextPath}/toLogin">登录</a>
  </body>
</html>

js文件夹下的jQuery,自己下载一个。

测试

 

 

 

 

 

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

虾米大王

有你的支持,我会更有动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值