Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call one controller to another controller URL in Spring MVC?

Hi I am new to Spring MVC ,I want to call method from one controller to another controller ,how can I do that .please check my code below

@Controller

    @RequestMapping(value="/getUser")
    @ResponseBody
    public User getUser()
    {
        User u = new User();
        //Here my dao method is activated and I wil get some userobject
       return u;
    }
   @Controller

    @RequestMapping(value="/updatePSWD")
    @ResponseBody
    public String updatePswd()
    {
        here I want to call above controller method and 
       I want to update that user password here.
       how can  I do that 
        return "";
    }

any one help me .

like image 760
user2963481 Avatar asked Jul 25 '14 07:07

user2963481


People also ask

Can we call one controller method from another controller?

Yes, you can call a method of another controller. The controller is also a simple class.

How do you call a controller in spring?

Spring REST Controller TestGo to URL https://localhost:8080/Spring-Controller/rest and you should get following output. Now let's provide the name parameter value in the URL, go to https://localhost:8080/Spring-Controller/rest/person/get?name=Pankaj and you will get following JSON response.

How do I forward a Spring MVC request?

@Controller public class MainController { @Autowired OtherController otherController; @RequestMapping("/myurl") public String handleMyURL(Model model) { otherController. doStuff(); return ...; } } @Controller public class OtherController { @RequestMapping("/doStuff") public String doStuff(Model model) { ... } }


2 Answers

Can do like this:

@Autowired
private MyOtherController otherController;

@RequestMapping(value = "/...", method = ...)
@ResponseBody
public String post(@PathVariable String userId, HttpServletRequest request) {
    return otherController.post(userId, request);
}
like image 129
Pavel Evstigneev Avatar answered Sep 17 '22 15:09

Pavel Evstigneev


You never have to put business logic into the controller, and less business logic related with database, the transactionals class/methods should be in the service layer. But if you need to redirect to another controller method use redirect

@RequestMapping(value="/updatePSWD")
@ResponseBody
public String updatePswd()
{
  return "redirect:/getUser.do";
}
like image 37
paul Avatar answered Sep 20 '22 15:09

paul