快速搭建SSM框架

文章目录

  • 1. 阶段一:基本框架搭建
    • 1.1 创建maven工程
    • 1.2 设置Maven为本地maven
    • 1.3 指定打包方式为war
    • 1.4 配置工程结构
      • 1.4.1 指定web.xml
      • 1.4.2 指定class文件输出路径
    • 1.5 pom.xml中导入项目所需依赖jar包
    • 1.6 创建项目目录
  • 2. 阶段二:配置文件编写
    • 2.1 编写jdbc.properties文件
    • 2.2 配置springmvc.xml文件
      • 2.2.1 自定义异常处理类1
      • 2.2.2自定义异常处理类2
    • 2.2 配置spring上下文环境配置文件applicationContext.xml
    • 2.3 spring配置类SpringConfig
    • 2.4 配置web.xml
    • 2.5 配置logback.xml文件
  • 3.阶段三:部署到Tomcat服务器
  • 4. 阶段五:测试
    • 4.1 创建实体类
    • 4.2 创建controller
    • 4.3 创建jsp
    • 4.3 开启tomcat,访问

1. 阶段一:基本框架搭建

1.1 创建maven工程

快速搭建SSM框架_第1张图片

快速搭建SSM框架_第2张图片

1.2 设置Maven为本地maven

快速搭建SSM框架_第3张图片
快速搭建SSM框架_第4张图片

1.3 指定打包方式为war

在pom.xml文件中
1. 设置打包方式为war
2. 添加springMVC依赖jar包

<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.0modelVersion>

    <groupId>edu.xjagroupId>
    <artifactId>SSM-studentartifactId>
    <version>1.0-SNAPSHOTversion>

    <packaging>warpackaging>
    
    <dependencies>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>5.3.3version>
        dependency>
 dependencies>
project>
编译打包
项目下自动添加web模型

快速搭建SSM框架_第5张图片
快速搭建SSM框架_第6张图片
快速搭建SSM框架_第7张图片

1.4 配置工程结构

1.4.1 指定web.xml

指定web.xml位置
src/main/webapp/WEN-INF/web.xml

快速搭建SSM框架_第8张图片
快速搭建SSM框架_第9张图片

1.4.2 指定class文件输出路径

快速搭建SSM框架_第10张图片

1.5 pom.xml中导入项目所需依赖jar包


<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.0modelVersion>

    <groupId>edu.xjagroupId>
    <artifactId>SSM-studentartifactId>
    <version>1.0-SNAPSHOTversion>
    
    <packaging>warpackaging>
    
    <properties>
        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
    properties>


    
    <dependencies>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>5.3.3version>
        dependency>

        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-txartifactId>
            <version>5.3.3version>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>5.3.3version>
        dependency>

        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>5.3.3version>
        dependency>

        
        
        <dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjweaverartifactId>
            <version>1.9.1version>
        dependency>
        <dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjrtartifactId>
            <version>1.9.1version>
        dependency>

        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.10version>
        dependency>

        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.26version>
        dependency>

        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>2.0.6version>
        dependency>
        
        
        <dependency>
            <groupId>org.junit.jupitergroupId>
            <artifactId>junit-jupiterartifactId>
            <version>5.9.0version>
            <scope>testscope>
        dependency>

        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <version>5.3.3version>
            <scope>testscope>
        dependency>

        
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>javax.servlet-apiartifactId>
            <version>4.0.1version>
            <scope>providedscope>
        dependency>

        <dependency>
            <groupId>javax.servlet.jspgroupId>
            <artifactId>javax.servlet.jsp-apiartifactId>
            <version>2.3.3version>
        dependency>

        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
        dependency>


        
        <dependency>
            <groupId>com.github.pagehelpergroupId>
            <artifactId>pagehelperartifactId>
            <version>5.3.1version>
        dependency>

        
        <dependency>
            <groupId>org.hibernate.validatorgroupId>
            <artifactId>hibernate-validatorartifactId>
            <version>6.2.3.Finalversion>
        dependency>
        <dependency>
            <groupId>javax.validationgroupId>
            <artifactId>validation-apiartifactId>
            <version>2.0.1.Finalversion>
        dependency>

        
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger2artifactId>
            <version>2.9.2version>
        dependency>

        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger-uiartifactId>
            <version>2.9.2version>
        dependency>

        
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-databindartifactId>
            <version>2.12.5version>
        dependency>


        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.18.24version>
            <scope>providedscope>
        dependency>

        
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-apiartifactId>
            <version>1.7.32version>
            <type>jartype>
            <scope>compilescope>
        dependency>

        <dependency>
            <groupId>ch.qos.logbackgroupId>
            <artifactId>logback-classicartifactId>
            <version>1.2.3version>
            <type>jartype>
            <scope>compilescope>
        dependency>
    dependencies>
project>

1.6 创建项目目录

快速搭建SSM框架_第11张图片
在这里插入图片描述

2. 阶段二:配置文件编写

