To prevent Null value entry in JSP page - java

I've been working on a simple project. Getting data from JSP using text box, then using the Java in backend to save it in the database. I've defined the fields as NOT NULL in database, but the problem is when I click on submit, the data is saved in database as "", I mean it doesnt take it as NULL and it stored it as BLANK or "". Is there any way to prevent the submit action even if any one field is NULL or without entry? I know I can check it in backend Java, but I've to check every value as NOT NULL if I do by this way. Stopping the Submit action if anyone of the field is NULL is a decent choice.

Try using required="true" for the fields you do not want to allow to be empty. For example:
<h:inputText id="user" styleClass="txtinput" value="#{login.user}" required="true"/>

You cannot control the value being sent unless you use the framework(e.g struts,spring,jsf) specific tags and it has inbuilt validation on the client side.
There is nothing called as null on the form.Everything goes as String.
You have to write client side validations for Blank or "" and check for this value before submission.
If the value is Blank or "" then do not submit.

Related

expiring the session of user if new tab is opened in browser using struts2 interceptors

My application is in struts2.
I have requirement that I am storing my application details in session. I cannot remove those attributes from session. After I log-in I have to choose an object to work on. Now I open a new tab and choose another object for working. Due to which my first object values are over written. Hence if in my first tab I do some work wrong information is updated for that action.
This is how I am planning to solve the issue.
I am trying to set a value in setter method in interceptor class but I cannot access that value in my index.jsp.
This interceptor is called on all the actions and index.jsp is also included in every jsp.
I will maintain a hashtable which will store the userid and a random string of 40 characters. This id will be unique and I will update the userid after comparing the value present in jsp to value stored against the value stored in hastable.
If I find that value matches then I will generate another value and store in jsp and hastable. If value does not matches I will destroy the session.
Kindly advice how can I proceed or is there any other work around to achieve the same.
code
Interceptor class
String strFrom = (String)aContext.get(ServletActionContext.ACTION_NAME);
HttpServletRequest httpReq = (HttpServletRequest)aContext.get(ServletActionContext.HTTP_REQUEST);
HttpSession session = httpReq.getSession();
String sessionValue = (String)httpReq.getSession().getAttribute("sessionValue");
String test = httpReq.getParameter("sessionValue");
if(strFrom.equals("ValidateUser")){
// Do nothing
}else if(sessionValue == null && strFrom.equals("HomePage")){
session.setAttribute("sessionValue", getRandomString(20));
}else if (sessionValue.equals(session.getAttribute("sessionValue"))){
session.setAttribute("sessionValue", getRandomString(20));
}else{
httpReq.setAttribute("message","Session Expired. Please Login Again");
return "loginAgain";
}
index.jsp
<body>
<s:hidden id="hidBidType" value="%{#session.tenderBidType}"/>
<s:property value="%{#session.sessionValue}"/>
<s:hidden name="sessionValue" id="sessionValue" value="%{#session.sessionValue}"/>
</body>
login.jsp
<form name="loginPage" method="post">
<s:hidden name="sessionValue" id="sessionValue" value="1"/>
</form>
For your randomly generated value of 40 characters, why not use timestamp?
Well, I don't see much advantages of your aproach (but I could be wrong, of course). You still can register a SessionListener and check if the user has session, cant't you? So, do you realy need to do all this kind of stuff is up to you, but I wouldn't do it that way - Interceptor for all pages, store value in the page, check if is the same... Just register one SessionListener and put your user ID or some otrher user's unique value in session, compare and destroy session (or whatelse you need).
Hope this helps.
EDITED
I'm working on a web application with a similar requirements. What we do (and I'm sure is not the best choice) is after logging open new window without navigation bar and close the loggin window. Then we capture all the events on the window and disable many features like ctrl+tab, right click etc. In this application the user is not allowed to open more than one window. I repeat - this is probably not the best choice. Just an idea.

How to maintain the contents in the text field after redircting to same page jsp.

