package controller;
import org.springframework.web.bind.annotation.*;
#RestController
#RequestMapping("users") //localhost:8080/users
public class UserController {
#GetMapping
public String getUser()
{
return "get the user";
}
#PostMapping
public String creteUser()
{
return "create user";
}
#PutMapping
public String updateUser()
{
return "update user";
}
#DeleteMapping
public String deleteUser()
{
return "delete user";
}
}
This is the code, I don't what's wrong with it. Application is running fine still getting no response. I have added all required dependencies.
Try checking the mapping again, there might be an incorrect URI while making the request.
Create UserNotFoundException class. It is a checked exception. Spring Boot auto-configures some default exception handling.
It would be good if we define a standard exception structure that is followed by across all the RESTful Services.
Related
When I try GET on localhost:8080/path I get 404 error.
endpoint:
#Path("path")
#Produces(MediaType.TEXT_PLAIN)
public Controller {
#GET
public String getString() {
return "hello";
}
}
project structure looks like this:
com.example.demo.controller.Controller.java
com.example.demo.DemoApplication.java
Project is generated with Spring Initializr with spring web and lombok and nothing else.
You are using JAX-RS with Spring Boot. You must use Spring MVC
#RestController
#RequestMapping("/path")
public Controller {
#GetMapping
public String getString() {
return "hello";
}
}
You should start with reading the documentation:
https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-developing-web-applications
https://spring.io/guides/gs/rest-service/
I am trying to auto-generate the swagger page for a RestAPI in Spring Boot using annotations.
Code of Controller:
#RestController
#Api(value="UserManagementAPI", produces = MediaType.APPLICATION_JSON_VALUE)
public class UserManagementController {
#RequestMapping("/")
public String index() {
return "Greetings from Spring Boot!";
}
#ApiOperation(value="add a pro",consumes="application/json")
#RequestMapping(value = "/getUser", method = RequestMethod.GET, produces="application/json")
public static List<UserDetails> getUser(#PathVariable(name="id") String id) throws UserException
{
return UserHelper.getUserByEmail(id);
}
Application.java
#SpringBootApplication
#EnableSwagger2
#Configuration
#ComponentScan({ "userManagement"})
#EnableAutoConfiguration
public class Application {
#Bean
public Docket simpleDiffServiceApi() {
return new Docket(DocumentationType.SWAGGER_2).groupName("userManagement").apiInfo(apiInfo()).select()
.apis(RequestHandlerSelectors.any())
// .paths(PathSelectors.any())
// Will also include the basic error controllers by default
.paths(Predicates.not(PathSelectors.regex("/error")))
// Exclude basic error controllers
.build().pathMapping("/");
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("Business Location Service")
.description("Spring Boot REST APIs for Business Location Service")
.contact(new Contact("EntSol-IoT (Niche Technology Delivery Group)", "http://somewebsite.com",
"some#mail.com"))
.version("1.0").build();
}
In the swagger page, I can see all my APIs. But there are more. It is showing all possible method type (e.g POST, GET, PUT etc.) though in Controller I only wrote GET method.
Another issue is that there is no Textbox in the swagger page under the API where I can search for the id. May be I am missing something. I have been trying to resolve it for past two days. But couldn't help myself. Thanks in advance.
I got the problem. Your getUser method is declared as static. Please remove static, for it to work.
public List<UserDetails> getUser(#PathVariable(name="id") String id) throws UserException { }
Controller class.
#RestController
#RequestMapping("/check")
public class Controller {
public String index(){
return "sdfksdjfkjkUshshdfisdfsdkasjdfjkasjdfkjakl:";
}
Application class
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
Added all the necessary dependency when running the application shows the
http://localhost:8081/demo/
Hello World
of index.xml
When I change to http://localhost:8081/check/ it gives
HTTP Status 404 – Not Found
Type Status Report
Message /check
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
How can I understand the flow of Spring Boot application?
You need to put the Http method on your method, here I am assuming you are doing a GET request
#RestController
#RequestMapping("/check")
public class Controller {
#GetMapping // you forgot to put http method here
public String index(){
return "sdfksdjfkjkUshshdfisdfsdkasjdfjkasjdfkjakl:";
}
Note: GetMapping is only available if you are using Spring 4.3 or above else use #RequestMapping(value = "/url", method = RequestMethod.GET)
Your controller should be like this:
#RestController
public class Controller {
#RequestMapping(value="/check")
public String index(){
return "sdfksdjfkjkUshshdfisdfsdkasjdfjkasjdfkjakl:";
}
}
It seems
#RequestMapping(value="/check") is not working.
switch to
#RequestMapping(path="/check")
though as per documentation it should work.
Let's say my website name is: foo.com
When a user types foo.com, I want to show index.html.
When a user types foo.com/something, I want the server catches the request at the controller.
Here is what I did in the HomeController:
#Controller
public class HomeController {
#RequestMapping(value={"/"}, method=RequestMethod.GET)
public String getHome() {
return "index.html";
}
}
And, the CustomController should catch the request
#Controller
public class CustomController {
#RequestMapping(value={"/{custom}"}, method=RequestMethod.GET)
public String getCustom(#PathVariable String custom) {
// Do something here..
}
}
However, it throws an error: Circular view path [index.html]: would dispatch back to the current handler URL [/index.html] again. It's because the CustomController catches the GET request: foo.com/index.html after the HomeController returns the string: index.html.
I did some research like this:
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/assets"); // My asset
registry.addResourceHandler("index.html").addResourceLocations("file:/index.html");
} // It's not working
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("forward:/" + FileNames.INDEX);
} // This also not working
}
And changing the annotation from #Controller to #RestController in the CustomController is not an option.
Also, I don't have JSP files in the project - they are plain *.html files.
I am using Spring 1.3.3 release, so please help me out.
This solution works with ui-router (AngularJS library). Also, you have to change $resourceProvider setting:
// In your app module config
$resourceProvider.defaults.stripTrailingSlashes = false;
Then, in the Spring server codes, you can do this:
#RequestMapping(value = "/{custom:[^\\.]*}")
public String redirect(#PathVariable String custom) {
// Do something here...
return "forward:/";
}
Found the solution at this link: https://spring.io/blog/2015/05/13/modularizing-the-client-angular-js-and-spring-security-part-vii
I'd like to return a custom 404 error using SpringBoot, but I'd like to be able to add some server-side logic to it, not just serve a static page.
1. I switched off the default whitelabel page in application.properties
error.whitelabel.enabled=false
2. I added a Thymeleaf error.html under resources/templates
This works by the way. The page is served, but no controller is called.
3. I created a class Error to be the "Controller"
package com.noxgroup.nitro.pages;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
#RequestMapping("/error")
public class Error {
#ExceptionHandler
public String index() {
System.out.println("Returning Error");
return "index";
}
}
Unfortunately, I'm not seeing Returning Error printed anywhere in the console.
I'm using the Embedded Tomcat with Spring Boot. I've seen various options, non of which seem to work including using #ControllerAdvice, removing the RequestMapping, etc. Neither work for me.
The servlet container is going to pick up the 404 before it can get to Spring, so you'll need to define an error page at servlet container level, which forwards to your custom controller.
#Component
public class CustomizationBean implements EmbeddedServletContainerCustomizer {
#Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/error"));
}
}
Easiest way I found was to implement the ErrorController.
#Controller
public class RedirectUnknownUrls implements ErrorController {
#GetMapping("/error")
public void redirectNonExistentUrlsToHome(HttpServletResponse response) throws IOException {
response.sendRedirect("/");
}
#Override
public String getErrorPath() {
return "/error";
}
}