8.1 配置

  • Spring MVC的配置是通过继承WebMvcConfigurerAdapter类并重载其方法实现的;
  • 前几个教程已做了得配置包括
    • 01点睛Spring MVC 4.1-搭建环境 配置viewResolver
    • 03点睛Spring MVC 4.1-REST 静态资源映射
    • 04点睛Spring MVC 4.1-拦截器 配置拦截器
    • 06点睛Spring MVC 4.1-文件上传 配置multipartResolver
    • 07点睛Spring MVC4.1-ContentNegotiatingViewResolver 配置ContentNegotiatingViewResolver

8.2 演示

8.2.1 配置路径匹配参数

  • 在Spring MVC中路径参数如果带.的话,.后面的值将被忽略,本例演示配置configurePathMatch不忽略点后面的参数;

  • 演示控制器

@RequestMapping("/configPath/{test}")
public @ResponseBody String configPath(@PathVariable String test){
return "request value:"+test;
}
  • 运行:访问http://localhost:8080/testSpringMVC/configPath/xx.yy

  • 在继承WebMvcConfigurerAdapterDemoMVCConfig类中重载configurePathMatch
    @Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.setUseSuffixPatternMatch(false);
}
  • 再次运行:访问访问http://localhost:8080/testSpringMVC/configPath/xx.yy

8.2.2 快捷定义ViewController

  • 我们经常涉及到页面转向,但没任何处理业务的时候,快捷的页面转向定义会节省好多代码;
  • 在views目录下建一个任意的test.jsp
  • 常规的方案是这样写的
@RequestMapping("/mytest")
public String test(){
return "test";
}
  • 在继承WebMvcConfigurerAdapterDemoMVCConfig类中重载addViewControllers
  @Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/mytest").setViewName("/test");
//添加更多
}
  • 以上效果等同,均会指向views下的test.jsp

8.2.3 配置HttpMessageConverter

  • HttpMessageConverter是对http的request和response进行自动转换
  • 配置HttpMessageConverter可重载下面两个方法任意一个

    • configureMessageConverters:重载会覆盖掉spring mvc默认注册的多个HttpMessageConverter
    • extendMessageConverters:仅添加一个自定义的HttpMessageConverter,不覆盖默认注册的HttpMessageConverter
  • 通过对上面的讲述,我们一般是重载extendMessageConverters方法;

  • 下面我们演示使用js向spring mvc发送自定义格式的字符串(属性用-隔开),通过自定义的HttpMessageConverter自动转换成对象,然后通过HttpMessageConverter输出指定格式到浏览器

  • 测试javabean

    • Person
package com.wisely.domain;

public class Person {

    private String firstName;
private String lastName;
public Person(String firstName, String lastName) {
super();
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
} }
  • 自定义HttpMessageConverterWiselyMessageConverter
package com.wisely.converters;

import java.io.IOException;
import java.nio.charset.Charset; import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.StreamUtils; import com.wisely.domain.Person; public class WiselyMessageConverter extends AbstractHttpMessageConverter<Person> { //自定义媒体类型
public WiselyMessageConverter(){
super(new MediaType("application", "x-wisely", Charset.forName("UTF-8")));
}
//从request里获得构造Person实例的数据
@Override
protected Person readInternal(Class<? extends Person> clazz,
HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
String temp = StreamUtils.copyToString(inputMessage.getBody(), Charset.forName("UTF-8"));
String[] tempArr = temp.split("-");
return new Person(tempArr[0],tempArr[1]);
} //只支持Person类
@Override
protected boolean supports(Class<?> clazz) {
return Person.class.isAssignableFrom(clazz);
} //将person实例转换成你想要的字符串格式
@Override
protected void writeInternal(Person person, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
String out = "hello:" +person.getFirstName() + "-" + person.getLastName();
outputMessage.getBody().write(out.getBytes());
} }
  • 配置WiselyMessageConverter
  @Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
WiselyMessageConverter converter = new WiselyMessageConverter();
converters.add(converter);
}

注释掉上例的configureContentNegotiation,这里会自动将媒体类型变为text/html

// 配置ContentNegotiationManager,在无后缀名情况下默认为jsp view resolver
// @Override
// public void configureContentNegotiation(
// ContentNegotiationConfigurer configurer) {
// //忽略请求的header信息,并将contentType置为text/html
// configurer.ignoreAcceptHeader(true).defaultContentType(
// MediaType.TEXT_HTML);
// }
  • 测试控制器
@RequestMapping(value = "/convert", produces = { "application/x-wisely" })
public @ResponseBody Person convert(@RequestBody Person person) {
return person;
}
  • 测试页面:test.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<div id="resp"></div><input type="button" onclick="req();" value="请求"/>
<script src="js/jquery.js" type="text/javascript"></script>
<script>
function req(){
$.ajax({
url: "convert",
data: "wang-yunfei",//注意此处的格式
type:"POST",
contentType:"application/x-wisely",
success: function(data){
$("#resp").html(data);
}
});
} </script>
</body>
</html>
  • 运行效果

