IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> 从0到1搭建一个SSM+Mysql的纯用户管理demo系统(只包含登录、用户增删改查功能) -> 正文阅读

[Java知识库]从0到1搭建一个SSM+Mysql的纯用户管理demo系统(只包含登录、用户增删改查功能)

搭建SSM+Mysql纯用户管理demo系统

学习SSM框架有两个难点:
1、从0到1搭建SSM框架,各种配置比较头疼
2、好多同学为了学习框架,下载了好多SSM的系统,但是功能太复杂,难以看到框架的核心东西
基于上面两点,我将功能点简化,只留下登录、用户管理模块(增删改查),让大家可以将重点放在SSM框架本身上来,更容易去研究和学会SSM框架。

详细搭建流程(三大配置)

在配置文件说明之前,我们以三层架构的角度看一下SSM框架在项目中所在的位置:
在这里插入图片描述
三层框架:
主要分为控制层(SpringMVC)、业务逻辑层(Service)、数据库层(Dao),三层结构作用主要是为了代码解耦,让业务功能实现起来更加清晰。我们可以注意到,与SSH相比,SpringMVC和Structs作用一样,也是servlet控制层。
那么SSM对应的在三层框架中的作用是什么呢,SpringMVC就相当于控制层(主要是Action);Mybatis相当于Dao数据库持久化层(Mybatis和Hibernate相比,Hibernate是全自动化的,不仅可以将数据库字段与成员变量映射,还把sql语句全部封装,不用自己写SQL,而Mybatis则需要自己手动写SQL,这样来说就比较灵活一些,自己管理SQL可以提高执行效率);Spring相当于一个大管家,它的作用也是为了代码的解耦,主要作用一个是IOC(注册service、controller、dao的对象)、另一个是AOP(切面编程,比如进行事务配置)。

1、创建空白的javaee项目,并且自己做好分包,这一步就略过了

2、springMvc配置:springMVC-servlet.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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	http://www.springframework.org/schema/mvc
	http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-3.0.xsd
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">
	
	<!-- 扫描controller包中带有@Controller注解的控制层类 -->
	<context:component-scan base-package="com.code2life.*.controller"></context:component-scan>
	<!-- 加载注解驱动 -->
	<mvc:annotation-driven />
	<!-- 配置静态资源访问-->
	<mvc:default-servlet-handler/>
	<mvc:resources location="/static/css/" mapping="/css/**"></mvc:resources>
	<mvc:resources location="/static/fonts/" mapping="/fonts/**"></mvc:resources>
	<mvc:resources location="/static/img/" mapping="/img/**"></mvc:resources>
	<mvc:resources location="/static/js/" mapping="/js/**"></mvc:resources>
	<mvc:resources location="/static/layui/" mapping="/layui/**"></mvc:resources>
	<!-- 内部资源视图解析器 -->
	<bean id="jspInternalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/pages/"/>
		<property name="suffix" value=".jsp"/>
	</bean>
	<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
	<!--<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">-->
		<!--<property name="defaultEncoding" value="UTF-8"/>-->
		<!--&lt;!&ndash; 指定所上传文件的总大小不能超过5M。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和   &ndash;&gt;-->
		<!--<property name="maxUploadSize" value="5120000"/>-->
	<!--</bean>-->
    <!-- 对控制层进行事物代理AOP支持 -->
    <aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
</beans>	

springMVC也是属于spring框架的一种技术,它的作用和structs一样,处于控制层,即用来处理前后端交互的。
这里我们使用了注解,其实本质上和手动注册action一样,配置文件通过扫描包,来让项目运行时识别注解的位置。

在这里插入图片描述
在这里插入图片描述
我们可以看一下常用的注解:@Controller、@Autowired、@RequestMapping

@Controller是用来声明这里是controller层,@Autowired用来注册内部的成员变量、@RequestMapping是用来定义路由跳转地址。
(具体的大家可以看看spring注解部分,这里不做过多的讲解)

3、spring配置: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:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd  
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd  
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
            http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.1.xsd 
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
   
    <!-- 运行包扫描,将dao和service包中的内容进行注入,注入的方式是使用注解 -->
     <context:component-scan base-package="com.code2life.ssm.dao,com.code2life.ssm.service,com.code2life.ssm.orm"></context:component-scan>
    <!-- 数据源配置 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/frameDemo?useUnicode=true&amp;characterEncoding=utf-8"></property>
        <property name="username" value="root"></property>
        <property name="password" value=""></property>
    </bean>   
    
    <!-- sessionFactory工厂配置,注入数据源配置dataSource -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    
    <!-- 需要将sqlSessionFactory对象注入到UserInfoMapper.java接口的代理实现类中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.code2life.ssm.orm"></property>
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>
    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

由于这里将spring和Mybatis进行了整合,所以这两个都放在了一个配置文件中。