Hi I have jsp page That is having some text fields,I will fill that text fields and I will submit that form to server side.If any error comes in the server side I will redirect to the same page with error message Now I want that text field to remain as it is but in my case it is clearing.How to make the text field as same.
The two options available to you are:
Don't reload the page. Instead submit the data via AJAX or validate it by javascript. That way you don't ever have to touch the data in the form. Make sure your javascript highlights the fields that have errors in some way.
The endpoint that you're POSTing your data to needs to be able to recognise that the data is invalid and include that data when returning the user to the same page. I'm not familiar with jsp, but generally you'd do that by including variables in your template for your form that could contain the data, and passing empty strings on the first load of the page. If the page is then shown to the user again after a failed form validation, pass back the POST data that you received in your form request.
There are two option, you can dispatch the request/response to the same page instead of redirect, but you need to add an attribute and recover it in the JSP, or you can add the attribute in the session , recover the value to de text field and remove it using (if you are using JSTL)

issues passing dropdown value to java

I have a bunch of select tags in my page where some of them allows the user to use the dropdown and some of them will be disabled at a given time. so I have a select tag in my jsp such as:
<html:select name="myobject" property="myfield" disabled="$(isDisabled ? 'disabled' : '')"/>
I wanted to set as readonly a select tag on my jsp but apparently is not possible so I had to put disable. Since disabled values are not passed back to the application when a user submits the action I created a hidden object of it to pass it as it's suggested everywhere to work around that...
<html:hidden name="myobject" property="myfield" indexed="true"/>
The problem is.. when the form is submited I don't get the new dropdown value selected by the user, I debug into my java code and what I receive is the value that was originally sent to the page instead of what the user picked. It works if I removed the hidden field but if I do so then the disabled selections won't displayed when refreshed cause disabled fields don't pass back the values and i'll receive null at my end... how do I fix this problem?
Thanks,
There may be a duplicate of name or property of the html hidden component.

dynamically update textbox value from database when combobox value is changed

Here is the situation. I have a drop down menu. The option sin this drop down menu are being populated by fetching some values from the database. To do this following is what i have done.. :-
<select name="product_list" onchange="selectProduct(this.value)">
<option value="none">Select one</option>
<%
List<String> options = new ArrayList<String>();
DynamicCombo comboBox = new DynamicCombo();
options = comboBox.generateComboBox();
Collections.sort(options);
int tempVar = 0;
while (tempVar < options.size()) {
out.print("<option value=\"");
out.print(options.get(tempVar));
out.print("\">");
out.print(options.get(tempVar));
out.print("</option>");
tempVar++;
}
%>
</select>
DynamicCombo is a class that has a method called 'generateComboBox()'. This method simply returns an array list containing all the values that are fetched from the database, which is what i need to show in my drop down box in the front end (jsp page). On my jsp page i simply iterate through this list and print it as options appropriately.
This works absolutely fine.
Now i have another text box on my form, say 'textbox1'. Now the requirement is that this text box value should be updated depending on what the user has selected from the above drop down box.
So for example if the user selects 'prod1'(which is a primary key in the backend database table) option from the drop down box, then the corresponding value ( the product name) should be fetched from the database table and should be updated in the textbox named 'textbox1'.
The other thing is this entire thing is contained in a form which is supposed to be finally submitted to the servlet for further processing.
So how can i achieve this.
i figured out the solution to my own problem. It might not be the most elegant way of doing it, but it does the job pretty well.
So as per my requirement, what i exactly wanted to do was.... insert a value (that will be fetched from the database) into a text box on my form depending on what the user chooses from the drop down box that is already present on my form.
To achieve this, i went about and thought if some how i could nest a form withing my main form, it'd solve my issue. But i discovered that nesting of forms is not allowed. So the next option i thought of was to some how submit the same form without the user clicking on the submit button and also handle it appropriately as an 'incomplete' submit (in the sense that the form is still to be submitted manually by the user by clicking on the submit button) on the server.
So i simply made use of the 'onChange' event of a drop down box. I created an additional hidden field on my form.I wrote a simple javascript function that would simply set the value of the hidden field to the string-"partial Submit" and would submit my main form (say named 'form1') as :-
document.getElementById("hidden_id").setAttribute("value","partial submit");
form1.submit;
The function that does the above will be called whenever (and everytime) the onchange event of the drop down box gets fired.
When the user finally clicks on the submit button on the form to submit the finally completed form, then another javascript function is called that simply sets the value of the hidden field on the form to the string, "final submit" and would submit the form as :-
document.getElementById("hidden_id").setAttribute("value","final submit");
form1.submit;
Now on my server, i checked for the value of this hidden field as :-
if(request.getParameter("hidden_id").equals("partial Submit"))
{
// make a database connection, pass the value user selected from the drop down box
// to a prepared statement that does the query for getting the 'productName' from
// the database, collect the returned string in a variable and set a
// request attribute with this returned value. This value can simply be used in the
// jsp to fill in the value part of the textbox1.
}
else
{
if(request.getParameter("hidden_id").equals("final Submit"))
{
// do the rest of the final processing that needs to be done when user finally
// submits the completed form.
}
else
{
// throw an exception to take care of the possibility that the user might send
// in a 3rd value as a value for the hidden field.
}
}
Since you havent provided the code for selectProduct(this.value) , i presume that it submits the jsp page as when you change the value in the drop down.
If that the case in the servelt, set the value that you want to show in jsp in request object
request.setAttribute("valuetodisplay" ,valuetodisplay);
and now in jsp
<input type="text" value ='<%= request.getAttribute("valuetodisplay")%>' />

