mmelear
mmelear

Reputation: 97

@ModelAttribute pass form data to new controller

I have a two controllers in play in this one. The first controller sets up the model and view for the welcome.jsp, which asks for input of data.

The second controller takes in the data, and routes to a service to take the data to the database. The problem I have is that when I have this piece of code in controller #2

@ModelAttribute("transaction")
    public TransactionHelper getTransactionHelper2(){
        System.out.println("in helper2");
        return new TransactionHelper();

All of my form data is null (makes sense, because it returns a new instance. but I don't know how to pass in the form data properly). How do I pass the form data to this method? Please see code below:

Controller 1

package com.atmWebApp.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.atmWebApp.entities.Account;
import com.atmWebApp.entities.TransactionHelper;
import com.atmWebApp.services.AccountService;
import com.atmWebApp.services.TransactionService;

@Controller
public class AccountController {

        @Autowired
        AccountService accountService;

        @ModelAttribute("account")
        public Account getAccountObject() {
              return new Account();
             }


        @ModelAttribute("transaction")
        public TransactionHelper getTransactionHelper(){
            System.out.println("in helper");
            return new TransactionHelper();
        }

        @RequestMapping("/")
        public ModelAndView helloWorld1() {
            return new ModelAndView("index");
        }

        @RequestMapping(value = "/login/", method = RequestMethod.POST)
        public ModelAndView login(@ModelAttribute("account") Account account, BindingResult result) {
            String accountId = account.getAccountId();
            String pin = account.getPin();

            if (accountId != null && pin != null){

                Account currentAccount = accountService.login(accountId, pin);
                System.out.println(currentAccount.getAccountId());
                if (currentAccount.getAccountId() != null){
                    return new ModelAndView("welcome", "balance", accountService.getAccountBalance(currentAccount.getAccountId()))
                                .addObject("accountId", accountId);
                }
            }
            return new ModelAndView("index", "message", "Wrong Account Number/PIN Combination");
        }


}

Controller 2

package com.atmWebApp.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.atmWebApp.entities.TransactionHelper;
import com.atmWebApp.services.TransactionService;

@Controller
public class TransactionController {


    @Autowired
    TransactionService transactionService;


/*  @ModelAttribute("transaction")
    public TransactionHelper getTransactionHelper2(){
        System.out.println("in helper2");
        return new TransactionHelper();
    }*/

    @RequestMapping(value = "/transact/")
    public ModelAndView login(@ModelAttribute("transaction") TransactionHelper transactionHelper, BindingResult result) {
        String accountId = transactionHelper.getAccountId();
        System.out.println(transactionHelper);
        System.out.println(transactionHelper.getDollarAmount());
        System.out.println(transactionHelper.getAccountId());
        String dollarAmount = transactionHelper.getDollarAmount();
        String transactionType = transactionHelper.getTransactionType();
        if (!transactionService.isValidDollarAmount(dollarAmount)){
            System.out.println("invalid amount");
            return new ModelAndView("welcome", "message", "Invalid Dollar Amount");
        }
        transactionService.initiateTransaction(transactionType, dollarAmount, accountId);
        return new ModelAndView(new RedirectView("index"), "message", "Transaction Successful");
    }

}

And the view:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Your account balance is   ${balance}.

<form:form commandName="transaction" action="/AtmWebApp/transact/">
<table>
<tr>
<td>Your Account Number:</td>
<td>
<form:select path="accountId">
   <form:option value= "${accountId}" />
</form:select></td>
<td>Deposit or Withdrawal?</td>
<td><form:select path="transactionType">
   <form:option value="deposit" />
   <form:option value="withdrawal" />
</form:select></td>
</tr>
<tr>
<td>How Much?</td>
<td><form:input path="dollarAmount" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit" />
</td>
</tr>
</table>
</form:form>
</body>
</html>

Upvotes: 0

Views: 2131

Answers (1)

Ankur Singhal
Ankur Singhal

Reputation: 26077

Both @SessionAttributes and @ModelAttribute will be maintained for all the handler methods of one same controller class and please note that this session attributes/model attributes can not be access by another controller classes, to do so you have to add this attribute in HttpSession.

You have 3 options

  1. Use @SessionAttributes to store the object in the session in between requests.
  2. Use @ModelAttribute annotated method to retrieve the object before each request
  3. In your methods add the HttpSession as an argument. Also once you are done with your attribute, clear the same from HttpSession.

So in your case, option 1 and option 2 does not fit.

Please go through this, might help you.

Upvotes: 1

Related Questions