Amit mahala
Amit mahala

Reputation: 33

Need to pass object from one controller to another controller

I am having 2 controllers in my class :-1st controller return to a jsp page , in that jsp i am using a form ,on submitting that form it calls 2nd controller . I want to pass one object from 1st controller to 2nd controller and dont want to send that object to intermediate jsp page so is there any way to do this .I dont want to use session attribute also

this is my 1st controller

@RequestMapping(value = "/login", method = RequestMethod.GET)
public static String login(final Model model) {
    final Studentdata studentdata = new Studentdata();
    studentdata.setName("username");
        return "Login" ;
    }

this is my Login.Jsp

<form action="/loungeHotel/checkLogin" method="post">
    <input type="submit" value="submit">
</form>

this is 2nd controller

@RequestMapping(value = "/checkLogin", method = RequestMethod.POST)
public static String checkLogin(final Model model) {
    System.out.println("here i want to access studentdata");
    return "MyAccount";
}

Upvotes: 0

Views: 5063

Answers (1)

LHA
LHA

Reputation: 9655

I think HttpSession is the right choice.

If you don't want to use HttpSession or any server storage such as Database, ... You can use this way - Client storage by using hidden inputs

  1. Modify login to store studentdata in request attribute

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    
    public static String login(HttpServletRequest request, final Model model) {
    
        final Studentdata studentdata = new Studentdata();
        studentdata.setName("username");
    
        request.setAttribute("studentData", studentdata);
    
        return "Login" ;
    }
    
  2. Modify login jsp

    <form action="/loungeHotel/checkLogin" method="post">
    
        <!-- Write all studentdata Properties as Hidden inputs  -->
    
        <input type="hidden" name="property1" value="${studentData.property1}"
        <input type="hidden" name="property2" value="${studentData.property2}"
        <input type="hidden" name="property3" value="${studentData.property3}"
    
        <input type="submit" value="submit">
    
    
    </form>
    
  3. Modify checkLogin

    RequestMapping(value = "/checkLogin", method = RequestMethod.POST)
    
        public static String checkLogin(HttpServletRequest request, final Model model) {
    
            System.out.println("here i want to access studentdata");
    
            // Recreate StudentData From request.getParameter(...)
    
            Studentdata studentdata = new Studentdata();
            studentdata.setProperty1 ( request.getParameter("property1"));
            // ... You may have to convert data too
    
            return "MyAccount";
    }
    

Upvotes: 2

Related Questions