【SSM框架】SSM框架整合及增删查改操作

导读:本篇文章讲解 【SSM框架】SSM框架整合及增删查改操作,文章出自:https://blog.csdn.net/weixin_43316702/article/details/105286800希望对大家有帮助,欢迎收藏,转发!站点地址:www.javazhiyin.com.com

>>强大,10k+点赞的 SpringBoot 后台管理系统竟然出了详细教程!

SSM:
SSM是由Spring、SpringMvc、Mybatis三大框架整合而成的。

整合步骤:
前提条件:导入jar包(Spring、SpringMvc、Mybatis所需的jar,Spring与Mybatis整合jar、数据库操作所需jar等)【具体的看我分享的链接
配置web.xml文件:

<!-- 处理编码格式 -->
<filter>
    <filter-name>characterEncodingFilter</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>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<!--加载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>

<!--加载springmvc配置文件-->
<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- springmvc默认加载springmvc的配置文件,这个需要满足以下规则:
         命名规则:servlet-name-servlet.xml====>springmvc-servlet.xml
         路径规范:springmvc-servlet.xml必须放在WEB-INF下面
    -->
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:dispatcher.xml</param-value>
    </init-param>
</servlet>
<!--配置可用后缀--->
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>*.do</url-pattern>
</servlet-mapping>
    <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>
 <!--这是文件上传时的后缀,
 如需要上传其他格式,将url-pattern的内容改为所需的即可-->
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.jpg</url-pattern>
</servlet-mapping>

配置spring文件:(applicationContext.xml)

	<!--扫描注解-->
    <context:component-scan base-package="com.ssm"/>

    <!--加载java的配置文件-->
    <context:property-placeholder location="classpath:db.properties"/>
    <!--第一步:配置数据源-->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <!--第二步:创建sqlSessionFactory,生产sqlSession-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:sqlMapConfig.xml"/>
    </bean>
    <!--配置mybatis接口代理开发
        * 接口类和映射文件必须同名
        * 接口类与映射文件必须在同一目录下
        * 映射文件namespace名字必须是借口的全类路径
        * 接口的方法名必须和映射Statement的id一致-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.ssm.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </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="update" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="insert" propagation="REQUIRED"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    <!--配置拦截service-->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.ssm.service.*.*(..))"/>
    </aop:config>

    <!--配置路径-->
    <mvc:annotation-driven/>
    <mvc:default-servlet-handler/>
    <mvc:resources mapping="/static/upload/**" location="/static/upload/"/>
    <mvc:resources mapping="/static/js/**" location="/static/js/"/>

数据库信息文件 db.properties:

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/mybatis_01?useUnicode=true&amp;characterEncoding=UTF-8
jdbc.username = root
jdbc.password = 123

配置springmvc文件:(dispatcher.xml)

	<!-- 将controller交给spring管理 -->
    <context:component-scan base-package="com.ssm"></context:component-scan>

    <!--
        <mvc:annotation-driven/>默认创建RequestMappingHandlerMapping,RequestMappingHandlerAdapter
        提供对json数据格式支持
    -->
    <mvc:annotation-driven/>

    <!-- 配置视图解析器:解析出真正的物理视图
        后台返回逻辑视图:index
        解析出真正的物理视图,前端+逻辑视图+后缀==/WEB-INF/index.jsp(/index.jsp)
    -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!--文件上传解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="10240000"></property>
    </bean>

配置mybatis文件:
(注意都放在config【idea设置文件为 Resources Root】或者放在src下)
sqlMapConfig.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.ssm.po"/>
    </typeAliases>

    <!--加载映射文件-->
    <mappers>
        <mapper resource="com/ssm/dao/UserMapper.xml"/>
        <mapper resource="com/ssm/dao/VideoMapper.xml"/>
        <!--&lt;!&ndash;批量加载映射文件&ndash;&gt;-->
        <!--<package name="com.sm.mapper"/>-->
    </mappers>
</configuration>

log4j.properties:

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