2.1 编写jdbc.properties文件

项目需要连接数据库,需要在resources下编写jdbc.properties文件
#1. 驱动类全限定名
jdbc.driver=com.mysql.cj.jdbc.Driver
#2.数据库url
jdbc.url=jdbc:mysql://localhost:3306/student_course?serverTimezone=Asia/Shanghai&characterEncoding=utf-8
#3. 数据库用户名
jdbc.username=root
#4. 用户密码
jdbc.password=zx200061、
#5. 初始化数据库连接数量
jdbc.initialSize=3
#6. 最大活动数量
jdbc.maxActive=10

2.2 配置springmvc.xml文件

在resources目录下编写springmvc.xml文件
主要内容
1. 上下文开启注解扫描,扫描控制器包
2. 上下文 向容器自动注册 
3.  添加视图解析器bean
4. 添加自定义异常处理类bean(MyCustomException1类自定义编写在exception包)
5. 添加表单数据验证器bean
6.  添加消息源Bean
7. swagger静态资源访问配置
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="edu.xja.controller,edu.xja.config.controller"/>
    
    <context:annotation-config/>


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

    
    <bean class="edu.xja.exception.MyCustomException1"/>
    
    

    
    <bean id="validator"
          class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        
        <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>
        
        <property name="validationMessageSource" ref="messageSource"/>
    bean>

    
    <bean id="messageSource"
          class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        
        <property name="basenames">
            <list>
                
                <value>classpath:messagesvalue>
            list>
        property>
        <property name="useCodeAsDefaultMessage" value="false"/>
        
        <property name="defaultEncoding" value="UTF-8"/>
    bean>


    
    
    <mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
    <mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>

    
    <mvc:annotation-driven validator="validator">
    mvc:annotation-driven>
beans>

2.2.1 自定义异常处理类1

实现HandlerExceptionResolver接口的异常处理类
package edu.xja.exception;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * 方式一:自定义异常处理类
 * 实现接口
 */
public class MyCustomException1 implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("errorMsg",e.getMessage());
        mv.setViewName("error");
        return mv;
    }
}

2.2.2自定义异常处理类2

使用注解的异常处理类
1. 类上用注解@ControllerAdvice
2. 方法用注解@ExceptionHandler
package edu.xja.exception;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

/**
 * 方式二:自定义异常处理类,使用注解
 */
@ControllerAdvice
public class MyCustomException2{

    /**
     * 使用异常处理器注解
     * @param e
     * @return
     */
    @ExceptionHandler
    public ModelAndView handlerError(Exception e){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("error");
        mv.addObject("errorMsg",e.getMessage());
        return mv;
    }

}

2.2 配置spring上下文环境配置文件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 http://www.springframework.org/schema/context/spring-context.xsd">

    
    <context:component-scan base-package="edu.xja.service,edu.xja.config.service"/>

beans>

2.3 spring配置类SpringConfig

在config.service包下创建SpringConfig
1. 向IOC容器注入DataSource 数据源bean
2. 向IOC容器注入SqlSessionFactory 会话工厂bean
package edu.xja.config.service;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;

/**
 * spring配置类
 */
@org.springframework.context.annotation.Configuration
@PropertySource("classpath:jdbc.properties")
@MapperScan("edu.xja.dao") //只扫描
class SpringConfig {
    //属性
    @Value("${jdbc.driver}")
    private String driverClassName;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    /**
     * 向容器添加数据源bean
     * @return
     */
    @Bean
    public DataSource dataSource(){
        //1. 实例化数据源驱动管理对象
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        //2. 为数据源驱动管理对象属性赋值
        //(1)驱动类名
        dataSource.setDriverClassName(driverClassName);
        //(2)数据源URL
        dataSource.setUrl(url);
        //(3)连接用户名
        dataSource.setUsername(username);
        //(4)用户密码
        dataSource.setPassword(password);

        //3. 返回数据源驱动管理对象
        return dataSource;
    }


    /**
     * session会话工厂
     * @param dataSource
     * @return
     */
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource){
       try{
           //1. 实例化session会话工厂SqlSessionFactoryBean
           SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
           //2. set属性
           //(1)set数据源
           sqlSessionFactoryBean.setDataSource(dataSource);
           //(2)set别名包
           sqlSessionFactoryBean.setTypeAliasesPackage("edu.xja.entity");
           //实例化路径匹配资源模式解析器
           PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
           //获取mapper资源
           Resource[] resources = resolver.getResources("classpath:mapper/*.xml");
           //(3)set 本地mapper资源
           sqlSessionFactoryBean.setMapperLocations(resources);
           //实例化配置类
           org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
           //为配置类设置下划线转驼峰为true
           configuration.setMapUnderscoreToCamelCase(true);
           //(4)set配置类
           sqlSessionFactoryBean.setConfiguration(configuration);
           //3. 返回SqlSessionFactory
           return sqlSessionFactoryBean.getObject();
       }catch(Exception e){
           e.printStackTrace();
       }
       return null;
    }

}