Sending info from Servlet to JSP

What I want to do:
I have a form with a lot of fields(nick, email, name, surname, etc.) but the user has to fill Nick and Email first in order to be able to fill the other fields(this is because we want to check that the nick and mail aren't in use by another client before he can introduce the rest of his information(name, surname, etc.)).
So, the user introduces Nick and Email and then he must press a button named "Validate", if the values are available(successful validation) then the rest of the fields are enabled and the user can continue filling the form, otherwise the fields stay disabled and an error is showed to the user.
The form will be located in a JSP, it will be submitted to a Servlet, once in the servlet I must validate the information that is in the form(i have a .JAR file included in this servlet, the validation consists in calling a function from that library, the function returns a boolean) and then I must return back to the same JSP the boolean that will represent the result of the validate function.
Now in the JSP I must enable(or not, depending on the value of the boolean) the rest of the TextFields.
I'm not sure if this is right but i was trying to submit with the button and at the same time run a javascript(onclick) that will use this boolean value that the servlet sends back to the JSP after making the validation. The javascript consists on an IF sentence that evaluates the boolean and if it's true then it enables all the fields on the JSP.
Problems so far:
I was able to send the Nick and Email from the JSP to the Servlet and to make the validation of the values, now i have the boolean but i have no idea on how to send it from the Servlet to the same JSP and use it in the onclick event of the same button I used to submit the info. I don't even know if it's possible to do this...
I'd be grateful if someone could give me a hand with this, i'm newbie in Java programming so i would appreciate simple explanations if possible.
Also, if there is a better way of doing what i want please share it, and if there are any doubts ask and i will try to explain it better.
There is no need for JavaScript at all.
In your servlet you can store the validation result into the request context:
req.setAttribute('checkResult', checkResult);
where req is of type HttpServletRequest and checkResult is a Boolean.
Then you can forward to your JSP:
RequestDispatcher dispatcher = req.getRequestDispatcher("/your.jsp");
dispatcher.forward(req, resp);
In your JSP you can set your form elements as read only depending on the attribute checkResult which you have put into the request context:
<textarea name="text" cols="50" rows="10"
<%= request.getAttribute("checkResult") != null && request.getAttribute("checkResult") ? "" : "readonly" %>
>...</textarea>
So if the check is not valid then the <textarea> element will contain the readonly attribute. Otherwise readonly is not present.
As Roy mentioned AJAX is best suited for your problem. You can use DWR! , it makes normal java classes available as AJAX services, just call the method on them and get the result. So easy.
I think AJAX is more suitable for your application, which will not require to submit the whole form and you can send back the validation flag as plain responseText or well-formatted responseXML. Also you can use a lot of good javascript library such as jQuery that helps you send an AJAX request quickly and simply.

Categories