同样的由于项目中使用了注解,所以spring的配置文件中配置了扫描包下面的文件来自动注册javabeans.同时,配置文件中配置了数据库的连接信息、事务配置。

最重要的是,spring配置文件中将mybatis的映射文件进行了配置,以便于项目中可以用mybatis的映射文件进行数据持久化。
在这里插入图片描述
我们来看下mybatis的映射文件: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.code2life.ssm.orm.UserMapper" >
  <resultMap id="BaseResultMap" type="com.code2life.ssm.domain.User" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="user_name" property="userName" jdbcType="VARCHAR" />
    <result column="pass_word" property="passWord" jdbcType="VARCHAR" />
    <result column="real_name" property="realName" jdbcType="VARCHAR" />
    <result column="age" property="age" jdbcType="INTEGER" />
    <result column="role" property="role" jdbcType="INTEGER" />
  </resultMap>
  <sql id="Base_Column_List" >
    id, user_name, pass_word, real_name, age, `role`
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from user
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from user
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.code2life.ssm.domain.User" >
    insert into user (user_name, pass_word, real_name, 
      age, `role`)
    values (#{userName,jdbcType=VARCHAR}, #{passWord,jdbcType=VARCHAR}, #{realName,jdbcType=VARCHAR}, 
      #{age,jdbcType=INTEGER}, #{role,jdbcType=INTEGER})
    <selectKey resultType="java.lang.Integer" keyProperty="id" >
      SELECT LAST_INSERT_ID()
    </selectKey>
  </insert>
  <insert id="insertSelective" parameterType="com.code2life.ssm.domain.User" >
    insert into user
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="userName != null" >
        user_name,
      </if>
      <if test="passWord != null" >
        pass_word,
      </if>
      <if test="realName != null" >
        real_name,
      </if>
      <if test="age != null" >
        age,
      </if>
      <if test="role != null" >
        `role`,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="userName != null" >
        #{userName,jdbcType=VARCHAR},
      </if>
      <if test="passWord != null" >
        #{passWord,jdbcType=VARCHAR},
      </if>
      <if test="realName != null" >
        #{realName,jdbcType=VARCHAR},
      </if>
      <if test="age != null" >
        #{age,jdbcType=INTEGER},
      </if>
      <if test="role != null" >
        #{role,jdbcType=INTEGER},
      </if>
    </trim>
    <selectKey resultType="java.lang.Integer" keyProperty="id" >
      SELECT LAST_INSERT_ID()
    </selectKey>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.code2life.ssm.domain.User" >
    update user
    <set >
      <if test="userName != null" >
        user_name = #{userName,jdbcType=VARCHAR},
      </if>
      <if test="passWord != null" >
        pass_word = #{passWord,jdbcType=VARCHAR},
      </if>
      <if test="realName != null" >
        real_name = #{realName,jdbcType=VARCHAR},
      </if>
      <if test="age != null" >
        age = #{age,jdbcType=INTEGER},
      </if>
      <if test="role != null" >
        `role` = #{role,jdbcType=INTEGER},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.code2life.ssm.domain.User" >
    update user
    set user_name = #{userName,jdbcType=VARCHAR},
      pass_word = #{passWord,jdbcType=VARCHAR},
      real_name = #{realName,jdbcType=VARCHAR},
      age = #{age,jdbcType=INTEGER},
      `role` = #{role,jdbcType=INTEGER}
    where id = #{id,jdbcType=INTEGER}
  </update>

  <select id="findUserListByPage" resultMap="BaseResultMap">
    select  *  from  user
    <if test="start!=null and limit!=null">
      limit #{start},#{limit}
    </if>
  </select>

  <select id="countUser" resultType="int">
    select count(*) from user
  </select>

  <select id="findUserByNameAndPassWord" parameterType="map" resultMap="BaseResultMap">
    select * from user where user_name = #{userName} and pass_word = #{passWord}
  </select>
</mapper>

最后这些配置文件最好放置在src目录下:
在这里插入图片描述

详细搭建流程(代码部分)

1、用户实体类映射:UserMapper.java

package com.code2life.ssm.orm;

import com.code2life.ssm.domain.User;
import com.code2life.ssm.vo.Page;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface UserMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);

    /**  注意: 以下为自己生成的方法,防止覆盖 */
    List<User> findUserListByPage(Page page);

    /**
     * 查询用户数据量
     * @return
     */
    int countUser();

    /**
     * 根据用户名、密码查询
     * @param userName
     * @param passWord
     * @return
     */
    List<User> findUserByNameAndPassWord(@Param("userName") String userName, @Param("passWord") String passWord);
}

2、service层:UserService.java

package com.code2life.ssm.service;

import com.code2life.ssm.domain.User;
import com.code2life.ssm.vo.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.code2life.ssm.dao.AllDao;

