How to do I ignore the class level #RequestMapping("/home") and directly call the method level #RequestMapping("/users") in Spring?
#Controller
#RequestMapping("/home")
#RequestMapping("/method1")
public void method1(){
...
}
#RequestMapping("/users")
public void listUsers(){
...
}
I want to call http://localhost:8080/users to invoke listUsers() method.
You cannot bypass requestmapping defined at class level. for If so why you want a class level mapping then... you can instead do something like this in the method level request mapping
#Controller
#RequestMapping("/home/method1")
public void method1(){
...
}
#RequestMapping("/users")
public void listUsers(){
...
}
In that case you may try this...
#Controller
#RequestMapping({ "/home", "/users" })
#RequestMapping("/method1")
public void method1(){
...
}
#RequestMapping(method="RequestMethod.GET")
public void listUsers(){
...
}
Change #RequestMapping("/users") for #RequestMapping(method=RequestMethod.GET)
From my understanding, what you expect is a class-level RequestMapping. The method-level RequestMapping should be under the path of class-level's.
I'll give you some examples:
#RestController
#RequestMapping("/home")
public class HomeController {
// Full path of following endpoint: /home/parents.
#RequestMapping(value = "/parents", method = RequestMethod.GET)
public ResponseEntity<List<People>> getParents() {
return ResponseEntity.ok(methodToGetParents());
}
For the path of "users" you should do it in another class (controller):
#RestController
#RequestMapping("/users")
public class UsersController {
// Full path of following endpoint: /users.
#RequestMapping(method = RequestMethod.GET)
public ResponseEntity<List<People>> getUsers() {
return ResponseEntity.ok(methodToGetUsers());
}
Related
#RestController()
#RequestMapping(path = "/users")
public class UserController {
#GetMapping()
public #ResponseBody Page<User> getAllUsers(#RequestParam Integer pageSize, UserRequest userRequest) {
//TODO: some implementation
}}
public class UserRequest{
public String name;
public String age;
}
send the request with invalid parameter, like localhost:8800/users?name1=1234, I want to return error. but in fact it ignore the invalid parameter name1.
I tried to add the user defined annotation on the method parameter and on the class , codes like below
#RestController()
#RequestMapping(path = "/users")
#Validated
public class UserController {
#GetMapping()
public #ResponseBody Page<User> getAllUsers(#RequestParam #Validated Integer pageSize, #Validated UserRequest userRequest} {
//TODO: some implementation
}
}
But it does not working.
I think it is happened because framework has ignore the invalid parameter before the method was called.
where did framework handle the url and how can I do to make it return error instead of ignore?
You can reject parameters that are not valid. You can do so in a HandlerInterceptor class.
Reference: Rejecting GET requests with additional query params
In addition to what is done in the above reference, in your addInterceptors, you can specify the path that is intercepted.
Like this:
#Configuration
public class WebConfig implements WebMvcConfigurer {
private String USERS_PATH = "/users";
// If you want to cover all endpoints in your controller
// private String USERS_PATH = List.of("/users", "/users/**");
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new FooHandlerInterceptor()).addPathPatterns(USERS_PATH);
}
}
I create the following controller:
#Controller
public class RootController {
#RequestMapping(path = "/login", method = RequestMethod.GET)
public String showLoginPage() {
return "redirect:resources/templates/login.html";
}
}
But, trying to map this endpoint, I receive 404-ERROR.
This is a target-page location:
What am I doing wrong?
#Controller
public class RootController {
#GetMapping("/login")
public String showLoginPage() {
return "login";
}
It works to me.I hope hepls you!
#Controller
public class RootController {
#GetMapping("/login")
public String showLoginPage() {
return "login.html";
}
This will work
I want to have a RestController-class with the base-mapping "/user" (so the different functions will have paths like "/user/add", "/user/remove" etc or use POST/GET etc)
This is the part that I don't understand and can't get to work:
#RestController
public class UserController {
#GetMapping("/user")
public Response login(Principal principal){
//some output
}
}
Expected behavior for this case would be that I can access my output under "/user". This works as expected.
Now if I modify it to the following (since all functions in this controller should have a path starting with "/user" this would be cleaner)
#RestController
#RequestMapping("/user")
public class UserController {
#GetMapping("/")
public Response login(Principal principal){
//some output
}
}
I get a 404-Error page and can't access "/user" anymore
All examples I have found use the same syntax (or sometimes #RequestMapping(path="/user") but that didn't work as well) and I don't know why it doesn't work.
Can someone tell me where my mistake is?
If you use this code:
#RestController
#RequestMapping("/user")
public class UserController {
#GetMapping("/")
public Response login(Principal principal){
//some output
}
}
Then your url should have "/" at the end like "http://localhost:8080/user/"
I would just throw away "/" symbol from #GetMapping("/") and left like this:
#RestController
#RequestMapping("/user")
public class UserController {
#GetMapping
public Response login(Principal principal){
//some output
}
}
And if you need map get or post you can use like this:
#RestController
#RequestMapping("/user")
public class UserController {
#GetMapping("/add")
public SampleObj getJson() {
return new SampleObj();
}
}
It should work.
Assertion error using #RequestMapping annotation outside of the class
I am getting this error message:
java.lang.AssertionError: Status
Expected :200
Actual :404
My Controller is like this
#Service
#RestController
#RequestMapping("/execute/files")
#ResponseBody
public class ControllerFiles {
#Autowired
#Qualifier("fileRunner")
ProcessRunnerInterface processRunnerInterfaceFiles;
public InputState executeRestFile(#RequestParam String name) throws ExecutionFailedException, URISyntaxException {
///code///
}
public List<String>....{
///code///
}
}
My Test
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest
#AutoConfigureMockMvc
public class ControllerFilesTest {
#Autowired
private MockMvc mockMvc;
#Autowired
ControllerFiles controllerFiles;
#Test
public void testSpringMvcGetFiles() throws Exception {
this.mockMvc.perform(get("/execute/files").param("name", "Spring Community Files"))
.andDo(print()).andExpect(status().isOk());
}
}
But when I have my code like this the test work fine!
#Service
#RestController
public class ControllerFiles {
#Autowired
#Qualifier("fileRunner")
ProcessRunnerInterface processRunnerInterfaceFiles;
#RequestMapping("/execute/files")
#ResponseBody
public InputState executeRestFile(#RequestParam String name) throws ExecutionFailedException, URISyntaxException {
///code///
}
public List<String>....{
///code///
}
}
Any ideas what is going wrong?
The methods in your RestController need to be marked as #RequestMapping if you want them to be picked up as request resources. If you want to keep the base request mapping at the controller level as in your first RestController then you need to do the following:
#RestController
#RequestMapping("my/path")
public class MyController {
#RequestMapping("/")
public InputState myMethod() {
...
}
}
As it is said in documentation:
In the above example, #RequestMapping is used in a number of places. The first usage is on the type (class) level, which indicates that all handler methods in this controller are relative to the /appointments path.
So the class level #RequestMapping is only indicating relativnes. It is not declare actual resource paths based on public methods only. So you need to annotate your method like this:
#GetMapping
public InputState executeRestFile(#RequestParam String name) throws Exception {
// omited
}
Or like this:
#RequestMapping(method = RequestMethod.GET)
public InputState executeRestFile(#RequestParam String name) throws Exception {
// omited
}
Say I have this:
#RequestMapping(value="/hello")
public ModelAndView hello(Model model){
System.out.println("HelloWorldAction.sayHello");
return null;
}
Is it possible to skip the value="hello" part, and just have the #RequestMapping annotation and have spring use the method name as the value, similar to this:
#RequestMapping
public ModelAndView hello(Model model){
System.out.println("HelloWorldAction.sayHello");
return null;
}
Thanks!
===================EDIT=====================
Tried this but not working:
#Controller
#RequestMapping(value="admin", method=RequestMethod.GET)
public class AdminController {
#RequestMapping
public ResponseEntity<String> hello() {
System.out.println("hellooooooo");
}
}
Try to add "/*" on the request mapping value of the class
#Controller
#RequestMapping(value="admin/*")
public class AdminController {
#RequestMapping
public ResponseEntity<String> hello() {
System.out.println("hellooooooo");
}
}
You can go the page http://localhost:8080/website/admin/hello
It should work if you move the RequestMethod on your specific method:
#Controller
#RequestMapping(value="admin")
public class AdminController {
#RequestMapping(method=RequestMethod.GET)
public ResponseEntity<String> hello() {
System.out.println("hellooooooo");
}
}
and access it through http://hostname:port/admin/hello
Have a look here: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping
Good luck