Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/398.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 弹簧复位_Java_Spring - Fatal编程技术网

Java 弹簧复位

Java 弹簧复位,java,spring,Java,Spring,我有一个Spring RestController,我从locahost:8080开始。当我向它发送请求(localhost:8080/people)时,我会得到一个XML格式的响应。我怎样才能把它变成JSON?当我使用Opera web浏览器发送请求时,我得到的是XML格式,但当我使用终端(我使用Mac)时,请求的答案是Json。如何使浏览器中的答案为JSON格式 控制器 package People; import java.util.List; import java.util.stre

我有一个Spring RestController,我从locahost:8080开始。当我向它发送请求(localhost:8080/people)时,我会得到一个XML格式的响应。我怎样才能把它变成JSON?当我使用Opera web浏览器发送请求时,我得到的是XML格式,但当我使用终端(我使用Mac)时,请求的答案是Json。如何使浏览器中的答案为JSON格式

控制器

package People;

import java.util.List;
import java.util.stream.Collectors;


import org.springframework.hateoas.Resource;
import org.springframework.hateoas.Resources;
import org.springframework.web.bind.annotation.*;

import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;

@RestController
@RequestMapping("people")
public class PersonController {

    private final PersonRepository repository;

    PersonController(PersonRepository repository){
        this.repository = repository;
    }

    @GetMapping
    public Resources<Resource<Person>> all(){
        List<Resource<Person>> persons = repository.findAll().stream()
                .map(employee -> new Resource<>(employee,
                        linkTo(methodOn(PersonController.class).one(employee.getId())).withSelfRel(),
                        linkTo(methodOn(PersonController.class).all()).withRel("Persons")))
                .collect(Collectors.toList());

        return new Resources<>(persons,
                linkTo(methodOn(PersonController.class).all()).withSelfRel());
    }

    @PostMapping("")
    public Person newEmployee(@RequestBody Person newEmployee) {
        return repository.save(newEmployee);
    }

    @GetMapping("{id}")
    public Resource<Person> one(@PathVariable Long id) {
        Person Person = repository.findById(id)
                .orElseThrow(() -> new PersonNotFoundException(id));

        return new Resource<>(Person,
                linkTo(methodOn(PersonController.class).one(id)).withSelfRel(),
                linkTo(methodOn(PersonController.class).all()).withRel("Persons"));
    }

    @PutMapping("{id}")
    public Person replacePerson(@RequestBody Person newPerson,@PathVariable Long id){
        return repository.findById(id)
                .map(Person -> {
                    Person.setName(newPerson.getName());
                    Person.setLastName(newPerson.getLastName());
                    return repository.save(Person);
                }).orElseGet(() -> {
                    newPerson.setId(id);
                    return repository.save(newPerson);
                });
    }

    @DeleteMapping("{id}")
    void deletePerson(@PathVariable Long id) {
        repository.deleteById(id);
    }

}
包装人;
导入java.util.List;
导入java.util.stream.collector;
导入org.springframework.hateoas.Resource;
导入org.springframework.hateoas.Resources;
导入org.springframework.web.bind.annotation.*;
导入静态org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
导入静态org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
@RestController
@请求映射(“人”)
公共类个人控制器{
私有最终PersonRepository存储库;
PersonController(PersonRepository存储库){
this.repository=存储库;
}
@GetMapping
公共资源(全部){
List persons=repository.findAll().stream()
.map(员工->新资源(员工、,
链接到(methodOn(PersonController.class).one(employee.getId()).withSelfRel(),
链接到(methodOn(PersonController.class).all().withRel(“Persons”))
.collect(Collectors.toList());
返回新资源(人员,
链接到(methodOn(PersonController.class).all()).withSelfRel());
}
@邮戳(“”)
公共人物newEmployee(@RequestBody Person newEmployee){
返回repository.save(newEmployee);
}
@GetMapping(“{id}”)
公共资源一(@PathVariable Long id){
Person=repository.findById(id)
.orelsetrow(()->newpersonnotfoundexception(id));
返回新资源(人员,
链接到(methodOn(PersonController.class).one(id)).withSelfRel(),
链接到(methodOn(PersonController.class).all()).withRel(“Persons”);
}
@PutMapping(“{id}”)
public Person replacePerson(@RequestBody Person newPerson,@PathVariable Long id){
返回repository.findById(id)
.map(个人->{
Person.setName(newPerson.getName());
Person.setLastName(newPerson.getLastName());
返回存储库。保存(个人);
}).orElseGet(()->{
newPerson.setId(id);
返回repository.save(newPerson);
});
}
@DeleteMapping(“{id}”)
void deletePerson(@PathVariable Long id){
repository.deleteById(id);
}
}
这就是反应的样子

<html>
<body>
<h1>Whitelabel Error Page</h1>
<p>
This application has no explicit mapping for /error, so you are seeing this as a fallback.
</p>
<div id="created">Mon Oct 29 22:41:51 MSK 2018</div>
<div>
There was an unexpected error (type=Internal Server Error, status=500).
</div>
<div>
Could not marshal [Resources { content: [Resource { content: Person(id=1, Name=Paul, LastName=Walker), links: [<http://localhost:8080/people/1>;rel="self", <http://localhost:8080/people>;rel="Persons"] }, Resource { content: Person(id=2, Name=Stan, LastName=Smith), links: [<http://localhost:8080/people/2>;rel="self", <http://localhost:8080/people>;rel="Persons"] }], links: [<http://localhost:8080/people>;rel="self"] }]: null; nested exception is javax.xml.bind.MarshalException - with linked exception: [com.sun.istack.internal.SAXException2: unable to marshal type "org.springframework.hateoas.Resource" as an element because it is not known to this context.]
</div>
</body>
</html>

白标错误页

此应用程序没有/error的显式映射,因此您将其视为回退。

2018年10月29日星期一22:41:51 MSK 出现意外错误(类型=内部服务器错误,状态=500)。 无法封送[资源{content:[资源{content:Person(id=1,Name=Paul,LastName=Walker),链接:[;rel=“self”;;rel=“Persons”]},资源{content:Person(id=2,Name=Stan,LastName=Smith),链接:[;rel=“self”;;rel=“Persons”]},链接:[;rel=“self”]}]:null;嵌套异常是javax.xml.bind.MarshalException-带有链接异常:[com.sun.istack.internal.saxeption2:无法将类型“org.springframework.hateoas.Resource”封送为元素,因为此上下文不知道它。]
控制台日志

2018-10-29 23:57:26.747  INFO 21281 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-10-29 23:57:26.747  INFO 21281 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2018-10-29 23:57:26.767  INFO 21281 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 20 ms
2018-10-29 23:57:26.985  WARN 21281 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not marshal [Resource { content: Person(id=1, Name=Paul, LastName=Walker), links: [<http://localhost:8080/people/1>;rel="self", <http://localhost:8080/people>;rel="Persons"] }]: null; nested exception is javax.xml.bind.MarshalException
 - with linked exception:
[com.sun.istack.internal.SAXException2: class People.Person nor any of its super class is known to this context.
javax.xml.bind.JAXBException: class People.Person nor any of its super class is known to this context.]]
2018-10-29 23:57:26.747信息21281---[nio-8080-exec-1]o.a.c.c.c.[Tomcat].[localhost].[/]:初始化Spring FrameworkServlet'dispatcherServlet'
2018-10-29 23:57:26.747信息21281---[nio-8080-exec-1]o.s.web.servlet.DispatcherServlet:FrameworkServlet“DispatcherServlet”:初始化已开始
2018-10-29 23:57:26.767信息21281---[nio-8080-exec-1]o.s.web.servlet.DispatcherServlet:FrameworkServlet“DispatcherServlet”:初始化在20毫秒内完成
2018-10-29 23:57:26.985 WARN 21281---[nio-8080-exec-1].w.s.m.s.DefaultHandlerExceptionResolver:Resolved[org.springframework.http.converter.httpMessageneTWritableException:无法封送[Resource{content:Person(id=1,Name=Paul,LastName=Walker),链接:[;rel=“self”;;rel=“Persons”]:null;嵌套异常为javax.xml.bind.MarshalException
-除此之外:
[com.sun.istack.internal.SAXException2:class People.Person及其任何超类在此上下文中都是已知的。
javax.xml.bind.JAXBException:class People.Person或其任何超类在此上下文中都是已知的。]]

请尝试将生产者添加到get方法中,如下所示

 @GetMapping(path = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)

浏览器和命令行之间的请求头有什么不同?(如果你不确定,你可以用你最喜欢的网络分析工具找出答案。)也许我问得不对。。。为什么它返回xml格式?我看了YouTube上的教程,其中作者得到了JSOn值,但我得到了一个XML…谢谢!你帮了我很大的忙!