How do I set session or global attribute using Spring MVC SimpleFormController

Discussion in 'Programming' started by reimeus, Feb 17, 2010.

  1. #1
    Hello,

    This might sound like a fairly simple question:

    I have a simple application written in Java using Spring MVC. I have a LogonController like so:


    public class LogonFormController extends SimpleFormController {

    final Logger logger = Logger.getLogger(getClass().getName());

    protected ModelAndView onSubmit(Object obj) throws Exception {
    String username = ((Credentials)obj).getUsername();
    logger.info("-> username is " + username);

    String fullName = // get full name from database
    Map<String, String> model = new HashMap<String, String>();
    model.put("username", username);
    model.put("fullName", fullName);

    return new ModelAndView(new RedirectView(getSuccessView()), "model", model);
    }
    }

    and:

    public class WelcomeController implements Controller {

    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

    // how do I get and set model here?

    return new ModelAndView("welcome");
    }

    }

    The Credentials class just contains the username & password, supplied at login. I plan to somehow read the full name from the database in the LogonController.

    I'm using a RedirectView so that the page doesnt 'stick' on the logon.htm page in the browser URL text field. As you can see I pass in the model into the WelcomeController but dont really know how to pick up this info & pass it on.

    Ideally I want the persons username and full name to be present on every jsp page. I was thinking of setting a session attribute....

    Any ideas?
    Scott
     
    reimeus, Feb 17, 2010 IP
  2. reimeus

    reimeus Peon

    Messages:
    4
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Hi,

    D'oh, the answer came to me shortly after posting. There is an overloaded onSubmit method for the Controller which contains a HTTPRequest instance. You can get a handle to the session from that and stuff whatever info you like into it. Isnt Spring great? :D

    -S
     
    reimeus, Feb 20, 2010 IP
  3. skp

    skp Peon

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Hey

    Can you please explain ur answer in code ? I am facing the same situation. Are you saying the onSubmit method is part of the welcomeController?

    Thanks
     
    skp, Mar 10, 2011 IP
  4. skp

    skp Peon

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Gotcha!! Its working now!
     
    skp, Mar 10, 2011 IP