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

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

新建maven项目

 

 

 导入依赖

<?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>
    </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>

数据库

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(
		newId 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);

配置文件

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/"/>
    <!-- 视图解析器   -->
    <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 + '}';
    }
}

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>

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>

service层

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();
}

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);
}

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;
    }
}

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);
    }
}

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

jsp层

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>

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>
    <p><a href="${pageContext.request.contextPath}/findUserList">用户列表</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>
        </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>

js文件下的jquery,自己下载一下。

 

 

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

虾米大王

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

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

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

打赏作者

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

抵扣说明:

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

余额充值