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
@R
You should place method getUser in a service (example UserService class) .
In the getUser controller, you call method getUser in the Service to get the User
Similarly, in the updatePswd controller, you call method getUser in the Service ,too
Here no need to add @reponseBody annotation as your redirecting to another controller Your code will look like
@Controller
class ControlloerClass{
@RequestMapping(value="/getUser",method = RequestMethod.GET)
@ResponseBody
public User getUser(){
User u = new User();
//Here my dao method is activated and I wil get some userobject
return u;
}
@RequestMapping(value="/updatePSWD",method = RequestMethod.GET)
public String updatePswd(){
//update your user password
return "redirect:/getUser";
}
}
A controller class is a Java class like any other. Although Spring does clever magic for you, using reflection to examine the annotations, your code can call methods just as normal Java code:
public String updatePasswd()
{
User u = getUser();
// manipulate u here
return u;
}
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);
}
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";
}