创建mapper.xml(用于对数据库进行操作):
例如: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:命名空间,用于隔离sql -->
<!-- 还有一个很重要的作用,使用动态代理开发DAO,1. namespace必须和Mapper接口类路径一致 -->
<mapper namespace="com.ssm.dao.UserMapper">
    <!-- 根据用户ID查询用户信息-->
    <!-- select:表示一个MappingStatement对象-->
    <!-- id:statement的唯一标识-->
    <!-- #{}:表示一个占位符?-->
    <!-- #{id}:里面的id表示输入参数的参数名称,如果该参数是简单类型,那么#{}里面的参数名称可以任意-->
    <!-- parameterType:输入参数的java类型-->
    <!-- resultType:输出结果的所映射的java类型(单条结果所对应的的java类型)-->
    <select id="findUserById" parameterType="int" resultType="com.ssm.po.User">
        SELECT * FROM USER WHERE id =#{id}
    </select>
    <!--查询全部-->
    <select id="findUserAll" resultType="com.ssm.po.User">
        SELECT * FROM USER
    </select>
    <!--通过username查找用户-->
    <select id="findUserByUsername" parameterType="String" resultType="com.ssm.po.User">
        select * from user where username like '%${value}%'
    </select>
    <!-- 新增用户 -->
    <insert id="insertUser" parameterType="com.ssm.po.User">
        <!-- selectKey 标签实现主键返回 -->
        <!-- keyColumn:主键对应的表中的哪一列 -->
        <!-- keyProperty:主键对应的pojo中的哪一个属性 -->
        <!-- order:设置在执行insert语句前执行查询id的sql,孩纸在执行insert语句之后执行查询id的sql -->
        <!-- resultType:设置返回的id的类型 -->
        <selectKey keyColumn="id" keyProperty="id" order="AFTER" resultType="int">
            SELECT LAST_INSERT_ID()
        </selectKey>
        INSERT INTO `user`
        (username,birthday,sex,address,head) VALUES (#{username},#{birthday},#{sex},#{address},#{head})
    </insert>
    <!-- 更新用户 -->
    <update id="updateUserById" parameterType="com.ssm.po.User">
	UPDATE `user` SET
	username = #{username} WHERE id = #{id}
    </update>
    <!-- 删除用户 -->
    <delete id="deleteUserById" parameterType="int">
		delete from user where id=#{id}
	</delete>
</mapper>

创建Mapper.xml对应接口:
UserMapper.java:

package com.ssm.dao;
import com.ssm.po.User;
import java.util.List;

public interface UserMapper {
    //通过id查找用户信息
    User findUserById(Integer id);

    //查找所有用户信息
    List<User> findUserAll();

    //通过username查找用户信息
    List<User> findUserByUsername(String username);

    //新增用户
    void insertUser(User user);

    //通过id更新username
    void updateUserById(User user);

    //通过id删除指定用户
    void deleteUserById(Integer id);
}

创建service接口与实现类:
接口:

package com.ssm.service;
import com.ssm.po.User;
import java.util.List;

public interface UserService {
    List<User> findUserAll();

    //通过id查找用户信息
    User findUserById(Integer id);

    //通过username查找用户信息
    List<User> findUserByUsername(String username);

    //新增用户
    void insertUser(User user);

    //通过id更新username
    void updateUserById(User user);

    //通过id删除指定用户
    void deleteUserById(Integer id);
}

实现类:

package com.ssm.service.impl;

import com.ssm.dao.UserMapper;
import com.ssm.po.User;
import com.ssm.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public List<User> findUserAll() {
        List<User> list = userMapper.findUserAll();
        return list;
    }

    @Override
    public User findUserById(Integer id) {
        User user = userMapper.findUserById(id);
        return user;
    }

    @Override
    public List<User> findUserByUsername(String username) {
        List<User> list = userMapper.findUserByUsername(username);
        return list;
    }

    @Override
    public void insertUser(User user) {
        userMapper.insertUser(user);
    }

    @Override
    public void updateUserById(User user) {
        userMapper.updateUserById(user);
    }

    @Override
    public void deleteUserById(Integer id) {
        userMapper.deleteUserById(id);
    }

}

创建controller进行获取请求进行前后端交互操作:

package com.ssm.controller;

