Spring Boot Controller is not calling - spring

My Application class in au.com.domain.demo package and my controller class au.com.domain.demo.control package. I tried to call get method in controller class, but it is not calling.
#SpringBootApplication
public class IssueTrackerApplication {
public static void main(final String[] args) {
System.out.println("coming here.0000..");
SpringApplication.run(IssueTrackerApplication.class, args);
}
}
My controller class is:
#RestController
public class IssueTrackingController {
#RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello() {
return "hello";
}
}

I suggest to try to follow an official tutorial from Spring: https://spring.io/guides/gs/rest-service/ - maybe it helps.
The other thing is - try not to return String from the method, but return an object instead. Spring Boot converts POJO classes to JSON.
Hope this helps :)

Related

Spring boot controller not being detected

Good day. I'm having issues with my Springboot app. The controller isn't being detected.The Component scan is used but it won't detect the controllers.
Folder structure
Application
#EntityScan(basePackages = "com.jokedata.models")
#EnableJpaRepositories(basePackages = "com.jokedata.repositories")
//#ComponentScan(basePackages = {"com.jokeweb.project.controllers"})
#SpringBootApplication(scanBasePackages = "com.jokeweb.project.controllers")
public class JokeApplication {
public static void main(String[] args) {
SpringApplication.run(JokeDataApplication.class, args);
}
}
Controller
#RestController
public class UserController {
#GetMapping("/home")
public String home() {
return "home";
}
}
Check if request URL or application port is correct or not.

Spring Boot - #RestController annotation gets picked up, but when replaced with #Controller annotation, it stops working

Here is a dummy project for the same :-
BlogApplication.java
#SpringBootApplication
#RestController
public class BlogApplication {
public static void main(String[] args) {
SpringApplication.run(BlogApplication.class, args);
}
#GetMapping("/hello")
public String hello(#RequestParam(value = "name", defaultValue = "World") String name) {
return String.format("Hello %s!", name);
}
}
HtmlController.java
#Controller //does not work
OR
#RestController //works
public class HtmlController {
#GetMapping("/getHtmlFile")
public String getHtmlFile() {
return "Bit Torrent Brief";
}
}
Why is it that #RestController is able to map getHtmlFile but #Controller returns 404 when /getHtmlFile is hit?
#RestController is the combination of #Controller and #ResponseBody.
when you use #Controller, you should write #ResponseBody before your method return type
#Controller
public class HtmlController {
#GetMapping("/getHtmlFile")
public #ResponseBody String getHtmlFile() {
return "Bit Torrent Brief";
}
}
This works.

#RestController returning blank

I'm building my first Spring Boot application. But I can't get my requestMapping controller answer properly.
This is my main class:
package com.hello.world;
#SpringBootApplication
public class HelloWorld implements CommandLineRunner{
public static void main(String[] args) {
SpringApplication.run(HelloWorld.class, args);
}
#Override
public void run(String... args) throws Exception {
....
}
}
And this is my RestController:
package com.hello.world.controllers;
#RestController
public class UrlMappingControllers {
#RequestMapping("/hi")
String home() {
return "Hello World!";
}
}
If I take a look at the log I can see the "/hi" mapping:
restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hi]}" onto java.lang.String com.hello.world.controllers.UrlMappingControllers.home()
But when I access: http:localhost:8080/hi I get a blank page, I expected seing the "Hello World" text.
Why am I getting a blank page?
--- Edit ----
I've just realised that I am getting the blank page only when I add a cxf service. I think it is because the #configuration annotation on this class:
package com.hello.world.helloWorld.configuration;
#Configuration
public class CXFConfiguration {
#Bean
public ServletRegistrationBean dispatcherServlet() {
return new ServletRegistrationBean(new CXFServlet(), "/services/*");
}
#Bean(name=Bus.DEFAULT_BUS_ID)
public SpringBus springBus() {
SpringBus springBus = new SpringBus();
return springBus;
}
#Bean
public Endpoint endpointGreentingService() {
EndpointImpl endpoint = new EndpointImpl(springBus(), new GreetingServiceImpl());
endpoint.getFeatures().add(new LoggingFeature());
endpoint.publish("/GreetingService");
return endpoint;
}
}
Could it be related?
#RestController = #Controller + #ResponseBody which means that when you call your api at http:localhost:8080/hi the body of the response will contain the result of the home() handler, i-e "Hello world".
#RestControllerbehind the scene makes Spring MVC uses a Json Message Converter (by default) and all handler methods inside a class annoted with #RestController will return a JSON, that is why you do not see your text on your browser.
You can use Postman or ARC to test your app. Some web browsers like Firefox shows JSON directly.

In Spring how to send enum as response in controller

I have Enum Class. I Need to send a Enum class Response from the Spring controller.
I am not able understand how to sent class as Response in spring controller. Please help me for that.
You can add anything which Jackson can de-serialize in a reponse
#RestController
public class HelloController {
#RequestMapping("/monday")
public ResponseEntity<DayOfWeek> monday() {
return new ResponseEntity<DayOfWeek>(DayOfWeek.MONDAY, HttpStatus.OK);
}
#RequestMapping("/days")
public ResponseEntity<List<DayOfWeek>> days() {
return new ResponseEntity<List<DayOfWeek>>(Arrays.asList(DayOfWeek.values()), HttpStatus.OK);
}
}
You can prove this to yourself with the following test, just do the Jacskon de-serialization manually
#RunWith(SpringRunner.class)
#SpringBootTest
#AutoConfigureMockMvc
public class HelloControllerTest {
#Autowired
private MockMvc mvc;
#Test
public void monday() throws Exception {
String json = new ObjectMapper().writeValueAsString(DayOfWeek.MONDAY);
mvc.perform(MockMvcRequestBuilders.get("/monday").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
.andExpect(content().string(equalTo(json)));
}
#Test
public void days() throws Exception {
String json = new ObjectMapper().writeValueAsString(Arrays.asList(DayOfWeek.values()));
mvc.perform(MockMvcRequestBuilders.get("/days").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
.andExpect(content().string(equalTo(json)));
}
}
If you wanna return all enum values than try something like this:
#GetMapping("enum")
public List<MyEnum> paymentMethods() {
return Arrays.asList(MyEnum.values());
}
public enum MyEnum {
FIRST, SECOND, THIRD;
}

access to property in external file works in controller but not in domain class

I have a property set in an external application.properties file and find that I can access it in the controller but not in the domain class. I'm using SpringBoot 1.1.9 and groovy and code snippets listed below.
Can someone please explain what I'm missing here?
Thanks!
--john
//Application class used to startup
#Configuration
#ComponentScan
#EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
//Controller - property is injected
#RestController
class CityController {
#Value( '${sample.property}' )
String stringTemplate
#RequestMapping(value = "/", method = RequestMethod.GET)
public String index(HttpServletResponse response) {
return String.format(stringTemplate, 'world')
}
}
//Domain class - property does not seem to be injected
#Component
public class City {
#Value( '${sample.property}' )
String stringTemplate
String toString() {
return String.format(stringTemplate, 'world')
}
}

Resources