快速上手的SSM整合

  在ssm整合之前,需要有spring,springmvc和mybatis的基础。
一:创库创表

create database db4;
use db4;
CREATE TABLE `user` (
        `uid` tinyint AUTO_INCREMENT,
        `uname` varchar(60),
        `usex` varchar(10),
        PRIMARY KEY (`uid`)
)

二:创建Web项目
  项目结构如下:
快速上手的SSM整合_第1张图片
三:准备jar包

效果图

快速上手的SSM整合_第2张图片 百度网盘地址获取jar和完整项目代码:

https://pan.baidu.com/s/1ZKztrvJXFmGMQ383tHqfDQ 提取码:upfk

四:编写配置文件

效果

快速上手的SSM整合_第3张图片

applicationContext.xml

 在WEB-INF目录下创建applicationContext.xml文件,内容如下:


<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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <import resource="spring-dao.xml">import>
    <import resource="spring-mvc.xml">import>
    <import resource="spring-service.xml">import>
    
beans>

spring-dao.xml

 在WEB-INF目录下创建spring-dao.xml文件,内容如下:


<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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    
    <context:property-placeholder location="WEB-INF/jdbc.properties"/>
    <bean id="driverManagerDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="username" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
    bean>

    
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="driverManagerDataSource"/>
        <property name="configLocation" value="WEB-INF/mybatis-config.xml"/>
        
        <property name="typeAliasesPackage" value="com.cht.entity"/>
    bean>

    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com/cht/dao/"/>
    bean>

beans>

mybatis-config.xml



<configuration>

        <settings>
            <setting name="logImpl" value="LOG4J"/>
        settings>

configuration>

jdbc.properties

jdbc.user=root
jdbc.password=123456
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db4?characterEncoding=utf-8&serverTimezone=UTC

spring-mvc.xml


<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
        https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">


    <context:component-scan base-package="com.cht.controller" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    context:component-scan>

    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    bean>

    <mvc:default-servlet-handler/>
    <mvc:annotation-driven >
        
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes" value="text/html;charset=UTF-8"/>
            bean>
        mvc:message-converters>
    mvc:annotation-driven>

beans>

spring-service.xml


<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" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">


    <context:component-scan base-package="com.cht">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    context:component-scan>

    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="driverManagerDataSource" />
    bean>

    
    <tx:annotation-driven  transaction-manager="transactionManager" />

beans>

web.xml


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

    <servlet>
        <servlet-name>dispatcherServletservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>/WEB-INF/applicationContext.xmlparam-value>
        init-param>
        
        <load-on-startup>1load-on-startup>
    servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServletservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>

    <filter>
        <filter-name>CharacterEncodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>utf-8param-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>
web-app>

五:编写程序代码进行测试

效果

快速上手的SSM整合_第4张图片
快速上手的SSM整合_第5张图片

编写实体类 entity包下

package com.cht.entity;

public class User {

    private Integer uid;
    private String uname;
    private String usex;

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public String getUname() {
        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

    public String getUsex() {
        return usex;
    }

    public void setUsex(String usex) {
        this.usex = usex;
    }

    @Override
    public String toString() {
        return "User{" +
                "uid=" + uid +
                ", uname='" + uname + '\'' +
                ", usex='" + usex + '\'' +
                '}';
    }
}

UserMapper.java

package com.cht.dao;

import com.cht.entity.User;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import java.util.List;
@Repository
public interface UserMapper {

    List<User> selectAll();