import java.util.List;

@Service("userinfoService")
public class UserService {
    
	@Autowired
	private AllDao allDao;

	/**
	 * 查询分页用户列表
	 * @param page
	 * @return
	 */
	public List<User> queryUserList(Page page){
		return allDao.getUserDao().findUserListByPage(page);
	}

	/**
	 * 查询总数据量
	 * @return
	 */
	public int countUser() {
		return allDao.getUserDao().getUserCount();
	}

	/**
	 * 删除用户信息
	 * @param id
	 */
	public void deleteUser(Integer id) {
		allDao.getUserDao().deleteUser(id);
	}

	/**
	 * 根据用户唯一标识查询用户信息
	 * @param id
	 * @return
	 */
	public User queryUserByPK(Integer id) {
		User user = allDao.getUserDao().findUserByPK(id);
		return user;
	}

	/**
	 * 修改用户信息
	 * @param user
	 */
	public void updateUser(User user) {
		allDao.getUserDao().updateUser(user);
	}

	/**
	 * 新增用户信息
	 * @param user
	 */
	public void addUserInfo(User user){
	    System.out.println("allDao.hashCode = " + allDao.hashCode());
	    System.err.println("Service层获取到插入的记录---》" + user.toString());
	    allDao.getUserDao().addUser(user);
	}

	/**
	 * 用户登陆校验
	 * @param userName
	 * @param passWord
	 * @return
	 */
	public boolean loginCheck(String userName, String passWord) {
		User user = allDao.getUserDao().findUserByUserNameAndPassWord(userName, passWord);
		if (user != null) {
			return true;
		} else {
			return false;
		}
	}

}

3、action控制层:UserAction.java

package com.code2life.ssm.controller;

import java.lang.reflect.Method;
import java.util.List;

import com.code2life.ssm.domain.User;
import com.code2life.ssm.service.AllService;
import com.code2life.ssm.vo.Page;
import com.code2life.ssm.vo.RespEntity;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@Transactional
public class UserController extends BaseAction {

    @Autowired
    private AllService allService;

    /**
     * 跳转到用户管理页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/goUserMange")
    public ModelAndView goUserMange(Model model) {
        ModelAndView mav = new ModelAndView("user-manage");
        return mav;
    }

    /**
     * 查询用户列表
     *
     * @param page
     * @return
     */
    @RequestMapping(value = "/user/list", method = {RequestMethod.POST, RequestMethod.GET}, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String getUserList(Page page) {
        int count = allService.getUserService().countUser();
        List<User> list = allService.getUserService().queryUserList(page);
        page.caculatestart();
        RespEntity respEntity = new RespEntity(0, "成功");
        respEntity.setCount(count);
        respEntity.setData(list);
        Gson gson = new Gson();
        return gson.toJson(respEntity);
    }

    /**
     * 删除用户信息
     * @param id
     * @return
     */
    @RequestMapping("/user/delete")
    public ModelAndView delstu(Integer id) {
        allService.getUserService().deleteUser(id);
        ModelAndView mav = new ModelAndView("user-manage");
        return mav;
    }

    /**
     * 跳转到修改页面,初始化数据
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/goUpdateUser")
    public String goUpdate(Integer id,Model model) {
        User user = allService.getUserService().queryUserByPK(id);
        model.addAttribute("user",user);
        return "user-update";
    }

    /**
     * 修改用户信息
     * @param id
     * @param user
     * @return
     */
    @RequestMapping(value = "/user/update", method = RequestMethod.POST)
    public String updateUser(Integer id, User user) {
        user.setId(id);
        allService.getUserService().updateUser(user);
        ModelAndView mav = new ModelAndView("user-manage");
        return "user-manage";
    }

    /**
     * 跳转到新增用户界面
     * @param model
     * @return
     */
    @RequestMapping("/goAddUser")
    public ModelAndView goAddUser(Model model) {
        ModelAndView mav = new ModelAndView("user-add");
        return mav;
    }

    /**
     * 新增用户
     * @param user
     * @return
     */
    @RequestMapping(value = "/user/add")
    public String addUserInfo(User user) {
        this.getAllService().getUserService().addUserInfo(user);
        return "user-manage";
    }
}

到这里简单的一个SSM的用户管理系统就完成了,业务逻辑只有增删改查,自己运行起来后,还可以自己去拓展实现新的模块,这样也可以进一步消化框架的逻辑。

系统功能界面

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

总结

本次SSM+mysql用户管理框架我已经将代码整理好,并且写了详细的框架搭建流程的word文档以及前后端数据交互的流程,如果需要完整的demo,可以加博主V:(Code2Life2)

写博客不易,觉得写得不错,记得一键三连!

  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2021-07-14 10:44:42  更:2021-07-14 10:45:21 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/2 16:17:05-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码