SpringBoot相關配置


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>
  • 運行效果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM