Spring return json - java

I have a Spring RestController which I am starting in locahost:8080. When I send a request to it (localhost:8080/people) I get a response in XML format. How can I make it JSON? When I send the request using Opera web browser I get XML format, but when I use the terminal( I use Mac) the answer to the request is Json. How can I make the answer in the browser be a JSON format.
Controller
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);
}
}
This is how the response looks like
<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>
Console log
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.]]

Please try to add producer to your get method as below
#GetMapping(path = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)

Related

Getting exception that says no mapping, when I have the mapping

My application is running with an exception. When I try to post to localhost:8080/addUser I get the error that there is no mapping. However I have it in my UserController.java:
2021-10-03 20:28:04.852 INFO 9896 --- [ngodb.net:27017] org.mongodb.driver.cluster : Exception in monitor thread while connecting to server edumeet-shard-00-01.egesp.mongodb.net:27017
com.mongodb.MongoSocketReadException: Prematurely reached end of stream
at com.mongodb.internal.connection.SocketStream.read(SocketStream.java:112) ~[mongodb-driver-core-4.2.3.jar:na]
at com.mongodb.internal.connection.SocketStream.read(SocketStream.java:131) ~[mongodb-driver-core-4.2.3.jar:na]
at com.mongodb.internal.connection.InternalStreamConnection.receiveResponseBuffers(InternalStreamConnection.java:647) ~[mongodb-driver-core-4.2.3.jar:na]
at com.mongodb.internal.connection.InternalStreamConnection.receiveMessageWithAdditionalTimeout(InternalStreamConnection.java:512) ~[mongodb-driver-core-4.2.3.jar:na]
at com.mongodb.internal.connection.InternalStreamConnection.receiveCommandMessageResponse(InternalStreamConnection.java:355) ~[mongodb-driver-core-4.2.3.jar:na]
at com.mongodb.internal.connection.InternalStreamConnection.sendAndReceive(InternalStreamConnection.java:279) ~[mongodb-driver-core-4.2.3.jar:na]
at com.mongodb.internal.connection.CommandHelper.sendAndReceive(CommandHelper.java:83) ~[mongodb-driver-core-4.2.3.jar:na]
at com.mongodb.internal.connection.CommandHelper.executeCommand(CommandHelper.java:33) ~[mongodb-driver-core-4.2.3.jar:na]
at com.mongodb.internal.connection.InternalStreamConnectionInitializer.initializeConnectionDescription(InternalStreamConnectionInitializer.java:107) ~[mongodb-driver-core-4.2.3.jar:na]
at com.mongodb.internal.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:62) ~[mongodb-driver-core-4.2.3.jar:na]
at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:144) ~[mongodb-driver-core-4.2.3.jar:na]
at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.lookupServerDescription(DefaultServerMonitor.java:188) ~[mongodb-driver-core-4.2.3.jar:na]
at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:144) ~[mongodb-driver-core-4.2.3.jar:na]
at java.base/java.lang.Thread.run(Thread.java:835) ~[na:na]
2021-10-03 20:28:05.681 INFO 9896 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2021-10-03 20:28:05.692 INFO 9896 --- [ restartedMain] com.example.login.LoginApplication : Started LoginApplication in 3.95 seconds (JVM running for 4.612)
2021-10-03 20:28:17.960 INFO 9896 --- [nio-8080-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-10-03 20:28:17.960 INFO 9896 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2021-10-03 20:28:17.996 INFO 9896 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Completed initialization in 36 ms
2021-10-03 20:28:18.025 WARN 9896 --- [nio-8080-exec-2] o.s.web.servlet.PageNotFound : No mapping for POST /addUser
2021-10-03 20:28:18.032 WARN 9896 --- [nio-8080-exec-2] o.s.web.servlet.PageNotFound : No mapping for POST /error
UserController.java
package com.example.login.User;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
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.RestController;
#Controller
#RestController
public class UserController {
private final UserRepository userRepository;
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
#RequestMapping(path = "/addUser", method = RequestMethod.POST)
public String addUser(#RequestBody User user) {
userRepository.save(user);
return "added user with id: " + user.getId();
}
#RequestMapping(path = "/getAllUsers", method = RequestMethod.GET)
public List<User> getAllUsers() {
return userRepository.findAll();
}
#RequestMapping(path = "/getAllUsers/{id}", method = RequestMethod.GET)
public Optional<User> getUser(#PathVariable String id) {
return userRepository.findById(id);
}
#RequestMapping(path = "/removeUser", method = RequestMethod.DELETE)
public String deleteUser(#PathVariable String id) {
userRepository.deleteById(id);
return "removed user with id" + id;
}
}
LoginApplication.java
package com.example.login;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
#SpringBootApplication
#EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class,WebMvcAutoConfiguration.class})
public class LoginApplication {
public static void main(String[] args) {
SpringApplication.run(LoginApplication.class, args);
}
}
you should change path to value as shown below:
#RequestMapping(path = "/addUser", method = RequestMethod.POST)
public String addUser(#RequestBody User user) {
userRepository.save(user);
return "added user with id: " + user.getId();
}
change to
#RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser(#RequestBody User user) {
userRepository.save(user);
return "added user with id: " + user.getId();
}

Spring Boot URL path variable encoding

I have a Spring boot (v2.3.5.RELEASE) REST API and cannot seem to fix an encoding problem with path variables. I have tried every solution that found online but nothing helped.
Here is the Main class:
#SpringBootApplication
public class RestApplication {
public static void main(String[] args) {
SpringApplication.run(RestApplication.class, args);
}
}
The RestController (the method is never executed when sending the request to that URL):
#RestController
#RequestMapping("/mvn/packages")
public class ModuleApi {
#Autowired
ModuleApiService service;
#GetMapping(value = "/{pkg}/{pkg_ver}/modules/{namespace}/metadata", produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<String> getModuleMetadata(#PathVariable("pkg") String package_name,
#PathVariable("pkg_ver") String package_version,
#PathVariable("namespace") String module_namespace) {
return service.getModuleMetadata(package_name, package_version, module_namespace);
}
}
The Configuration class:
#Configuration
public class CorsConfiguration
{
#Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setForceEncoding(true);
characterEncodingFilter.setEncoding("UTF-8");
registrationBean.setFilter(characterEncodingFilter);
return registrationBean;
}
}
The application.properties:
logging.level.org.springframework.web=DEBUG
server.port=8080
server.tomcat.uri-encoding=UTF-8
server.servlet.encoding.charset=UTF-8
server.servlet.encoding.enabled=true
server.servlet.encoding.force=true
I even added encoding to the spring-boot-maven-plugin in the pom.xml:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.3.6.RELEASE</version>
<configuration>
<mainClass>RestApplication</mainClass>
<jvmArguments>-Dfile.encoding=UTF8</jvmArguments>
</configuration>
</plugin>
But the result is still the same.
When sending a request to http://localhost:8080/mvn/packages/junit:junit/4.12/%2Fjunit.framework%2FAssert
i.e. mvn/packages/{pkg}/{pkg_ver}/modules/{namespace}/metadata and namespace is encoded, it returns HTTP 400 - BAD REQUEST.
However, when I try http://localhost:8080/mvn/packages/junit:junit/4.12/foo (does not need encoding/decoding), it works.
I also tried using ALLOW_ENCODED_SLASH property. Main class:
#SpringBootApplication
public class RestApplication {
public static void main(String[] args) {
System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true");
SpringApplication.run(RestApplication.class, args);
}
}
But in this case it cannot resolve the request to that mapping and returns 404 - NOT FOUND:
2020-12-10 17:03:27.044 DEBUG 105120 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : GET "/mvn/packages/junit:junit/4.12/%2Fjunit.framework%2FAssert", parameters={}
2020-12-10 17:03:27.053 DEBUG 105120 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
2020-12-10 17:03:27.056 DEBUG 105120 --- [nio-8080-exec-1] o.s.w.s.r.ResourceHttpRequestHandler : Resource not found
2020-12-10 17:03:27.056 DEBUG 105120 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed 404 NOT_FOUND
2020-12-10 17:03:27.060 DEBUG 105120 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : "ERROR" dispatch for GET "/error", parameters={}
2020-12-10 17:03:27.062 DEBUG 105120 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#errorHtml(HttpServletRequest, HttpServletResponse)
2020-12-10 17:03:27.083 DEBUG 105120 --- [nio-8080-exec-1] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, text/html;q=0.8]
2020-12-10 17:03:27.087 DEBUG 105120 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Exiting from "ERROR" dispatch, status 404
Can anyone help me please?

