• SSM框架集成各配置文件


    SSM框架集成各配置文件

    Spring Spring MVC Mybatis 的整合SpringMVC相当于Spring的一个组件 本来就是一个家族的不存在整合的问题,所以主要就是Spring于Mybatis的整合

    第一步 创建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.huang</groupId>
        <artifactId>SSM</artifactId>
        <version>1.0-SNAPSHOT</version>
        <dependencies>
            <!--   mysql驱动-->
            <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.15</version>
            </dependency>
            <!--    spring 管理jdbc依赖-->
            <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>5.2.1.RELEASE</version>
            </dependency>
            <!-- 数据库连接池依赖 -->
            <dependency>
                <groupId>com.mchange</groupId>
                <artifactId>c3p0</artifactId>
                <version>0.9.5.2</version>
            </dependency>
            <!--    mybatis依赖-->
            <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.2</version>
            </dependency>
            <!--    mybatis spring 整合依赖-->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>2.0.2</version>
            </dependency>
    
    
            <!--    junit依赖-->
            <!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api -->
            <dependency>
                <groupId>org.junit.jupiter</groupId>
                <artifactId>junit-jupiter-api</artifactId>
                <version>5.3.2</version>
                <scope>test</scope>
            </dependency>
            <!--  springMVC 框架依赖-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>5.1.9.RELEASE</version>
            </dependency>
            <!--  servlet 框架依赖-->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
                <version>2.5</version>
            </dependency>
            <!--  jsp依赖-->
            <dependency>
                <groupId>javax.servlet.jsp</groupId>
                <artifactId>jsp-api</artifactId>
                <version>2.2</version>
            </dependency>
            <!--    jackson    转json字符串依赖-->
    
            <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.10.1</version>
            </dependency>
            <!--第三方浏览器接收上传文件依赖-->
            <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>1.3.3</version>
            </dependency>
            <!--Apache开源的一个工具包,其封装了对IO的常见操作-->
            <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
            <dependency>
                <groupId>commons-io</groupId>
                <artifactId>commons-io</artifactId>
                <version>2.4</version>
            </dependency>
    <!--        aop织入包-->
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>1.9.5</version>
            </dependency>
        </dependencies>
        <build>
            <resources>
                <resource>
                    <directory>src/main/resource</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                </resource>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                </resource>
            </resources>
    
    
        </build>
    
    </project>
    

    第二步 创建Mybatis配置文件

    mybatis整合导Spring中 其配置文件可以完全不要 但为让整体结构清晰习惯配置此文件mybatis-config.xml

    在此文件中只配置 java实体类的别名 注册mapper文件 数据库日志

    <?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>
       <!--   配置日志-->
       <settings>
           <setting name="logImpl" value="STDOUT_LOGGING"/>
       </settings>
       <!--    给实体类 起别名-->
       <typeAliases>
           <package name="com.huang.pojo"/>
       </typeAliases>
    
       <!--    注册 mapper.xml-->
       <mappers>
           <mapper class="com.huang.dao.UserMapper"/>
           <mapper class="com.huang.dao.CustomerMapper"/>
       </mappers>
    </configuration>
    

    第三步 将Mybatis以及Dao层托管给Spring

    创建spring-dao.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"
           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="classpath:db.properties"/>
        <!--    数据库连接池  c3p0-->
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="${jdbc.driver}"/>
            <property name="jdbcUrl" value="${jdbc.url}"/>
            <property name="user" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
    
            <!-- c3p0连接池的私有属性 -->
            <property name="maxPoolSize" value="30"/>
            <property name="minPoolSize" value="10"/>
            <!-- 关闭连接后不自动commit -->
            <property name="autoCommitOnClose" value="false"/>
            <!-- 获取连接超时时间 -->
            <property name="checkoutTimeout" value="10000"/>
            <!-- 当获取连接失败重试次数 -->
            <property name="acquireRetryAttempts" value="2"/>
    
        </bean>
        <!--   注入sqlSessionFactory-->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!--        数据源-->
            <property name="dataSource" ref="dataSource"/>
            <!--        读取mybatis配置文件-->
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
        </bean>
        <!--    配置dao接口自动扫描包 动态实现Dao接口可以注入spring容器-->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
            <!--        扫描要扫描的包-->
            <property name="basePackage" value="com.huang.dao"/>
        </bean>
    
    </beans>
    

    ​ db.properties 配置数据库连接信息

    jdbc.driver=com.mysql.cj.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/boot_crm?useSSL=true&useUnicode=true&characterEncoding=UTF-8
    jdbc.username=root
    jdbc.password=Root
    

    第四步 将Service层 托管到Spring

    <?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
            https://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
            https://www.springframework.org/schema/aop/spring-aop.xsd">
        <!--    扫描 service 下的包-->
        <context:component-scan base-package="com.huang.service"/>
    
        <!--  配置声明式事务-->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"/>
        </bean>
        <!--   结合aop 实现事务织入-->
        <!--    配置事务通知-->
        <tx:advice id="transactionInterceptor" transaction-manager="transactionManager">
            <tx:attributes>
                <tx:method name="add" propagation="REQUIRED"/>
                <tx:method name="del" propagation="REQUIRED"/>
                <tx:method name="update" propagation="REQUIRED"/>
                <tx:method name="search" read-only="true"/>
                <tx:method name="get" read-only="true"/>
            </tx:attributes>
        </tx:advice>
        <!--    配置事务切入-->
        <aop:config>
            <!-- 切入点-->
            <aop:pointcut id="pointCut" expression="execution( * com.huang.dao.*.*(..))"/>
            <!--  执行环绕增加-->
            <aop:advisor advice-ref="transactionInterceptor" pointcut-ref="pointCut"/>
        </aop:config>
    </beans>
    

    第五步创建SpringMVC配置文件

    <?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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/mvc
            https://www.springframework.org/schema/mvc/spring-mvc.xsd
             http://www.springframework.org/schema/context
            https://www.springframework.org/schema/context/spring-context.xsd">
        <!--    1-注解驱动-->
        <mvc:annotation-driven>
            <!--        spring处理乱码问题-->
            <mvc:message-converters register-defaults="true">
                <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                    <constructor-arg value="UTF-8"/>
                </bean>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                    <property name="objectMapper">
                        <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                            <property name="failOnEmptyBeans" value="false"/>
                        </bean>
                    </property>
                </bean>
            </mvc:message-converters>
        </mvc:annotation-driven>
        <!--    2-静态资源过滤-->
        <mvc:default-servlet-handler/>
    
        <!--    3-扫描包-->
        <context:component-scan base-package="com.huang.controller"/>
        <!--    4-视图解析器-->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="suffix" value=".jsp"/>
            <property name="prefix" value="/WEB-INF/jsp/"/>
        </bean>
    
        <!--5-配置文件解析器-->
        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <!-- 设置文件上传的最大大小-->
            <property name="maxUploadSize" value="10485760"/>
        </bean>
        <!-- 6-接口跨域配置 -->
        <mvc:cors>
            <mvc:mapping path="/**"
                         allowed-origins="*"
                         allowed-methods="POST, GET, OPTIONS, DELETE, PUT"
                         allowed-headers="Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
                         allow-credentials="true"/>
        </mvc:cors>
    
    </beans>
    

    创建一个 applicationContext.xml文件整合Spring配置文件

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd">
        <import resource="classpath:spring-dao.xml"/>
        <import resource="classpath:spring-service.xml"/>
        <import resource="classpath:spring-mvc.xml"/>
    </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">
        <!--    DispatchServlet 将托管给spring的java类配置给web-->
        <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:applicationContext.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>springMVC</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
        <!--    乱码过滤json字符串-->
        <filter>
            <filter-name>encodingFilter</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>encodingFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
        <!--    session 过期时间-->
        <session-config>
            <session-timeout>15</session-timeout>
        </session-config>
        <!-- 允许跨域请求 -->
        <filter>
            <filter-name>SimpleCORSFilter</filter-name>
            <filter-class>com.huang.util.SimpleCORSFilter</filter-class>
            <init-param>
                <param-name>IsCross</param-name>
                <param-value>true</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>SimpleCORSFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    </web-app>
    

    1.浏览器上传文件类

    package com.huang.controller;
    
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.multipart.MultipartFile;
    
    import javax.servlet.http.HttpServletRequest;
    import java.io.File;
    import java.io.IOException;
    import java.util.UUID;
    
    @RestController
    public class UpLoadFile {
    
        @RequestMapping(value = "/upload",method = RequestMethod.POST)
        public String fileupload(HttpServletRequest request, MultipartFile upload) throws IOException {
    
    //        文件上传
            System.out.println("上传文件");
            //要上传的位置
            String path = request.getSession().getServletContext().getRealPath("/upload/");
            File file=new File(path);
            if(!file.exists()){
                file.mkdirs();
            }
            //获取上传文件的名字
            String filename = upload.getOriginalFilename();
            String uuid = UUID.randomUUID().toString().replace("-", "");
            //给上传的文件重新命名避免出现重名
            filename=uuid+"_"+filename;
            upload.transferTo(new File(path,filename));
            return "success";
        }
    
    }
    
    

    开启跨域类

    package com.huang.util;
    
    import javax.servlet.*;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    /**
     * 跨域请求 处理
     */
    public class SimpleCORSFilter implements Filter {
        private boolean isCross = false;
    
        @Override
        public void destroy() {
            isCross = false;
        }
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
            if (isCross) {
                HttpServletRequest httpServletRequest = (HttpServletRequest) request;
                HttpServletResponse httpServletResponse = (HttpServletResponse) response;
                System.out.println("检测到请求: " + httpServletRequest.getServletPath());
                httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
                httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
                httpServletResponse.setHeader("Access-Control-Max-Age", "0");
                httpServletResponse.setHeader("Access-Control-Allow-Headers",
                        "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
                httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
                httpServletResponse.setHeader("XDomainRequestAllowed", "1");
            }
            chain.doFilter(request, response);
        }
    
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
            String isCrossStr = filterConfig.getInitParameter("IsCross");
            isCross = isCrossStr.equals("true") ? true : false;
            System.out.println(isCrossStr);
        }
    
    }
    
  • 相关阅读:
    [ZJOI2007]仓库建设(斜率dp优化)
    [HNOI2008]玩具装箱toy(斜率优化dp)
    2019牛客暑期多校训练营(第十场)F-Popping Balloons
    2019牛客暑期多校训练营(第十场)B-Coffee Chicken
    子集的生成—二进制枚举
    2019牛客暑期多校训练营(第九场)D-Knapsack Cryptosystem(思维+子集和)
    2019牛客暑期多校训练营(第九场) E-All men are brothers(并查集+组合数学)
    字符串的最小表示法
    2019牛客暑期多校训练营(第八场)
    [HDU4734] 不要62(数位dp入门)
  • 原文地址:https://www.cnblogs.com/huangshen/p/12410259.html
Copyright © 2020-2023  润新知