我正在使用spring security和java config
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/*").hasRole("ADMIN")
.and()
.addFilterAfter(new CsrfTokenResponseHeaderBindingFilter(), CsrfFilter.class)
.exceptionHandling()
.authenticationEntryPoint(restAuthenticationEntryPoint)
.and()
.formLogin()
.successHandler(authenticationSuccessHandler)
.failureHandler(new SimpleUrlAuthenticationFailureHandler());
Run Code Online (Sandbox Code Playgroud)
我正在使用PostMan来测试我的REST服务.我成功获得'csrf token',我可以使用X-CSRF-TOKEN请求标头登录.但登录后我点击发布请求(我在请求标题中包含相同的令牌,我用于登录发布请求)我收到以下错误消息:
HTTP状态403 - 无法验证提供的CSRF令牌,因为找不到您的会话.
任何人都可以指导我做错了什么.
我的 Spring Boot 应用程序提供以下 REST 控制器:
@RestController
@RequestMapping("/api/verify")
public class VerificationController {
final VerificationService verificationService;
Logger logger = LoggerFactory.getLogger(VerificationController.class);
public VerificationController(VerificationService verificationService) {
this.verificationService = verificationService;
}
@GetMapping
public void verify(
@RequestParam(value = "s1") String s1,
@RequestParam(value = "s2") String s2) {
try {
verificationService.validateFormat(s1, s2);
} catch (InvalidFormatException e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage());
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果validateFormat()抛出,InvalidFormatException客户端会得到一个正确的 HTTP 400。然而,默认的 JSON 响应正文如下所示:
{
"timestamp": "2020-06-18T21:31:34.911+00:00",
"status": 400,
"error": "Bad Request",
"message": "",
"path": "/api/verify"
} …Run Code Online (Sandbox Code Playgroud) 我试图在基于Spring的REST API中读取HTTP头.我跟着这个.但是我收到了这个错误:
没有找到类java.lang.String,
ContentType:application/octet-stream的消息正文阅读器
我是Java和Spring的新手,所以无法解决这个问题.
这就是我的通话方式:
@WebService(serviceName = "common")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public interface CommonApiService {
@GET
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
@Path("/data")
public ResponseEntity<Data> getData(@RequestHeader(value="User-Agent") String userAgent, @DefaultValue ("") @QueryParam("ID") String id);
}
Run Code Online (Sandbox Code Playgroud)
我试过了@Context:HTTPHeader是null这种情况.
如何从HTTP标头获取值?
X-Auth-Token之间有什么区别:dadas123sad12 vs Authorization:Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ == headers.哪个是首选
我从学习Spring开始,创建基本项目,创建数据库,插入值,然后在Web浏览器中打印.我的问题是,当我将RestController放在像主类一样的包中时 - 它可以,但我想将它分发给其他包,当我创建新包时,移动RestController它不起作用.让我们解释一下:
我的项目看起来像:
|-Springtestv_01
|-src/main/java
|--com.person <-- it's a main package
|-Main.java
|-Person.java
|-PersonLineRunner.java
|-PersonRepository.java
|-PersonController.java
|-com.controller <-- second package, I want put here PersonController.java
|-src/main/resources
|-data.sql
pom.xml
Run Code Online (Sandbox Code Playgroud)
我的控制器看:
@RestController
public class PersonController {
@Autowired PersonRepository personRepository;
@RequestMapping("/persons")
Collection<Person> persons(){
return this.personRepository.findAll();
}
}
Run Code Online (Sandbox Code Playgroud)
当所有东西都在com.person包装中时,我写在网页浏览器http:// localhost:8080 /个人并且它正常工作......但我想转移PersonController.java到com.controller包装,当我移动它时,我的网页浏览器打电话给我
出现意外错误(type = Not Found,status = 404).没有可用的消息
我不知道应该怎么做才能修复它.也许我应该改变一些事情pom.xml?
我的pom.xml看起来像
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.person</groupId>
<artifactId>person</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringTest_v0_1</name> …Run Code Online (Sandbox Code Playgroud) 这将返回200 OK,Content-Length:0
@RestController
public class RepoController {
@RequestMapping(value = "/document/{id}", method = RequestMethod.GET)
public Object getDocument(@PathVariable long id) {
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
简单地说,我希望它返回204 No Content on null.
有没有办法强制spring-mvc/rest在null而不是200时返回204?我不想更改每个rest方法以返回ResponseEntity或类似的东西,只将null映射到204
最终编辑
因此,在研究了这个之后,因为我所看到的答案并没有完全成熟,我发现Spring做了一些奇怪的东西与扩展匹配.如果我提交这样的请求byNameOrAtlName/myStringHere.1或这个byNameOrAtlName/myStringHere.12一切都很好,但byNameOrAtlName/myStringHere.123会导致它打破byNameOrAtlName/myStringHere.com,但是byNameOrAtlName/myStringHere.co没关系,但byNameOrAtlName/myStringHere.c不是.
总而言之,我不知道逻辑spring用于确定扩展内容,但对于某些扩展,它{varName:.+}可以作为一种解决方法,但看起来你需要完全禁用点文件后缀来真正解决它.
使用Spring 4.1.6
Spring正在抛出以下异常 org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
我有以下代码,除非字符串(名称)中有句号,否则一切正常.
@RestController
@RequestMapping(value = "/foo/")
public class Testing{
@RequestMapping(value = "byNameOrAltName/{name:.+}", method = RequestMethod.GET)
@Transactional(readOnly = true)
public Collection<MyDTO> getByNameOrAltNAme(@PathVariable("name") String name) {
return myRepo.getMyDTOsByNameOrAtlName(name);
}
}
Run Code Online (Sandbox Code Playgroud)
这样可行.http://localhost:8080/data/foo/byNameOrAtlName/myStringHere,但如果我这样做就失败了http://localhost:8080/data/foo/byNameOrAtlName/myStringHere.fluffy
我阅读了关于这个例外的其他答案,但它们似乎都不适用于我的案例.起初我认为这是春天不喜欢在路径中的时间段的问题,并且我在使用正则表达式之前修复了它.+但是我在使用和不使用正则表达式时尝试了它并且我得到了相同的错误.
关于为什么Spring会抛出这个的任何想法?
编辑
这是我的调试日志:
21:32:09,118 DEBUG work.orm.jpa.support.OpenEntityManagerInViewFilter: 161 - Opening JPA EntityManager in OpenEntityManagerInViewFilter
21:32:09,118 DEBUG rk.security.web.util.matcher.AntPathRequestMatcher: 151 - Checking match …Run Code Online (Sandbox Code Playgroud) 我创建了一个简单的REST服务(POST).但是,当我从邮递员@RequestBody调用此服务时,没有收到任何值.
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
@RestController
public class Add_Policy {
@ResponseBody
@RequestMapping(value = "/Add_Policy", headers = {
"content-type=application/json" }, consumes = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
public Policy GetIPCountry( @RequestBody Policy policy) {
System.out.println("Check value: " + policy.getPolicyNumber());
return policy;
}
}
Run Code Online (Sandbox Code Playgroud)
我的java Bean对象如下:
public class Policy {
private String PolicyNumber;
private String Type;
private String Tenture;
private String SDate;
private String HName;
private String Age;
public String getPolicyNumber() {
return …Run Code Online (Sandbox Code Playgroud) 以下两者之间的区别是什么?
@GetMapping(path = "/usr/{userId}")
public String findDBUserGetMapping(@PathVariable("userId") String userId) {
return "Test User";
}
@RequestMapping(value = "/usr/{userId}", method = RequestMethod.GET)
public String findDBUserReqMapping(@PathVariable("userId") String userId) {
return "Test User";
}
Run Code Online (Sandbox Code Playgroud) 我在我的春季启动项目中使用了swagger2.它工作得很好,但我需要basic-error-controller从api中排除它.目前我使用正则表达式使用以下代码.它正在运作,但有任何完美的方法来做到这一点.
代码:
@Bean
public Docket demoApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.regex('(?!/error.*).*'))
.build()
}
Run Code Online (Sandbox Code Playgroud) java ×7
spring ×7
spring-boot ×4
rest ×2
csrf ×1
http ×1
http-headers ×1
maven ×1
package ×1
spring-mvc ×1
spring-rest ×1
swagger-2.0 ×1