Spring MVC - passing variables from one page to anther
Asked Answered
P

3

4

I need help. I am working on a project where I have multiple pages and multiple forms; each page has one form. I just need to be able to pass values from one jsp to another. What should I do?

I am new to Spring MVC. I am using spring 2.5.6.

Here's my design:

formPage1.jsp --> Controller1 --> formPage2a.jsp --> Controller2 needs val frm pg1 & pg2a. formPage1.jsp --> Controller1 --> formPage2b.jsp --> Controller3 needs val frm pg1 & pg2b. formPage1.jsp --> Controller1 --> formPage2c.jsp --> Controller4 needs val frm pg1 & pg2c.

As you can see above, formPage1.jsp can load either formPage2a, formPage2b or formPage2c. Based on the input provided in formPage1.jsp, it goes to the controller (which is an extension of SimpleFormController) and controller get the values entered by user = command object.

I want to be able to use these command object values in either formPage2a, formPage2b or formPage2c when they are submitted to another controller.

here's the current code:


formPage1.jsp:

<form:form method="post" commandName="gainLossRequest">
            <form:errors path="*" cssClass="error"/>
            <table>
                <tr>
                    <td>
                        <table>
                            <tr>
                                <td><h4>Choose Client</h4></td>
                                <td style="font-size: medium; font-family: Arial, bold; color: red">*</td>
                            </tr>
                        </table>
                    </td>
                    <td>
                        <form:select path="client">
                            <form:option value="none" label="Select" />
                            <form:option value="abc" label="abc" />
                            <form:option value="def" label="def" />
                            <form:option value="xyz" label="xyz" />
                        </form:select>
                    </td>
                </tr>
<tr>
                    <td colspan="2">
                        <input type="reset" value="Reset" />
                        <input type="submit" value="Next" />
                    </td>
                </tr>
            </table>
            </form:form>

Controller1.java

public class TestController extends SimpleFormController {

    /** Logger for this class and subclasses */
    protected final Log logger = LogFactory.getLog(getClass());

    public TestController() {
        logger.info("entering TestController.constructor..");
        setCommandClass(UserPreference.class);
        setCommandName("userPreference");
    }

    public ModelAndView onSubmit(HttpServletRequest request,
            HttpServletResponse response, Object command, BindException errors)
            throws ServletException {
        logger.info("entering TestController.onSubmit all..");

        UserPreference userPreference = (UserPreference) command;

        ModelAndView view = null;

        if ("abc".equals(userPreference.getClient())) {
            GainLossRequest gainLossRequest = new GainLossRequest(userPreference);
            view = new ModelAndView("redirect:/test/gainLossRequest.htm",
                    "gainLossRequest", gainLossRequest);
                } else if ("def".equals(userPreference.getClient())) {
            IncomingPositionsRequest incomingPositionsRequest = new IncomingPositionsRequest();
            view = new ModelAndView(
                    "redirect:/test/incomingPositionsRequest.htm",
                    "incomingPositionsRequest", incomingPositionsRequest);
        } else if ("xyz".equals(userPreference
                .getClient())) {
            TaxStrategyRequest taxStrategyRequest = new TaxStrategyRequest();
            view = new ModelAndView("redirect:/test/taxStrategyRequest.htm",
                    "taxStrategyRequest", taxStrategyRequest);
        }
        }
}

formPage2a.jsp

<form:form method="post" commandName="gainLossRequest">
            <form:errors path="*" cssClass="error"/>
            <table style="width: 60%">
                <tr>
                     <td>Account Number (s):</td>
                     <td style="font-size: medium; font-family: Arial, bold; color: red">*</td>
                </tr>
                <tr>
                    <td>
                        User Chosen Client: 
                    </td>
                    <td>
                        <c:out value="${gainLossRequest.client}"/>
                    </td>
                </tr>
                                <tr colspan="2">
                                        <td>
                        <input type="reset" value="Reset" />
                        <input type="submit" value="Submit" />
                    </td>
                </tr>

dispatcher servlet config

<!-- setupNew.jsp is the first jsp --> 

<bean name="/test/setupNew.htm" class="chimeraweb.web.TestController">
        <property name="sessionForm" value="true"/>
        <property name="commandName" value="userPreference"/>
        <property name="commandClass" value="chimeraweb.service.UserPreference"/>
        <property name="validator">
            <bean class="chimeraweb.service.UserPreferenceValidator"/>
        </property>
        <property name="formView" value="/test/setupNew"/>
    </bean>