    Integer addUser(User user);
}

UserMapper.xml



<mapper namespace="com.cht.dao.UserMapper">
    <select id="selectAll" resultType="com.cht.entity.User">
        select * from user
    select>
    <insert id="addUser" parameterType="User">
        insert into user values (null,#{uname},#{usex})
    insert>
mapper>

UserServices

package com.cht.services;

import com.cht.entity.User;

import java.util.List;

public interface UserServices {
    List<User> selectAll();

    String addUser(User user);
}

UserServicesImpl

package com.cht.services;

import com.cht.dao.UserMapper;
import com.cht.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServicesImpl implements UserServices {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> selectAll() {
        return userMapper.selectAll();
    }

    @Transactional
    @Override
    public String addUser(User user) {
        Integer i = userMapper.addUser(user);
        //制造异常,看看事务是否发挥作用,如果发挥作用,那么将不会添加成功!!!因为被回滚了!!!当然了,客户端会报500错误
        //注意这里不要try catch 否则事务会失效
        Integer num = 1/0;
        if(i!=0){
            return "添加成功";
        }else {
            return "添加失败";
        }
    }
}

TestController

package com.cht.controller;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;
@Controller
public class TestController {

    static Logger logger = Logger.getLogger(TestController.class);

    @ResponseBody
    @RequestMapping("/message")
    public String message(){
        logger.info("测试spring-mvc.xml下的消息转换器是否成功解决乱码");
        return "你好,我是舞动程序";
    }

    @RequestMapping("/test")
    public String test(String wenben, Map<String,Object> map){
        logger.info("测试web.xml下的filter过滤器是否解决乱码");
        map.put("wenben",wenben);
        return "index";
    }
}

UserController

package com.cht.controller;

import com.cht.entity.User;
import com.cht.services.UserServices;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

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

    @Autowired
    private UserServices userServices;

    static Logger logger = Logger.getLogger(UserController.class);

    @RequestMapping("/query")
    public String selectAll(Map<String,Object> map){
        logger.info("我进来了");
        List<User> users = userServices.selectAll();
        for (User user:users) {
            System.out.println(user);
        }
        map.put("username",users);
        return "index";
    }
    @RequestMapping("/addUser")
    @ResponseBody
    public String addUser(Map<String,Object> map){
        User user = new User();
        user.setUname("陈哈哈");
        user.setUsex("男");
        String mes = userServices.addUser(user);
        System.out.println(mes);
        return mes;
    }
}

log4j.properties

log4j.rootLogger=DEBUG,console,file

#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=【%c】-%m%n

#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/wudongchengxu.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=【%p】【%d{yy-MM-dd}】【%c】%m%n

#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

六:编写页面

在web目录下新建两个jsp文件

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: wudongchengxu
  Date: 2021/5/12
  Time: 20:47
  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>
用户信息:${username}
<br/>
接收表单的值:${wenben}
</body>
</html>

send.jsp

<%--
  Created by IntelliJ IDEA.
  User: wudongchengxu
  Date: 2021/5/12
  Time: 20:47
  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>
  <form action="/test" method="post">
      <input type="text" name="wenben"/>
      <input type="submit" value="提交">
  </form>
</body>
</html>

七:测试

测试UserController下的selectAll

先查看user表有几条记录,如下:

快速上手的SSM整合_第6张图片 让我们启动Tomcat,然后在地址栏上输入:

http://localhost:8080/user/query即可,如下:
快速上手的SSM整合_第7张图片

测试UserController下的addUser

测试http://localhost:8080/user/addUser

快速上手的SSM整合_第8张图片 注意,以上异常是我故意造成的异常,主要是看事务是否发挥作用了,如果发挥作用,那么添加用户时,即使成功添加也会回滚,也就是相当于没添加,让我们查询一下数据库,如下: 快速上手的SSM整合_第9张图片 看到没有,不管我怎么刷新,陈哈哈就是没有,其实它已经添加成功了,只是遇到异常回滚了而已,那么也就说明事务配置成功了。

测试TestController下的message方法

http://localhost:8080/message

快速上手的SSM整合_第10张图片 没有乱码,说明spring-mvc下的消息转换器配置成功。

测试TestController下的message方法test方法

http://localhost:8080/send.jsp

快速上手的SSM整合_第11张图片 点击提交即可,如下: 快速上手的SSM整合_第12张图片 说明web.xml下面字符过滤器其了作用。那么到此,ssm就已经整合成功了。

你可能感兴趣的:(java,spring,mybatis,springmvc,java)