Stack overflow calling Spring authenticationManager.authenticate

I started with a spring boot starter project version 2.3.5, but when I call authenticationManager.authenticate I get a stack overflow error.
java.lang.StackOverflowError: null
at ch.qos.logback.classic.Logger.callTurboFilters(Logger.java:751) ~[logback-classic-1.2.3.jar:na]
at ch.qos.logback.classic.Logger.isDebugEnabled(Logger.java:469) ~[logback-classic-1.2.3.jar:na]
at ch.qos.logback.classic.Logger.isDebugEnabled(Logger.java:465) ~[logback-classic-1.2.3.jar:na]
at org.apache.commons.logging.LogAdapter$Slf4jLog.isDebugEnabled(LogAdapter.java:310) ~[spring-jcl-5.2.10.RELEASE.jar:5.2.10.RELEASE]
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:186) ~[spring-security-core-5.3.5.RELEASE.jar:5.3.5.RELEASE]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$AuthenticationManagerDelegator.authenticate(WebSecurityConfigurerAdapter.java:524) ~[spring-security-config-5.3.5.RELEASE.jar:5.3.5.RELEASE]
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:219) ~[spring-security-core-5.3.5.RELEASE.jar:5.3.5.RELEASE]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$AuthenticationManagerDelegator.authenticate(WebSecurityConfigurerAdapter.java:524) ~[spring-security-config-5.3.5.RELEASE.jar:5.3.5.RELEASE]
Initially I did not use the user variable and instead created created the new UsernamePasswordAuthenticationToken inside the authenticationManager.authenticate either way I get the stack overflow error. I also have tried #PostMapping instead of #RequestMapping and Method. All of these cause the same failure.
I get the printline that says I am "in /Authenticate" with the following.
2020-11-09 16:20:32.141 DEBUG 10456 --- [nio-8080-exec-2] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to io.javabrains.springsecurityjwt.HelloResource#createAuthenticationToken(AuthenticationRequest)
2020-11-09 16:20:32.188 DEBUG 10456 --- [nio-8080-exec-2] m.m.a.RequestResponseBodyMethodProcessor : Read "application/json;charset=UTF-8" to [io.javabrains.springsecurityjwt.models.AuthenticationRequest#758a32c5]
in /Authenticate
2020-11-09 16:20:32.197 DEBUG 10456 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Failed to complete request: org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.StackOverflowError
2020-11-09 16:20:32.201 ERROR 10456 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler dispatch failed; nested exception is java.lang.StackOverflowError] with root cause
Here is the full code of the Class
Thank you for any info or things I should try!
package io.javabrains.springsecurityjwt;
import io.javabrains.springsecurityjwt.models.AuthenticationRequest;
import io.javabrains.springsecurityjwt.models.AuthenticationResponse;
import io.javabrains.springsecurityjwt.services.MyUserDetailsService;
import io.javabrains.springsecurityjwt.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
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.RestController;
#RestController
public class HelloResource {
#Autowired
private AuthenticationManager authenticationManager;
#Autowired
private MyUserDetailsService userDetailsService;
#Autowired
private JwtUtil jwtTokenUtil;
#RequestMapping( "/hello")
public String hello() {
return "Hello World";
}
#RequestMapping(value = "/authenticate", method = RequestMethod.POST)
public ResponseEntity<?> createAuthenticationToken(#RequestBody AuthenticationRequest authenticationRequest) throws Exception {
UsernamePasswordAuthenticationToken user = new UsernamePasswordAuthenticationToken(authenticationRequest.getUsername(), authenticationRequest.getPassword());
System.out.println("in /Authenticate");
try {
authenticationManager.authenticate(
user
// new UsernamePasswordAuthenticationToken(authenticationRequest.getUsername(), authenticationRequest.getPassword())
);
System.out.println("in Try in /Authenticate");
} catch (BadCredentialsException e) {
throw new Exception("Incorrect Username or Password", e);
}
System.out.println("outside the try catch");
final UserDetails userDetails = userDetailsService
.loadUserByUsername(authenticationRequest.getUsername());
final String jwt = jwtTokenUtil.generateToken(userDetails);
return ResponseEntity.ok(new AuthenticationResponse(jwt));
}
}

