SpringBoot常见错误集



1.解springboot项目请求出现非法字符问题 java.lang.IllegalArgumentException:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* @author Blue
* @date 2020/3/12
**/

import org.apache.catalina.connector.Connector;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
* @Author: Blue
* Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986
**/
@Configuration
public class TomcatConfig {

@Bean
public TomcatServletWebServerFactory webServerFactory() {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
factory.addConnectorCustomizers((Connector connector) -> {
connector.setProperty("relaxedPathChars", "\"<>[\\]^`{|}");
connector.setProperty("relaxedQueryChars", "\"<>[\\]^`{|}");
});
return factory;
}
}

2.org.springframework.web.HttpMediaTypeNotSupportedException: Content type ‘application/json;charset=UTF-8’ not supported或其他Content type不支持处理

注意:

  • 使用post协议提交时,请检查Content type类型
  • 如果想用@RequestBody注解做提交json字符串自动绑定到pojo入参时,contentType类型需要是”application/json;charset=UTF-8”,否则也会抛”not supported”异常
1
2
3
4
5
6
7
8
9
10
11
// 示例
$.ajax({
type: "POST",
contentType: "application/json;charset=UTF-8",
url: "/reg",
data: JSON.stringify(data.field),
dataType: 'json',
success: function(result) {

}
});
1
2
3
4
5
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ResponseBody
public Result<?> reg(@RequestBody UserInfo user) {
//...
}

心得:

  • @ResponseBody:将java对象转为json格式的数据,可作用在方法上
  • @RequestBody:将json数据转换成对象,可作用在方法入参上
打赏
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  1. © 2020 coderblue    湘ICP备20003709号

请我喝杯咖啡吧~

支付宝
微信