2.4 配置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">
    
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:applicationContext.xmlparam-value>
    context-param>

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


    
    <servlet>
        <servlet-name>dispatcherServletservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:springmvc.xmlparam-value>
        init-param>
        
        <load-on-startup>1load-on-startup>
    servlet>
    
    <servlet-mapping>
        <servlet-name>dispatcherServletservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>
    
web-app>

2.5 配置logback.xml文件

resources目录下创建logback.xml文件

<configuration  scan="true" scanPeriod="60 seconds" debug="false">
    <appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
        
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
        filter>
        <encoder>
         
            <pattern>%date{yyyy-MM-dd HH:mm} | %highlight(%-5level) | %boldYellow(%thread) | %boldGreen(%logger{36}) | %msg%npattern>
        encoder>
    appender>

    <appender name="RollingFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
        
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>DEBUGlevel>
        filter>
        <File>logs/logback.logFile>
        
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>logs/jx-film-%d{yyyy-MM-dd-HH}.%i.zipfileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>10MBmaxFileSize>
            timeBasedFileNamingAndTriggeringPolicy>
            <maxHistory>672maxHistory>
        rollingPolicy>
        <encoder>
            <pattern>%d{MM:dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%npattern>
        encoder>
    appender>

    <appender name="ErrorConsole" class="ch.qos.logback.core.ConsoleAppender">
        
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>DEBUGlevel>
        filter>
        <encoder>
            <pattern>%date{yyyy-MM-dd HH:mm:ss} | %highlight(%-5level) | %boldYellow(%thread) | %boldGreen(%logger{36}) | %msg%npattern>
        encoder>
    appender>

    
    <logger name="edu.xja" level="INFO"/>
    <logger name="org.springframework.web" level="INFO"/>
    <logger name="org.springframework.core.env.PropertySourcesPropertyResolver" level="WARN"/>


    
    <root level="INFO">
        
        <appender-ref ref="Console"/>
        <appender-ref ref="RollingFile"/>
    root>
configuration>

3.阶段三:部署到Tomcat服务器

快速搭建SSM框架_第12张图片

快速搭建SSM框架_第13张图片

启动tomcat,启动成功表示能访问到资源

4. 阶段五:测试

4.1 创建实体类

package edu.xja.entity;

import org.hibernate.validator.constraints.Length;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;
import java.io.Serializable;

@Component
public class UserLoginVO implements Serializable {
    @NotNull(message = "用户id不能为空")
    private Integer id;
    @NotNull
    @Length(min=2,max = 8,message = "用户名不能少于2位不能大于8位")
    private String username;


    public UserLoginVO() {
    }

    public UserLoginVO(Integer id, @Length(min = 2, max = 8, message = "用户名不能少于2位不能大于8位") String username) {
        this.id = id;
        this.username = username;
    }



    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

4.2 创建controller

package edu.xja.controller;

import edu.xja.entity.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * 测试controller
 */
@Controller
@Api("测试使用controller")
@Validated  //验证注解
public class HelloController {

    @GetMapping("hello")
    public ModelAndView hello(){
        ModelAndView view = new ModelAndView("hello");
        view.addObject("hello","hello");
        return  view;
    }

    @ApiOperation(value="根据主键获取学生信息",notes="输入视图,获取有错误信息属性的视图")
    @RequestMapping("/error")
    @ApiModelProperty(value = "模拟异常" ,required = true)
    public ModelAndView upload(@ApiParam("模型和视图") ModelAndView modelAndView) throws Exception {
        //模拟异常
        int i = 100/0;
        ModelAndView view = new ModelAndView("error");
        return  modelAndView;
    }

    /**
     * 指定验证参数UserLoginVO user
     * @param user
     * @param result
     * @return
     */
    @PostMapping("/login")
    public ModelAndView login(@Validated UserLoginVO user, BindingResult result){

        ModelAndView mv=new ModelAndView("success");
        if (result.hasErrors()) {
            mv.addObject("errorMsg",result.getFieldError("userName").getDefaultMessage());
            mv.setViewName("error");
            return mv;
        }
        System.out.println("登录成功");
//        mv.addObject("loginError","")
        return mv;
    }
}

4.3 创建jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: Lenovo
  Date: 2022/8/3
  Time: 8:25
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transition//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>添加用户title>
head>
<body>
<form action="${pageContext.request.contextPath}/login" method="post">
    用户id:<input type="text" name="id"><br>
    用户名:<input type="text" name="username"><br>
    <input type="submit" value="提交">
form>
body>
html>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Titletitle>
head>
<body>
    程序出现异常,异常信息如下:<br/>
    ${errorMsg}
body>
html>

4.3 开启tomcat,访问

快速搭建SSM框架_第14张图片
快速搭建SSM框架_第15张图片

快速搭建SSM框架_第16张图片

你可能感兴趣的:(SSM,spring,maven,java)