Solving "no suitable HttpMessageConverter found" error

I have simple application that is trying consume Rest service:
#SpringBootApplication
public class ConsumingRestApplication
{
private static final Logger log = LoggerFactory.getLogger(ConsumingRestApplication.class);
public static void main(String[] args)
{
SpringApplication.run(ConsumingRestApplication.class, args);
}
#Bean
public RestTemplate restTemplate(RestTemplateBuilder builder)
{
return builder.build();
}
#Bean
public CommandLineRunner run(RestTemplate restTemplate) throws Exception
{
return args -> {
try
{
restTemplate.getForObject("https://gturnquist-quoters.cfapps.io/api/random", Quote.class);
} catch (RestClientException e)
{
e.printStackTrace();
}
};
}
}
Quote class:
#JsonIgnoreProperties(ignoreUnknown = true)
public class Quote {
private String type;
private Value value;
public Quote() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Value getValue() {
return value;
}
public void setValue(Value value) {
this.value = value;
}
#Override
public String toString() {
return "Quote{" +
"type='" + type + '\'' +
", value=" + value +
'}';
}
}
Got error :
org.springframework.web.client.UnknownContentTypeException: Could not extract response: no suitable HttpMessageConverter found for response type [class com.example.consumingrest.Quote] and content type [application/json;charset=UTF-8]
Whole exception trace:
2020-10-19 12:39:04.984 INFO 8328 --- [ restartedMain] c.e.c.ConsumingRestApplication : Starting ConsumingRestApplication on GM with PID 8328 (C:\gdrive\java_test\consumingrest\build\classes\java\main started by g in C:\gdrive\java_test\consumingrest)
2020-10-19 12:39:04.987 INFO 8328 --- [ restartedMain] c.e.c.ConsumingRestApplication : No active profile set, falling back to default profiles: default
2020-10-19 12:39:05.070 INFO 8328 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2020-10-19 12:39:05.070 INFO 8328 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2020-10-19 12:39:06.843 INFO 8328 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-10-19 12:39:06.856 INFO 8328 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-10-19 12:39:06.857 INFO 8328 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.38]
2020-10-19 12:39:06.957 INFO 8328 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-10-19 12:39:06.957 INFO 8328 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1887 ms
2020-10-19 12:39:07.204 INFO 8328 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-10-19 12:39:07.395 INFO 8328 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2020-10-19 12:39:07.603 INFO 8328 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-10-19 12:39:07.617 INFO 8328 --- [ restartedMain] c.e.c.ConsumingRestApplication : Started ConsumingRestApplication in 3.076 seconds (JVM running for 3.545)
2020-10-19 12:39:07.786 WARN 8328 --- [ restartedMain] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.example.consumingrest.Quote]]: com.fasterxml.jackson.databind.JsonMappingException: Cannot deserialize Class org.springframework.beans.factory.annotation.Value (of type annotation) as a Bean
2020-10-19 12:39:07.786 WARN 8328 --- [ restartedMain] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.example.consumingrest.Quote]]: com.fasterxml.jackson.databind.JsonMappingException: Cannot deserialize Class org.springframework.beans.factory.annotation.Value (of type annotation) as a Bean
2020-10-19 12:39:08.541 WARN 8328 --- [ restartedMain] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.example.consumingrest.Quote]]: com.fasterxml.jackson.databind.JsonMappingException: Cannot deserialize Class org.springframework.beans.factory.annotation.Value (of type annotation) as a Bean
2020-10-19 12:39:08.542 WARN 8328 --- [ restartedMain] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.example.consumingrest.Quote]]: com.fasterxml.jackson.databind.JsonMappingException: Cannot deserialize Class org.springframework.beans.factory.annotation.Value (of type annotation) as a Bean
2020-10-19 12:39:08.544 WARN 8328 --- [ restartedMain] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.example.consumingrest.Quote]]: com.fasterxml.jackson.databind.JsonMappingException: Cannot deserialize Class org.springframework.beans.factory.annotation.Value (of type annotation) as a Bean
2020-10-19 12:39:08.545 WARN 8328 --- [ restartedMain] .c.j.MappingJackson2HttpMessageConverter : Failed to evaluate Jackson deserialization for type [[simple type, class com.example.consumingrest.Quote]]: com.fasterxml.jackson.databind.JsonMappingException: Cannot deserialize Class org.springframework.beans.factory.annotation.Value (of type annotation) as a Bean
org.springframework.web.client.UnknownContentTypeException: Could not extract response: no suitable HttpMessageConverter found for response type [class com.example.consumingrest.Quote] and content type [application/json;charset=UTF-8]
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:126)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:741)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:674)
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:315)
at com.example.consumingrest.ConsumingRestApplication.lambda$run$0(ConsumingRestApplication.java:37)
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:795)
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:779)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:322)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)
at com.example.consumingrest.ConsumingRestApplication.main(ConsumingRestApplication.java:21)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
What is starting point o solving this problem? What logic I should go to find problem?
I believe you are missing Value object or must be a wrong import. Along with that you need to add getter methods for the field if they are private, when you are returning that object directly in the response, here is how i have done it:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
#RestController
public static class Test {
#Autowired
private RestTemplate restTemplate;
#GetMapping
public Quote test() {
return restTemplate.getForObject("https://gturnquist-quoters.cfapps.io/api/random", Quote.class);
}
}
public static class Quote {
private String type;
private Value value;
public String getType() {
return type;
}
public Value getValue() {
return value;
}
}
public static class Value {
private Long id;
private String quote;
public Long getId() {
return id;
}
public String getQuote() {
return quote;
}
}
}