<!-- gainLossRequest.jsp is the 2nd jsp where I want to display the values captured in the first jsp page -->

    <bean name="/test/gainLossRequest.htm" class="chimeraweb.web.SimpleGainLossController">
        <property name="sessionForm" value="true"/>
        <property name="commandName" value="gainLossRequest"/>
        <property name="commandClass" value="chimeraweb.service.GainLossRequest"/>
        <property name="validator">
            <bean class="chimeraweb.service.GainLossValidator"/>
        </property>
        <property name="formView" value="/test/gainLossRequest"/>
    </bean>

Please help!!

Pamplona answered 3/6, 2012 at 15:54 Comment(1)
The question is.. I am unable to pass values from the first formPage to the 2nd formPage. I want to know how to do that.Pamplona
Q
2

You have to persist the user entered information on the first page either using a hidden variable as mentioned above by JB Nizet. Or you can set the value in the model attribute that will be returned on your corresponding controllers.

The pseudo code for you.

formPage1.jsp --> Controller1 --> set the values in this form by retrieving it from the Request object --> formPage2a.jsp --> Controller2 will have val frm both pg1 & pg2a.

In this way there is no need to maintain a session attribute.

Quid answered 4/6, 2012 at 13:56 Comment(7)
Ok, Thanks. This is what I am doing inside Controller1.java. I want to know "how to set the values in the 2nd form"?? Does this code help set the values in the form?? Or is it wrong?? The command object in 2nd.jsp is GainLossRequest. I am setting the values I got from 1st.jsp to this object.. so that I can retrieve them in 2nd.jsp. But when I try to do.. <c:out value="${gainLossRequest.client}"/>, it doesn't display anything.Pamplona
------------------ Inside Controller1.java: ------------------ String client = ((UserPreference) command).getClient(); logger.info("User chosen client: " + client); GainLossRequest gainLossRequest = new GainLossRequest(userPreference); view = new ModelAndView("redirect:/test/gainLossRequest.htm", "gainLossRequest", gainLossRequest); logger.info("Value of client inside controller after assigning it to glRequest object: " + gainLossRequest.getClient());Pamplona
You need to look at your Controller1.java. You are returning different model objects based on some conditions. You need to have them persisted in those model objects. I havent used xml configurations for a while.. So use your judgement on what needs to be done.Quid
You are using a redirect: for your view, that will cause your request to lose any knowledge of the domain object. The jsp wont know what to populate your hidden input with because the instance of the object will not be available in the page.Kristynkrock
Hmm.. ok. This is very useful. Thanks. I think I am slowly getting there.. but not quite there yet. The reason I had to redirect is 'cus I want to map different URLs to different beans. Basically, based on the "client" that user chooses, I want to take him to different pages. This line has helped me achieve this -- <bean name="/test/gainLossRequest.htm" class="chimeraweb.web.SimpleGainLossController">. So, if i get rid of this redirect:prefix, then, I won't be able to load pages based on input. Or may be, that's how much I know. Any inputs?Pamplona
Ok, finally!! I think I got it. The problem is with redirect. Instead of doing I just returned the same url (/test/gainLossRequest) and it worked. It was able to display the values from request!! Thank you so much!!!!!!!!! You made my day!! I was struggling with this for 2-3 days!!Pamplona
oh, damn! not there yet. The thing is.. it's getting all values.. but taking me to the same old Controller1.java instead of Controller2.java. I need to go to Controller2.java for further processing. It's unable to go to Controller2.java 'cus it's unable to map the request URL to Controller bean.Pamplona
K
7

You could also use session attributes, either manually, such as:

public ModelAndView handleRequest(HttpServletRequest request){
      request.getSession().getAttribute("nameOfAttribute");
}

Apologies for writing this as an annotated controller, I do not recall if xml config controllers offer this feature...

There is no Spring code involved for that. The other option is to use the @SessionAttribute annotation on your controller:

