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

后端 未结 5 864
长情又很酷
长情又很酷 2021-01-03 00:34

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         


        
相关标签:
5条回答
  • 2021-01-03 01:01

    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

    0 讨论(0)
  • 2021-01-03 01:05

    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";
            }
    
    }
    
    0 讨论(0)
  • 2021-01-03 01:09

    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;
     }
    
    0 讨论(0)
  • 2021-01-03 01:13

    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);
    }
    
    0 讨论(0)
  • 2021-01-03 01:17

    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";
    }
    
    0 讨论(0)
提交回复
热议问题