【Spring】整合【SpringMVC】

导入依赖

XML 复制代码
<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
</dependency>
<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
 </dependency>
<dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
      <scope>provided</scope>
</dependency>
<!--Jackson-->
<dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.13.4</version>
 </dependency>

配置SpringMVC

XML 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
                      https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
         version="5.0">
  <!--配置监听器,监听器的作用是监听Servlet容器启动时创建Spring容器-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring.xml</param-value>
  </context-param>
  <!--配置DispatcherServlet,该Servlet有两个作用:-->
  <!--1:对于项目的所有请求先到达该Servlet,然后由该Servlet统一分发或路由-->
  <!--2: 创建Web环境下Spring容器-->
  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>  
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <!--【可选】配置字符编码过滤器-->
  <filter>
    <filter-name>characterFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>characterFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

【注意】配置DispatcherServlet时,如果不指定配置文件,SpringMVC会在WEB-INF目录下寻找以servlet-name中配置的名称加-servlet寻找配置文件,例如:servlet-name中配置了名称为dispatcher,SpringMVC会寻找名称为dispatcher-servlet.xml的配置文件,通常情况下,需要指定固定位置的固定配置文件,如上例中所示。

SpringMVC.XML

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"
       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="cn.bytecollege.controller"/>
    <!--配置视图解析器,可以使用prefix指定页面的前缀,例如页面存放路径,使用Suffix执行后缀,通常指定页面的扩展名-->
    <bean name="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--配置消息转换,也就是说当使用@ResponBody注解时,需要此处的配置,并且需要导入Jackson依赖-->
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/plain;charset=UTF-8</value>
                        <value>text/html;charset=utf-8</value>
                        <value>application/json</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
    <!--
        mapping:静态资源的请求路径
        location:静态资源存放的本地路径
    -->
    <mvc:resources mapping="/static/**" location="/WEB-INF/static/"/>
</beans>

SpringMVC常用注解

@Controller

该注解标注在控制器上,表明该类可以接收请求,具体的请求由类中的方法处理。

@RequestMapping

java 复制代码
package org.springframework.web.bind.annotation;
​
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
​
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {
    String name() default "";
    //该方法或者该类的请求路径
    @AliasFor("path")
    String[] value() default {};
    //等价于value
    @AliasFor("value")
    String[] path() default {};
    //设置接收的请求方式,如果不配置该属性,则可以接收所有类型的请求, 如果配置,则只能接收指定类型的请求
    RequestMethod[] method() default {};
    //必须携带固定的参数才可以处理请求例如:name=admin
    String[] params() default {};
    //响应头中必须包含固定参数才可以处理请求
    String[] headers() default {};
    //请求数据类型是指定类型的请求可以处理
    String[] consumes() default {};
    //
    String[] produces() default {};
}

通常,可以使用该注解的替代注解,常用的有:

  • @GetMapping

  • @PostMapping

属性 类型 是否必要 说明
value String[] 用于将指定请求的地址映射到方法
name String 给映射地址指定一个别名
method RequestMethod[] 映射指定请求的方法,包括GET、POST、HEAD、OPTIONS、PUT、PATCH、DELETE、TRACE
consumes String[] 指定处理请求的提交内容(Content-Type),例如:application/json
produces String[] 指定返回的内容类型,返回的内容类型必须是request请求头中所包含的类型
params String[] 指定request中必须包含某些参数值时,才让该方法处理请求
headers String[] 指定request中必须包含某些指定的header值,才能让该方法处理请求
path String[] 用于将指定请求的地址映射到方法

@RequestMapping 不但支持标准的 URL,还支持 Ant 风格(?、*和**字符)的和带{xxx}占位符的URL。以下 URL 都是合法的。

  • /user/*/createUser∶ 匹配/user/aa/createUser、/user/bbb/createUser等 URL。

  • /user/**/createUser∶匹配/user/createUser、/user/aaa/bbb/createUser 等URL。

  • /user/createUser??∶匹配/user/createUseraa、/user/createUserbb等 URL。

  • /user/{userld}∶匹配 user/123、user/456 等URL。

  • /user/**/{userId}∶匹配 user/aa/bbb/123、user/aaa/456等 URL。

  • company/{companyld}/user/{userId}/detail∶匹配 company/123/user/456/detail 等
URL。

@RequestParam

该注解的作用是将请求参数和Controller方法参数进行绑定