JstlView forwarding request to dispatcher servlet instead of rendering the view(Spring boot + Spring MVC)

I have set up an spring boot application and I am trying to run a simple mvc flow. But JstlView class is forwarding the request to render /WEB-INF/views/jsp/login.jsp to 'dispatcherServlet' and I am getting the following logs:-
2015-10-25 17:43:06.143 DEBUG 6181 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Rendering view [org.springframework.web.servlet.view.JstlView: name 'login'; URL [/WEB-INF/views/jsp/login.jsp]] in DispatcherServlet with name 'dispatcherServlet'
2015-10-25 17:43:06.143 DEBUG 6181 --- [nio-8080-exec-1] o.s.web.servlet.view.JstlView : Added model object 'username' of type [java.lang.String] to request in view with name 'login'
2015-10-25 17:43:06.146 DEBUG 6181 --- [nio-8080-exec-1] o.s.web.servlet.view.JstlView : Forwarding to resource [/WEB-INF/views/jsp/login.jsp] in InternalResourceView 'login'
2015-10-25 17:43:06.148 DEBUG 6181 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Successfully completed request
My Application.java to run spring boot application:-
#Configuration
#EnableAutoConfiguration
#ComponentScan("com.thinksmallgroup.projectmanager")
#EnableWebMvc
public class Application {
#Bean
public DispatcherServlet dispatcherServlet() {
return new DispatcherServlet();
}
#Bean
public ServletRegistrationBean dispatcherRegistration() {
ServletRegistrationBean registration = new ServletRegistrationBean(dispatcherServlet(), "*.do");
return registration;
}
/**
* main method to start the application.
*
* #param args
* any arguments passed while running the application.
*/
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
My WebConfig.java
#Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/views/jsp/", ".jsp");
registry.order(Ordered.HIGHEST_PRECEDENCE);
}
}
Controller:-
#Controller
public class LoginController {
/**
* #param name
* #return String
*/
#RequestMapping("/login.do")
public ModelAndView login(#RequestParam(required = false) String name) {
return new ModelAndView("login", "username", "VIneet");
}
My login.jsp:-
<html>
<head><title>Think Small Group</title></head>
<body>
<h1>Project Manager</h1>
<p>Welcome ${username}</p>
</body>
</html>

Categories