Using $ request.session.setAttribute to save a dropdown menu

I am trying to save a dropdown parameter that controls the number of items displayed in the registry. How should I do it? The drop-down list uses onChange to sort the registry results.

+4
source share
1 answer

I do not do Velocity, so here is the JSP / Servlet-target answer. I suppose you also use Servlets, since Velocity is actually a template engine and does nothing to manage requests / preprocess / postprocess.

So, do you want to save certain data in subsequent queries? There are two ways to achieve this.

  • Store the value for the subsequent query in a hidden input element. For instance.

    <form action="servlet" method="post"> <select name="itemcount" onchange="submit()"> <option>1</option><option>2</option><option>3</option> </select> </form> 

    and then in the form of the following request:

     <form action="servlet" method="post"> <select name="sortfield" onchange="submit()"> <option>col1</option><option>col2</option><option>col3</option> </select> <input type="hidden" name="itemcount" value="${param.itemcount}"> </form> 

    ${param.itemcount} basically returns request.getParameter("itemcount") . When stored in a hidden input element, you see nothing, but request.getParameter("itemcount") will also be available in the next request.

  • Save the value in the session. For instance. inside servlet:

     Integer itemcount = Integer.valueOf(request.getParameter("itemcount")); request.getSession().setAttribute("itemcount", itemcount); 

    so that you can access it in any servlet running in the same session as if necessary:

     Integer itemcount = (Integer) request.getSession().getAttribute("itemcount"); 

    But this has a big caveat: it can cause "wtf?" when the user opens several windows in one session and selects another element in both windows. The last selected value in window A will be reflected in window B!

It seems obvious to me that you should store data with query coverage in the query area, so it is preferable 1. Use a session only for data with session coverage.

+1
source

Source: https://habr.com/ru/post/1299063/


All Articles