Java:SpringMvc--基于注解和xml开发

一、概述

1、定义:

SpringMVC是一种基于Java实现MVC模型的轻量级Web框架

2、优点:

使用简单、开发便捷(相比于Servlet)、灵活性强;

基于原生的 Servlet ,通过了功能强大的 前端控制器 DispatcherServlet ,对请求和响应进行统一
处理。

二、基于注解配置

1、导入依赖

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>6.0.4</version>
    </dependency>
    <dependency>
      <groupId>jakarta.servlet</groupId>
      <artifactId>jakarta.servlet-api</artifactId>
      <version>5.0.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.14.2</version>
    </dependency>

2、创建配置类并且将web.xml替换

配置类,扫描controller包,加载Controller控制器bean,扫描放行的SpringMvcSupport

@Configuration
@ComponentScan({"com.islunatic.controller","com.islunatic.config"})
@EnableWebMvc//开启自动转化为json数据的支持
public class SpringMvcConfig {
}

创建web项目入口配置类,设置拦截路径,解决post请求中文乱码问题  

public class SpringMvcInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{};
    }
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringMvcConfig.class};
    }
     //设置SpringMVC请求地址拦截规则
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
    //乱码处理
    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("UTF-8");
        return new Filter[]{filter};
    }
}

上面添加了静态资源,SpringMVC会拦截,需要在SpringConfig的配置类中将静态资源进行放行。

@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
        registry.addResourceHandler("/css/**").addResourceLocations("/css/");
        registry.addResourceHandler("/js/**").addResourceLocations("/js/");
        registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");
    }
}

 注: getServletMappings方法,设SpringMVC对应的请求映射路径,即SpringMVC拦截哪些请求

gwtServletApplicationContext用来加载SpringMVC环境

getRootApplicationContext用来加载Spring环境

3、编写controller类

@Controller
public class UserController {
    @RequestMapping("/user")
    @ResponseBody
    public String User(){
        System.out.println("user...");
        return "{muddle:spring}";
    }
    @RequestMapping(value = "/save")
    @ResponseBody
    //@RequestBody设置接受json数据
    public String save(@RequestBody User user){
        System.out.println(user);
        return "success";
    }
}
名称@Controller
类型类注解
位置SpringMVC控制器类定义上方
作用设定SpringMVC的核心控制器bean
名称@RequestMapping
类型类注解或方法注解
位置SpringMVC控制器类或方法定义上方
作用设置当前控制器方法请求访问路径,即配置映射路径
相关属性value(默认),请求访问路径
名称@ResponseBody
类型类注解或方法注解
位置SpringMVC控制器类或方法定义上方
作用设置当前控制器方法响应内容为当前返回值,无需解析。即返回json数据

4、当使用SpringConfig加载Bean的时候排除掉SpringMvc控制的Bean

@Configuration
@ComponentScan(value="com.islunatic",
    excludeFilters=@ComponentScan.Filter(
    	type = FilterType.ANNOTATION,
        classes = Controller.class
    )
)
public class SpringConfig {
}
  • excludeFilters属性:设置扫描加载bean时,排除的过滤规则

  • classes属性:设置排除的具体注解类,当前设置排除@Controller定义的bean

  • type属性:设置排除规则,当前使用按照bean定义时的注解类型进行排除;其中ANNOTATION:按照注解排除。

名称@ComponentScan
类型类注解
位置类定义上方
作用设置spring配置类扫描路径,用于加载使用注解格式定义的bean
相关属性excludeFilters:排除扫描路径中加载的bean,需要指定类别(type)和具体项(classes) includeFilters:加载指定的bean,需要指定类别(type)和具体项(classes)

5、五种参数的类型传递

①普通参数:url地址传参,地址参数名与形参变量名相同,定义形参即可接收参数。

②pojo类型传参:请求参数名与形参对象属性名相同,定义POJO类型形参即可接收参数。

③嵌套pojo类型传参:请求参数名与形参对象属性名相同,按照对象层次结构关系即可接收嵌套POJO属性参数

注意:请求参数key的名称要和POJO中属性的名称一致,否则无法封装

④数组类型传参:请求参数名与形参对象属性名相同且请求参数多个,定义数组类型即可接收参数

注意:同名请求参数可以直接映射到对应名称的形参数组对象中

⑤集合类型传参:请求参数名与形参集合对象名相同且请求参数为多个,@RequestParam绑定参数关系

注意:同名请求参数可以使用@RequestParam注解映射到对应名称的集合对象中作为数据