@Controller 
@SessionAttributes("nameOfAttribute")
public class MyController{
//your session attribute can be accessed in controller methods using @ModelAttribute
public ModelAndView handleRequest(@ModelAttribute("nameOfAttribute")){
      session.getAttribute("nameOfAttribute");
}

Note

You will need to clear the session attribute when you are done with it:

request.getSession().setAttribute("nameOfAttribute", null);
Kristynkrock answered 4/6, 2012 at 13:23 Comment(2)
I am able to access the user entered values in 1st jsp page Thanks. I didn't completely understand. Please tell me if this assumption is wrong. step1: User enters values in 1st jsp step2: values go to controller1.java step3: i need to be able to capture the same values in 2nd jsp step4: pass on the same value to controller2.java. I am successful with step1 and step2. So, getting user entered values in controller1 is not an issue. I want to somehow pass on those values to controller2.java (step4). but i understand I can't get to step4 without going to step3. Does it make sense?Pamplona
Yes, what I am saying is you can store the object you are working on in the user's session. That way there is no need to put hidden inputs with all the data in it. Instead of passing variables to the jsp, put whatever domain object you are building into the Session object. I believe Spring 2.5 has a multistepaction controller or wizard controller you could use to accomplish this, too.Kristynkrock
Q
2

You have to persist the user entered information on the first page either using a hidden variable as mentioned above by JB Nizet. Or you can set the value in the model attribute that will be returned on your corresponding controllers.

The pseudo code for you.

formPage1.jsp --> Controller1 --> set the values in this form by retrieving it from the Request object --> formPage2a.jsp --> Controller2 will have val frm both pg1 & pg2a.

In this way there is no need to maintain a session attribute.

Quid answered 4/6, 2012 at 13:56 Comment(7)
Ok, Thanks. This is what I am doing inside Controller1.java. I want to know "how to set the values in the 2nd form"?? Does this code help set the values in the form?? Or is it wrong?? The command object in 2nd.jsp is GainLossRequest. I am setting the values I got from 1st.jsp to this object.. so that I can retrieve them in 2nd.jsp. But when I try to do.. <c:out value="${gainLossRequest.client}"/>, it doesn't display anything.Pamplona
------------------ Inside Controller1.java: ------------------ String client = ((UserPreference) command).getClient(); logger.info("User chosen client: " + client); GainLossRequest gainLossRequest = new GainLossRequest(userPreference); view = new ModelAndView("redirect:/test/gainLossRequest.htm", "gainLossRequest", gainLossRequest); logger.info("Value of client inside controller after assigning it to glRequest object: " + gainLossRequest.getClient());Pamplona
You need to look at your Controller1.java. You are returning different model objects based on some conditions. You need to have them persisted in those model objects. I havent used xml configurations for a while.. So use your judgement on what needs to be done.Quid
You are using a redirect: for your view, that will cause your request to lose any knowledge of the domain object. The jsp wont know what to populate your hidden input with because the instance of the object will not be available in the page.Kristynkrock
Hmm.. ok. This is very useful. Thanks. I think I am slowly getting there.. but not quite there yet. The reason I had to redirect is 'cus I want to map different URLs to different beans. Basically, based on the "client" that user chooses, I want to take him to different pages. This line has helped me achieve this -- <bean name="/test/gainLossRequest.htm" class="chimeraweb.web.SimpleGainLossController">. So, if i get rid of this redirect:prefix, then, I won't be able to load pages based on input. Or may be, that's how much I know. Any inputs?Pamplona
Ok, finally!! I think I got it. The problem is with redirect. Instead of doing I just returned the same url (/test/gainLossRequest) and it worked. It was able to display the values from request!! Thank you so much!!!!!!!!! You made my day!! I was struggling with this for 2-3 days!!Pamplona
oh, damn! not there yet. The thing is.. it's getting all values.. but taking me to the same old Controller1.java instead of Controller2.java. I need to go to Controller2.java for further processing. It's unable to go to Controller2.java 'cus it's unable to map the request URL to Controller bean.Pamplona
S
1

The simplest way is to use hidden fields in the second page(s) to store what the user has enetered in the first form. This way, all the fields, inclusing those from the first page, will be submitted with the second form(s).

Surprising answered 3/6, 2012 at 16:7 Comment(5)
Thanks for the quick reply. Really appreciate it. But I don't know how to pass variables as hidden. Do you know the syntax?Pamplona
static.springsource.org/spring/docs/2.0.x/reference/…Surprising
I tried. It didn't work. I changed the code like this in 2nd jsp. <tr> <td> Client: </td> <td> <form:hidden path="client" /> </td> </tr>Pamplona
It's impossible to help you more if the only symptom is "it doesn't work". Be more precise. Tell us what it does and what it should do. Show us your code. Give us exception stack traces. "It doesn't work" doesn't mean anything. When you go to a doctor, you don't just say: "I'm sick". You tell him that your head hurts, that you vomit, etc.Surprising
I am sorry. I thought I was clear enough. I pasted all the code with regards to those two jsp pages and the controller inbetween. The problem is, user enters a value in page1 and i want to capture that in page2. I am not able to do that. I added the DispatcherServlet config file that was missing. Do you need more info?Pamplona

© 2022 - 2024 — McMap. All rights reserved.