import com.ssm.po.User;
import com.ssm.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    //查询所有用户
    @RequestMapping("list")
    public String list(Model model){
        List<User> list = userService.findUserAll();

        model.addAttribute("list",list);

        return "UserList";
    }

    //查询所有用户
    @RequestMapping("listById")
    public String findUserById(Model model,int id){
        User user = userService.findUserById(id);

        model.addAttribute("user",user);

        return "UpdateUser";
    }

    //根据关键词找名字查询所有用户
    @RequestMapping("listByUsername")
    public String listByUsername(Model model,String username){
        List<User> list = userService.findUserByUsername(username);
        model.addAttribute("list",list);
        return "UserList";
    }

    @RequestMapping("saveUser")
    public String saveUser(Model model,int id,String username){
        User user = new User();
        user.setId(id);
        user.setUsername(username);
        userService.updateUserById(user);

        return "index";
    }

	//插入新用户(顺带上传头像)
	//【注意喔,上传图片的格式还要在web.xml配置】
    @RequestMapping("insertUser")
    public String insertUser(String username, String sex, String address,MultipartFile upload, HttpServletRequest request) throws IOException {

        //使用fileupload组件完成文件上传
        //上传位置指定
        //上传的位置要指定
        String path = request.getSession().getServletContext().getRealPath("/static/upload/");
        //判断该路径是否存在
        File file = new File(path);
        if (!file.exists()) {
            //如果这个文件夹不存在的话,就创建这个文件
            file.mkdirs();
            System.out.println("noexist");
        }else{
            System.out.println("exist");
        }
        //获取上传文件名称
        String filename = upload.getOriginalFilename();
        //把文件名称设置成唯一值 uuid 以防止文件名相同覆盖
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //新文件名
        filename = uuid + "_" + filename;
        //完成文件上传
        upload.transferTo(new File(path, filename));
        String NewFilePath = "static/upload/"+filename;

            User user = new User();
            user.setUsername(username);
            user.setHead(NewFilePath);
            user.setBirthday(new Date());
            user.setSex(sex);
            user.setAddress(address);
            userService.insertUser(user);

        return "redirect:list.do";
    }

	//删除用户
    @RequestMapping("deleteUser")
    public String deleteUser(int id){
        userService.deleteUserById(id);
        return "redirect:list.do";
    }
}

jsp前端:

<h1>用户列表:</h1>
<form method="post" action="${pageContext.request.contextPath}/user/listByUsername.do" >
    (根据用户名称查找)<input type="text" name="username" id="username">
    <input type="submit" value="查找">
</form>&nbsp;&nbsp;
<a href="${pageContext.request.contextPath}/user/list.do">显示所有用户</a>
<table width="80%" border="1">
<tr>
    <td>序号</td>
    <td>编号</td>
    <td>头像</td>
    <td>名字</td>
    <td>性别</td>
    <td>生日</td>
    <td>住址</td>
    <td>操作1</td>
    <td>操作2</td>
</tr>
<c:forEach items="${list}" var="user" varStatus="u">
    <tr>
        <td>${u.count}</td>
        <td>${user.id}</td>
        <td><img src="${pageContext.request.contextPath}/${user.head}" style="width: 60px;height: 60px;"></td>
        <td>${user.username}</td>
        <td>${user.sex}</td>
        <td>${user.birthday}</td>
        <td>${user.address}</td>
        <td><a href="${pageContext.request.contextPath}/user/listById.do?id=${user.id}">修改</a></td>
        <td><a href="${pageContext.request.contextPath}/user/deleteUser.do?id=${user.id}">删除</a></td>
    </tr>
</c:forEach>
</table>
<hr>
<h1>添加用户</h1>
<form action="${pageContext.request.contextPath}/user/insertUser.do" method="post"  enctype="multipart/form-data" id="useritem">
    <span>姓名:</span><input type="text" value="${user.username}" name="username" id="uname"/>&nbsp;&nbsp;
    <span>性别:</span>
    <select id="sex" name="sex">
        <option value="男"></option>
        <option value="女"></option>
    </select>&nbsp;&nbsp;
    <span>住址:</span><input type="text" value="${user.address}" name="address" id="address">&nbsp;&nbsp;
    <hr/>
    <img src="" id="imgSrc" height="100" width="100">
    <input type="file" id="upload" name="upload" class="upload">
    <input type="hidden" value="" id="head" name="head"/>
    <input type="submit" value="添加"/>
</form>

在这里插入图片描述具体操作没有展示,有什么问题可留言。
注意:上传文件的路径和格式也需要要在web.xml配置喔。
谢谢阅读。