名称@RequestParam
类型形参注解
位置SpringMVC控制器方法形参定义前面
作用绑定请求参数与处理器方法形参间的关系
相关参数required:是否为必传参数 defaultValue:参数默认值

6、JSON数据传输参数

SpringMvc使用jackson来处理json数据,使用@EnableWebMvc开启json数据类型自动转换,使用@RequestBody注解将外部传递的json数组数据映射到形参的集合对象中作为数据。

名称@EnableWebMvc
类型配置类注解
位置SpringMVC配置类定义上方
作用开启SpringMVC多项辅助功能
名称@RequestBody
类型形参注解
位置SpringMVC控制器方法形参定义前面
作用将请求中请求体所包含的数据传递给请求参数,此注解一个处理器方法只能使用一次
名称@ResponseBody
类型方法\类注解
位置SpringMVC控制器方法定义上方和控制类上
作用设置当前控制器返回值作为响应体, 写在类上,该类的所有方法都有该注解功能
相关属性pattern:指定日期时间格式字符串

@RequestBody与@RequestParam区别:

@RequestParam用于接收url地址传参,表单传参
@RequestBody用于接收json数据

 三、基于xml配置

1、配置web.xml

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>teacity</display-name>
  <!--  编码集  -->
  <!--  配置spring的编码过滤器  -->
  <filter>
    <filter-name>encoding</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>encoding</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>
  <!--配置Spring的监听器,在服务器启动时加载Spring的配置文件-->
  <listener>
        <!--
            配置Spring的监听器,在服务器启动时加载Spring的配置文件
            Spring配置文件默认位置和名称:/WEB-INF/applicationContext.xml
            可通过上下文参数自定义Spring配置文件的位置和名称
        -->
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!--  spring mvc  -->
  <!--配置springmvc的前端控制器DispatcherServlet,对浏览器发送到请求进行统一处理-->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <!-- 通过初始化参数设置springmvc的配置文件和名称 -->
      <param-name>contextConfigLocation</param-name>
      <!-- 使用classpath:表示从类路径查找配置文件 -->
      <param-value>classpath:springmvc-config.xml</param-value>
    </init-param>
    <!--  将DispatcherServlet的初始化提前到服务器启动时  -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <!--
        设置springMVC的核心控制器所能处理的请求的请求路径
        /所匹配的请求可以是/login或.html或.js或.css方式的请求路径
        但是/不能匹配.jsp请求路径的请求
        即 /:匹配浏览器向服务器发送的所有请求(不包括.jsp)
        /*:匹配浏览器向服务器发送的所有请求(包括.jsp)
    -->
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
</web-app>

2、配置springmvc-config.xml及视图解析器类型

2.1基于InternalResourceView(转发视图)视图解析器

当控制器方法中所设置的视图名称以 "forward:" 为前缀时,创建 InternalResourceView 视图,此时的视 图名称不会被SpringMVC 配置文件中所配置的视图解析器解析,而是会将前缀 "forward:" 去掉,剩余部 分作为最终路径通过转发的方式实现跳转。
<?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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.2.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd 
        http://www.springframework.org/schema/task 
        http://www.springframework.org/schema/task/spring-task-4.2.xsd">
	<!-- 扫描内容 -->
	<context:component-scan base-package="com.islunatic.controller" />

    <!--
        配置默认的servlet处理静态资源
        当前工程的web.xml配置的前端控制器DispatcherServlet的url-pattern是/
        tomcat的web.xml配置的DefaultServlet的url-pattern也是/
        此时,浏览器发送的请求会优先被DispatcherServlet进行处理,但是DispatcherServlet无法处理静态资源
        若配置了<mvc:default-servlet-handler />,此时浏览器发送的所有请求都会被DefaultServlet处理
        若配置了<mvc:default-servlet-handler />和<mvc:annotation-driven />
        浏览器发送的请求会先被DispatcherServlet处理,无法处理在交给DefaultServlet处理
    -->
    <mvc:default-servlet-handler />

	<!-- 开启注解配置 -->
	<mvc:annotation-driven />
    <!--
	    视图控制器:为当前的请求直接设置视图名称实现页面跳转
	    若设置视图控制器,则只有视图控制器所设置的请求会被处理,其他请求全部为404
	    此时必须再次配置一个标签:<mvc:annotation-driven />
    -->
    <!--<mvc:view-controller path="/" view-name="index"></mvc:view-controller>-->
	<!-- 配置静态资源的访问映射,此配置中的文件,将不被前端控制器拦截 -->
	<mvc:resources location="/js/" mapping="/js/**" />
	<mvc:resources location="/css/" mapping="/css/**" />
	<mvc:resources location="/images/" mapping="/images/**" />
	<mvc:resources location="/headimg/" mapping="/headimg/**" />
	<!-- 视图解析器 -->
    <!--	InternalResourceViewResolver转发视图    -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 前缀 -->
		<property name="prefix" value="/WEB-INF/jsp/" />
		<!-- 后缀 -->
		<property name="suffix" value=".jsp" />
	</bean>
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="UTF-8" />
		<property name="maxUploadSize" value="2097152" /><!-- 2M -->
		<property name="maxInMemorySize" value="40960" />
	</bean>
</beans>
@RequestMapping("/view/forward")
    public String testInternalResourceView(){
        return "forward:/index";
    }

2.2基于ThymeleafView视图解析器

当控制器方法中所设置的视图名称没有任何前缀时,此时的视图名称会被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: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.islunatic.controller"></context:component-scan>
    <!--开启mvc的注解驱动-->
    <mvc:annotation-driven />
    <!--
        视图控制器:为当前的请求直接设置视图名称实现页面跳转
        若设置视图控制器,则只有视图控制器所设置的请求会被处理,其他的请求将全部404
        此时必须在配置一个标签:<mvc:annotation-driven />
    -->
    <mvc:view-controller path="/" view-name="index"></mvc:view-controller>
    <!-- 配置Thymeleaf视图解析器 -->
    <bean id="viewResolver" class="org.thymeleaf.spring6.view.ThymeleafViewResolver">
        <property name="order" value="1"/>
        <property name="characterEncoding" value="UTF-8"/>
        <property name="templateEngine">
            <bean class="org.thymeleaf.spring6.SpringTemplateEngine">
                <property name="templateResolver">
                    <bean class="org.thymeleaf.spring6.templateresolver.SpringResourceTemplateResolver">
                        <!-- 视图前缀 -->
                        <property name="prefix" value="/WEB-INF/templates/"/>
                        <!-- 视图后缀 -->
                        <property name="suffix" value=".html"/>
                        <property name="templateMode" value="HTML5"/>
                        <property name="characterEncoding" value="UTF-8" />
                    </bean>
                </property>
            </bean>
        </property>
    </bean>
</beans>
@RequestMapping("/view/thymeleaf")
    public String testThymeleafView(){
        return "success";
}

2.3基于RedirectView(重定向视图)视图解析器

当控制器方法中所设置的视图名称以 "redirect:" 为前缀时,创建 RedirectView 视图,此时的视图名称不 会被SpringMVC 配置文件中所配置的视图解析器解析,而是会将前缀 "redirect:" 去掉,剩余分作为最终路径通过重定向的方式实现跳转。
<?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="com.islunatic.controller"></context:component-scan>
    <!--开启mvc的注解驱动-->
    <mvc:annotation-driven />
    <!--
        视图控制器:为当前的请求直接设置视图名称实现页面跳转
        若设置视图控制器,则只有视图控制器所设置的请求会被处理,其他的请求将全部404
        此时必须在配置一个标签:<mvc:annotation-driven />
    -->
    <mvc:view-controller path="/" view-name="index"></mvc:view-controller>
    <!-- 配置Thymeleaf视图解析器 -->
    <!-- Redirect view -->
    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.RedirectView">
        <property name="url" value="redirect.html" />
    </bean>
</beans>
@RequestMapping("/view/redirect")
    public String testRedirectView(){
        return "redirect:/index";
}

3、视图控制器

当控制器方法中,仅仅用来实现页面跳转,即只需要设置视图名称时,可以将处理器方法使用 view-controller标签进行表示。
    <!--
        视图控制器:为当前的请求直接设置视图名称实现页面跳转
        若设置视图控制器,则只有视图控制器所设置的请求会被处理,其他的请求将全部404
        此时必须在配置一个标签:<mvc:annotation-driven />
    -->
    <!--
        path:设置处理的请求地址
        view-name:设置请求地址所对应的视图名称
    -->
    <mvc:view-controller path="/" view-name="index"></mvc:view-controller>

注意:当SpringMVC中设置任何一个view-controller时,其他控制器中的请求映射将全部失效,此时需 要在SpringMVC的核心配置文件中设置开启mvc注解驱动的标签: <mvc:annotation-driven />

     <!--开启mvc的注解驱动-->
    <mvc:annotation-driven />
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IsLuNaTiC

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值