SpringBoot相关配置的更多相关文章

  1. 【持续更新】springboot相关配置

    @Configuration public class MyWebMvcConfig implements WebMvcConfigurer { //注册了新的访问路径 @Override publi ...

  2. springboot配置server相关配置&整合模板引擎Freemarker、thymeleaf&thymeleaf基本用法&thymeleaf 获取项目路径 contextPath 与取session中信息

    1.Springboot配置server相关配置(包括默认tomcat的相关配置) 下面的配置也都是模板,需要的时候在application.properties配置即可 ############## ...

  3. SpringBoot数据源相关配置

    数据源配置 单数据源 配置步骤 引入依赖:H2数据库驱动.JDBC依赖.acturator(运维).web模块(用于测试).lambok(使用@Slf4j打印日志). 直接配置所需的Bean,注入容器 ...

  4. SpringBoot cache-control 配置静态资源缓存 (以及其中的思考经历)

    昨天在部署项目时遇到一个问题,因为服务要部署到外网使用,中间经过了较多的网络传输限制,而且要加载arcgis等较大的文件,所以在部署后,发现页面loading需要很长时间,而且刷新也要重新从服务器下载 ...

  5. 补习系列(10)-springboot 之配置读取

    目录 简介 一.配置样例 二.如何注入配置 1. 缺省配置文件 2. 使用注解 3. 启动参数 还有.. 三.如何读取配置 @Value 注解 Environment 接口 @Configuratio ...

  6. SpringBoot自动配置源码调试

    之前对SpringBoot的自动配置原理进行了较为详细的介绍(https://www.cnblogs.com/stm32stm32/p/10560933.html),接下来就对自动配置进行源码调试,探 ...

  7. SpringBoot自定义属性配置以及@ConfigurationProperties注解与@Value注解区别

    我们可以在application.properties中配置自定义的属性值,为了获取这些值,我们可以使用spring提供的@value注解,还可以使用springboot提供的@Configurati ...

  8. springboot日志配置

    默认情况下,spring boot使用的是LogBack日志系统.在spring-boot-starter-web和spring-boot-starter中都已经默认依赖了logging的工具包. 如 ...

  9. SpringBoot 核心配置

    1. 入口类和 @SpringBootApplication Spring Boot的项目一般都会有*Application的入口类,入口类中会有main方法,这是一个标准的Java应用程序的入口方法 ...

随机推荐

  1. 3D空间中射线与轴向包围盒AABB的交叉检测算法【转】

    引言 在上一节中,我讲述了如何实现射线与三角形的交叉检测算法.但是,我们应该知道,在游戏开发中,一个模型有很多的三角形构成,如果要对所有的物体,所有的三角形进行这种检测,就算现在的计算机运算能力,也是 ...

  2. python 实现九型人格测试小程序

    用python实现九型人格测试,并把测试结果绘制成饼图,实现代码如下: # @Description: 九型人格 import xlrd, matplotlib.pyplot as plt data ...

  3. NLayerAppV3-Distributed Service Layer(分布式服务层)

    回顾:NLayerAppV3是一个使用.net 2.1实现的经典DDD的分层架构的项目. NLayerAppV3是在NLayerAppV2的基础上,使用.net core2.1进行重新构建的:它包含了 ...

  4. 几条shell命令

    windows: route add 158.0.0.0 mask 255.0.0.0 158.137.38.1 metric 3 linux: netstat -apn  查看所有端口使用,可查看端 ...

  5. Day44 数据库的操作

    视图操作: 1.左连接查询 select * from person left join dept on person.dept_id = dept.did 2. 右连接 3. 内连接  inner ...

  6. Linux下安装python虚拟环境(virtualenv,vritulaenvwrapper)

    一.virtualenv virtualenv是如何创建"独立"的Python运行环境的呢? 原理很简单,就是把系统Python复制一份到virtualenv的环境,用命令sour ...

  7. 深度优先搜索 - 简单demo

    输入一个数n,输出 1 ~ n 的全排列,例如输入 3,全排列则为:123,132,213,231,312,321 一共六种. 这里采用深度优先搜索来解决这个问题: #include<stdio ...

  8. 利用DNSlog回显Weblogic(CVE-2017-10271) 漏洞执行命令结果

    作者:Armyzer0 Weblogic(CVE-2017-10271) 漏洞出来以后又是一波血雨腥风,正好我昨天测试的时候发现了一个存在这个漏洞的weblogic,但是他不回显咋办呢!让他返回执行结 ...

  9. 基于Zookeeper实现的分布式互斥锁 - InterProcessMutex

    Curator是ZooKeeper的一个客户端框架,其中封装了分布式互斥锁的实现,最为常用的是InterProcessMutex,本文将对其进行代码剖析 简介 InterProcessMutex基于Z ...

  10. Java MVC和三层架构

    一.设计模式 Model 1 和Model 2 Model 1 前面学习了Servlet和Jsp,对这两个有个大概的认识,Servlet就是为了解决静态页面的问题,能够实现动态的页面,使维护,开发更加 ...