java 复制代码
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestParam {
​
   /**
    * 将前端请求参数的名称(即请求参数的name或者key)与方法参数绑定
    * Alias for {@link #name}.
    */
   @AliasFor("name")
   String value() default "";
   
   /**
    * The name of the request parameter to bind to.
    * @since 4.2
    */
   @AliasFor("value")
   String name() default "";
​
   /**
    * Whether the parameter is required.
    * <p>Defaults to {@code true}, leading to an exception being thrown
    * if the parameter is missing in the request. Switch this to
    * {@code false} if you prefer a {@code null} value if the parameter is
    * not present in the request.
    * <p>Alternatively, provide a {@link #defaultValue}, which implicitly
    * sets this flag to {@code false}.
    * 如果不传该参数则抛出异常
    */
   boolean required() default true;
​
   /**
    * The default value to use as a fallback when the request parameter is
    * not provided or has an empty value.
    * <p>Supplying a default value implicitly sets {@link #required} to
    * {@code false}.
    */
   String defaultValue() default ValueConstants.DEFAULT_NONE;
​
}

@PathVariable

该注解的作用时将请求路径中的参数绑定到Controller方法参数

java 复制代码
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PathVariable {
​
   /**
    * 请求路径中参数的名称
    * Alias for {@link #name}.
    */
   @AliasFor("name")
   String value() default "";
​
   /**
    * The name of the path variable to bind to.
    * @since 4.3.3
    * 作用同value
    */
   @AliasFor("value")
   String name() default "";
​
   /**
    * Whether the path variable is required.
    * <p>Defaults to {@code true}, leading to an exception being thrown if the path
    * variable is missing in the incoming request. Switch this to {@code false} if
    * you prefer a {@code null} or Java 8 {@code java.util.Optional} in this case.
    * e.g. on a {@code ModelAttribute} method which serves for different requests.
    * @since 4.3.3
    * 是否必须传递该参数,如果为null则抛出异常
    */
   boolean required() default true;
​
}

@ResonseBody

将方法的返回值转成Json格式的字符串或者Json对象

@RequestBody

将前端发送的JSON格式的数据绑定到方法参数的对象中

@SessionAttribute

获取使用value或者name指定名称的在Session中保存的数据

@CookieValue

获取使用value或者name指定名称的在Cookie中保存的数据

Spring整合MyBatis

导入依赖

XML 复制代码
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis-spring</artifactId>
  <version>2.0.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.5.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>8.0.28</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>druid</artifactId>
  <version>1.2.11</version>
</dependency>
<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
</dependency>

配置Mybatis

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:component-scan base-package="cn.bytecollege.service"/>
    <!--加载数据库配置文件-->
    <context:property-placeholder location="classpath:data.properties"/>
    <!--配置数据源-->
    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="url" value="${url}"/>
        <property name="username" value="${user}"/>
        <property name="password" value="${password}"/>
​
​
        <!-- 配置初始化大小、最小、最大 -->
        <property name="initialSize" value="5" />
        <property name="minIdle" value="10" />
        <property name="maxActive" value="20" />
​
        <!-- 配置获取连接等待超时的时间 -->
        <property name="maxWait" value="6000" />
​
        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="2000" />
​
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="600000" />
        <property name="maxEvictableIdleTimeMillis" value="900000" />
​
        <property name="validationQuery" value="select 1" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
​
        <property name="keepAlive" value="true" />
        <property name="phyMaxUseCount" value="1000" />
​
        <!-- 配置监控统计拦截的filters -->
        <property name="filters" value="stat" />
    </bean>
    <!--配置SqlSessionFactoryBean-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--配置数据源-->
        <property name="dataSource" ref="dataSource"/>
        <!--配置Mybatis的配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--配置Mapper映射器的位置-->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>
    <!--配置Mapper接口的位置-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.bytecollege.mapper"></property>
    </bean>
</beans>
相关推荐
秋说2 分钟前
【Java代码审计 | 第六篇】XSS防范
java·xss
何中应21 分钟前
你为什么要写博客?
java·后端·程序员创富
handsomestWei37 分钟前
quartz在双机热备场景定时任务双份执行冲突解决方案
java·quartz·双机热备
lyrhhhhhhhh38 分钟前
手写一个Tomcat
java·tomcat
孑么1 小时前
力扣 编辑距离
java·数据结构·算法·leetcode·职场和发展·贪心算法·动态规划
夏天的味道٥6 小时前
使用 Java 执行 SQL 语句和存储过程
java·开发语言·sql
冰糖码奇朵8 小时前
大数据表高效导入导出解决方案,mysql数据库LOAD DATA命令和INTO OUTFILE命令详解
java·数据库·sql·mysql
浪九天9 小时前
Java直通车系列13【Spring MVC】(Spring MVC常用注解)
java·后端·spring
小斌的Debug日记9 小时前
框架基本知识总结 Day16
redis·spring