How to use an HTML5 data attribute to get session attribute - java

I'm new to the front end side of Java EE and HTML5. I have read that you could use the data attribute to read through the DOM. How would you properly use this to get a session attribute already set by java. Compared to the other methods such as using a hidden input.
<input id="sid" type="hidden" name="series" value="${sessionScope.series} />
var sid = document.getElementById("sid"), series;

Use something like this:
<div id="div1" data-special-value="${sessionScope.series}"></div>
And get the attribute value like:
document.getElementById("div1").getAttribute("data-special-value")
Or even ( http://caniuse.com/dataset ):
document.getElementById("div1").dataset("special-value")
Or with jQuery:
$("#div1").attr("data-special-value")
// or
$("#div1").data("special-value")
Although I'm not sure storing a session value on an element is right. It's definitely not wrong, I'm just wondering what you'd need/use it for with sessions. Sessions appear once.
The data-* attributes are more useful with storing related data to something. For example, if you loop through a bunch of database records and print their columns, but want to also store the row's database id once, you'd use:
<c:forEach items="${rows}" var="row">
<tr data-row-id="${row.id}">
<td>${row.name}</td>
<td>${row.description}</td>
</tr>
</c:forEach>
Then if you want to get the original row.id value, it's stored in one place an encompasses everything it pertains to (the columns). This is usually how/where I use data-* attributes. Of course, there are many ideas/uses for this.

Related

javascript document.forms[0] and document.<formname> have different elements

I am trying to implement client side validation in Struts 2. my theme is xhtml. The javascript generated is not able to validate my code. After debugging , I found that Struts is using the following notation to refer the elements.
form = document.getElementById(<form id>);
service = form.elements['service'];
the point is that service is coming as undefined.
when I checked that form.elements is null; However if I access form using document.formname i am able to see the fields in elements collection.
I am thinking document.forms[0] is returning the same object as document.getElementById(formid). What is the difference?
The form element can access fields by name, for this purpose you should get the form element. You can do it in many ways, use document.getElementById() or document.forms[], or $("#formid"). Whatever way you choose doesn't matter. Just note that a document can contain many forms, so you should reference a correct one. Getting form element by id returns an element that has an id attribute, getting it by the index in the forms property you should know the correct index. Once you get the form element you can reference input fields by name. For example
<form id="formid">
<input name="service">
</form>
<script>
var v = document.getElementById("formid")['service'];
</script>

How do I use BeanUtils.populate to populate a bean from a form which has a checkbox

I am guessing I may be missing something simple here but I have done a lot of searching and have not found the answer...
Summary
How can I use the ready made libraries which support JavaBeans to help me take a checkbox from an HTML form and use it to populate a boolean field in a JavaBean which will then be used to update a database table? If this isn't going to work what approach would be best? Ultimately I am trying to avoid writing field specific code in what is, in all other respects, generic code.
Description
I have a jsp file (addScreen.jsp) which displays a form.
I want to use the data which is entered into the form to populate a JavaBean (type Screens).
I will then use the JavaBean (via Hibernate) to update a record in a database table.
The database table (Screens) contains a column, enabledFlag which has a boolean type.
The way I have represented this in the html form is as a checkbox.
In my controller code, when I process the form I want to use the elegant and generic functionality provided to support JavaBeans.
So I am trying to use the BeanUtils.populate() method to take data from the HTML form and use it to populate the screen field of type Screens.
This approach works very well for most of the fields in screen and converts the data from the form into the right type and stores it within the screen JavaBean.
But (and here is the problem) it doesn't process the checkbox and create a true or false value to go into the Boolean field within the Screens JavaBean. In fact it always leaves that field populated with false. I'm guessing it doesn't do anything and it defaults to false.
I think I can see why this doesn't work exactly as I have done it (but feel free to correct me). The way the checkbox state is recorded in the HttpServletRequest parameters probably isn't going to reflect what BeanUtils.populate() is expecting so it can't do anything useful. But I am not sure what it is expecting so I don't know how to manipulate the input so that populate() gives the right answer (not sure if that is very clear).
So given the above, my questions are:
Is there anything fundamentally wrong with what I am trying to do - i.e. use BeanUtils or other general purpose JavaBean library to populate a JavaBean from an HTML form which includes a checkbox? If so please let me know a better way of achieving my goal.
Assuming that there isn't a fundamental problem with what I am trying to do, am I using the wrong method or approach or should I be manipulating the data in some way before calling populate() so that it interprets the checkbox correctly?
Any other tips about how to go about this?
I have tried to include some relevant code below without swamping readers with irrelevant detail, but feel free to ask to see more if it would help. All feedback welcome.
Code Snippets
Form from addScreen.jsp which includes the enabledFlag checkbox
<form id="editScreen" method="post" action='Controller.do'>
<table>
<col class='label' />
<tr>
<td>
<label>Screen Name:</label>
</td>
<td>
<input type='text' name='name'>
</td>
</tr>
<tr>
<td>
<label>Enabled?:</label>
</td>
<td>
<input type="checkbox" name="enabledFlag" value="Enabled" checked>
</td>
</tr>
<tr><td>
<input type='submit' name='addButton' value='Add'>
</td></tr>
</table>
</form>
Declaration of enabled flag within Screens JavaBean
private boolean enabledFlag;
#Column(name = "EnabledFlag", nullable = true, insertable = true, updatable = true, length = 0, precision = 0)
#Basic
public boolean isEnabledFlag() {
return enabledFlag;
}
public void setEnabledFlag(boolean enabledFlag) {
this.enabledFlag = enabledFlag;
}
Call to BeanUtils.populate()
BeanUtils.populate(data, request.getParameterMap());
data is of type Screens and request is the HttpServletRequest containing the form data.
Just a guess - the value of your flag is "Enabled", try something like "true", "on" or "1".
Or do you have mapping code that maps "Enabled" to true?
Also, there seems to be a problem when the checkbox is unchecked, as in that case, nothing is sent to the server - there seems to be a common solution in using Javascript to set a hidden field to a value "on" or "off" and considering the hidden field only, and ignoring the checkbox itself.
See here for further reference: http://books.google.de/books?id=KNjkjBDEKssC&lpg=PT107&ots=9wZRkd_Y48&pg=PT107#v=onepage&q&f=false

How to update a the contents of a list displayed on JSP using Struts2?

I'm using Struts2 to display the contents of a list of objects on a JSP.
The flow of events is as following:
GetDataAction.java -> fetches values from
the database, fills in the ArrayList
named tableList. On success, the
displayData.jsp is shown.
displayData.jsp -> uses the s:iterate tag to display the values of objects
in the tableList.
The user changes some values in the
displayData.jsp and presses on the
Update button. On the click of
Update button, the
UpdateDataAction.java is called.
Now my problem is; How do I use the same tableList in UpdateDataAction.java to get the modified values?
I tried declaring an ArrayList with the same name 'tableList' (along with getters and setters), in UpdateDataAction.java but it throws a NullPointerException.
Please suggest.
IMO the way you are updating is not a good idea.Either you should link every row to a seperate edit page or use ajax.There are many plugins available to update table values using ajax,If you need i can provide you the links
Back to your way of doing it,i guess you are doing it as follows
<s:form action="UpdateDataActionName">
<s:iterator value="tableList">
<s:textfield name="objectName.propertyName1" value="%(propertyName1)">
<s:textfield name="objectName.propertyName2" value="%(propertyName2)">
<s:textfield name="objectName.propertyName3" value="%(propertyName3)">
</s:iterator>
<s:submit value="Update"/>
</s:form>
Now declare a list in your UpdateDataAction,of type <objectNameoftableListType> i.e. the same object type which the tabeList is representing.The name of the list must be objectName.Try to Iteate and check if you are getting the right values as submitted from the jsp.

getting hidden fields value

I am working on a Struts2 application. I am setting the value of a hidden field in JSP with the purpose to access it by JavaScript.
My JSP code:
<s:iterator value="collegelist">
<tr>
<td align="center"><s:property value="collegename"/></td>
<s:hidden name="hiddenname" key="collegename" />
</tr>
</s:iterator>
My JS code:
var myForm = document.frmAction;
var text = myForm.hiddenname.value;
alert("hidden field text is:" + text);
The alerts shows a blank value.
What is the cause and how can I solve this?
Try
element = document.getElementsByName("hiddenname");
alert(element[0].value);
You generate multiple fields having the same name, since your code is inside a s:iterator tag. You should obviously have such a loop in your Javascript as well :
var hiddenFields = document.getElementsByName("hiddenname");
for (var i = 0; i < hiddenFields.length; i++) {
alert("hidden field text is::" + hiddenFields[i].value);
}
Also, verify the the value is not blank in the generated HTML, and that the hidden fields'a name is hiddenname.
I tried your code and it surely works.. problem is somewhere in your server code itself..
Look here: http://jsbin.com/ajajo4/2/edit
Make sure you have only one form with the name "frmAction" and only one hidden field with the name "hiddenname". If you have multiple, you'll get an array instead of a single value.
The root of the problem is that you are inside of an iterator. Struts updates the name for you in order to correctly hook everything up. If you pull up your page and view source, your hidden field will probably look something like this:
<input type="hidden" name="collegelist[0].hiddenname" value="thename"/>
Regardless, if you want the retrieval by name to work, do not trust the name that you supply to a struts tag. Always pull up the generated source and look at what name the field actually has.

Using request.setAttribute in a JSP page

Is it possible to use request.setAttribute on a JSP page and then on HTML Submit get the same request attribute in the Servlet?
No. Unfortunately the Request object is only available until the page finishes loading - once it's complete, you'll lose all values in it unless they've been stored somewhere.
If you want to persist attributes through requests you need to either:
Have a hidden input in your form, such as <input type="hidden" name="myhiddenvalue" value="<%= request.getParameter("value") %>" />. This will then be available in the servlet as a request parameter.
Put it in the session (see request.getSession() - in a JSP this is available as simply session)
I recommend using the Session as it's easier to manage.
The reply by Phil Sacre was correct however the session shouldn't be used just for the hell of it. You should only use this for values which really need to live for the lifetime of the session, such as a user login. It's common to see people overuse the session and run into more issues, especially when dealing with a collection or when users return to a page they previously visited only to find they have values still remaining from a previous visit. A smart program minimizes the scope of variables as much as possible, a bad one uses session too much.
You can do it using pageContext attributes, though:
In the JSP:
<form action="Enter.do">
<button type="SUBMIT" id="btnSubmit" name="btnSubmit">SUBMIT</button>
</form>
<% String s="opportunity";
pageContext.setAttribute("opp", s, PageContext.APPLICATION_SCOPE); %>
In the Servlet (linked to the "Enter.do" url-pattern):
String s=(String) request.getServletContext().getAttribute("opp");
There are other scopes besides APPLICATION_SCOPE like SESSION_SCOPE. APPLICATION_SCOPE is used for ServletContext attributes.
If you want your requests to persists try this:
example: on your JSP or servlet page
request.getSession().setAttribute("SUBFAMILY", subFam);
and on any receiving page use the below lines to retrieve your session and data:
SubFamily subFam = (SubFamily)request.getSession().getAttribute("SUBFAMILY");
Try
request.getSession().setAttribute("SUBFAMILY", subFam);
request.getSession().getAttribute("SUBFAMILY");
Correct me if wrong...I think request does persist between consecutive pages..
Think you traverse from page 1--> page 2-->page 3.
You have some value set in the request object using setAttribute from page 1, which you retrieve in page 2 using getAttribute,then if you try setting something again in same request object to retrieve it in page 3 then it fails giving you null value as "the request that created the JSP, and the request that gets generated when the JSP is submitted are completely different requests and any attributes placed on the first one will not be available on the second".
I mean something like this in page 2 fails:
Where as the same thing has worked in case of page 1 like:
So I think I would need to proceed with either of the two options suggested by Phill.
i think phil is right request option is available till the page load. so if we want to sent value to another page we want to set the in the hidden tag or in side the session if you just need the value only on another page and not more than that then hidden tags are best option if you need that value on more than one page at that time session is the better option than hidden tags.

Categories

Resources