Error : null value being entered in table through jsp code - java

My code snippets are as below :
ShopRegister2.jsp :
<%
session = request.getSession();
session.setAttribute("s_id", s_id);
out.println("Your id is : "+s_id);
%>
<br>
Please note it for further use.!<br>
<form name="register" method="post" onsubmit=" return reg_form()" action="ShopRegister3.jsp"><br>
Enter your name : <input type="text" name="s_name" id="s_name"><br>
Enter your Location : <input type="text" name="s_location" id="s_location"><br>
Enter your password : <input type="password" name="s_password" id="s_password"> <br>
Confirm Password : <input type="password" name="c_s_password" id="c_s_password"><br>
<input type="submit" value="Submit"><br>
</form><br>
ShopRegister3.jsp :
String s_name=null, s_password=null, s_location=null;
int s_id = 0;
session.setAttribute("s_name", s_name);
session.setAttribute("s_password", s_password);
session.setAttribute("s_location", s_location);
String s_id_string=(String)request.getParameter("s_id");
s_id = session.getAttribute("s_id") != null ? (Integer) session.getAttribute("s_id") : 0 ;
s_name=(String)session.getAttribute("s_name");
s_password=(String)session.getAttribute("s_password");
s_location=(String)session.getAttribute("s_location");
//entering values into Shop table
PreparedStatement s_insert = con.prepareStatement("insert into ShopSystem.Shop values(?,?,?,?)");
s_insert.setInt(1, s_id);
s_insert.setString(2, s_password);
s_insert.setString(3, s_location);
s_insert.setString(4, s_name);
int c = s_insert.executeUpdate();
//checking whether the value was inserted successfully
if(c>0)
{ %>
S_ID = <%= s_id %> has been registered successfully.<br>
<% response.sendRedirect("ShopMenu3.jsp");
} %>
In the above code the server is directing to ShopMenu3.jsp after running ShopRegister3.jsp
Yet in my database, null values are being entered for the attributes : name, password and location.
I have tried many things..., where exactly seems to be the error?

Your session variables are always set to null;
Use:
s_name=(String)request.getParameter("s_name");
s_password=(String)request.getParameter("s_password");
s_location=(String)request.getParameter("s_location");
To get the values before setting them in the session

Maybe that is the problem?
String s_name=null, s_password=null, s_location=null;
And then you set session to this null values.

You have to first request that parameter before setSession statement;
so in ShopRegister3.jsp, after s_name initialization to `null´.
Request that parameter like:
s_name = request.getParameter("s_name");
Now you can setSession for this variable; it will not return null for s_name variable now.

Related

my servlet accepting the empty input fields through html form

i'm taking input values through html form and using the servlet to inserting them into the database , but when i don't put any field in the html form it is also accepting the that input . Although i've put the restrictions in my html code for the input fields .
When i tried to renter the empty fields , its shows the below error
ERROR
Duplicate entry '' for key 'users.PRIMARY
it means its accepting the user name as a empty string .
here it is my html form
<form action="userreg" method="post">
Username : <input type="text" name="username" pattern=".{3,}" title ="must contains more then 3 letters"><br/><br/>
Password : <input type="password" name="password" placeholder="password must be 8 char long one upper, lower case letter must" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Must have 8 chars one lowercase , uppercase"><br/><br/>
FirstName: <input type="text" pattern=".{3,}" title="this field cant be empty" name="firstname"><br/><br/>
Last Name: <input type="text" pattern=".{3,}" title="this field cant be empty" name="lastname"><br/><br/>
Address : <input type="text" pattern=".{3,}" name="address"><br/><br/>
Phone No : <input type="text" pattern=".{3,}" name="phone"><br/><br/>
Email Id : <input type="text" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,}$" name="mailid" placeholder="xyz#gmail.com" title="please enter valid mail"><br/><br/>
<input type="submit" value=" I AGREE FOR ALL TERMS & CONDITIONS ! REGISTER ME ">
</form>
here is my userRegistration servlet class
try {
Connection con = DBConnection.getCon();
PreparedStatement ps = con
.prepareStatement("insert into " + IUserContants.TABLE_USERS + " values(?,?,?,?,?,?,?,?)");
ps.setString(1, uName);
ps.setString(2, pWord);
ps.setString(3, fName);
ps.setString(4, lName);
ps.setString(5, addr);
ps.setString(6, phNo);
ps.setString(7, mailId);
ps.setInt(8, 2);
int k = ps.executeUpdate();
if (k==1) {
RequestDispatcher rd = req.getRequestDispatcher("Sample.html");
rd.include(req, res);
pw.println("<h3 class='tab'>User Registered Successfully</h3>");
} else {
RequestDispatcher rd = req.getRequestDispatcher("Sample.html");
pw.println("<h3 class='tab'>Registration failed !, please enter valid details</h3>");
rd.include(req, res);
pw.println("Sorry for interruption! Register again");
}
} catch (Exception e) {
e.printStackTrace();
}
That is the expected behavior. You may use HTML input elements attributes like „required“ and some frontend libraries to assist/enforce the presence of values, but in the end all validation needs to be done in the backend.
Because aside using the browser‘s form submit function, one can still send a malicious HTTP request using cURL or SoapUI, bypassing all frontend validations.

Jsp:java.lang.NumberFormatException: null

Home.jsp Post aid to Edit.jsp
<input type="button" value="修改" onclick="location.href='Edit.jsp?aid=<%=art.getAsId()%>'"/>
Edit.jsp Get aid.
String aid = request.getParameter("aid");
out.print(aid);
if (aid == null)
response.sendRedirect("Home.jsp");
else {
IAsset ad=new AssetDao();
AssetName art=ad.getInfo(Integer.parseInt(aid));
}
EditControl.jsp
but in this page, it always tell me aid =null.
request.setCharacterEncoding("utf-8");
AssetName art= new AssetName();
art.setAsId(Integer.parseInt(request.getParameter("aid")));
art.setUID(request.getParameter("UID"));
art.setAsnu(request.getParameter("asnu"));
art.setAsnm(request.getParameter("asnm"));
art.setAste(request.getParameter("aste"));
art.setSpec(request.getParameter("spec"));
And Report
java.lang.NumberFormatException: null
<input type="button" value="修改" onclick="location.href='Edit.jsp?aid=<%=art.getAsId()%>'"/>
In this line you missed to give name of the input field
so you need to change it like this
<input type="button" name="aid" value="修改" onclick="location.href='Edit.jsp?aid=<%=art.getAsId()%>'"/>
and change parsing code like this
AssetName art=ad.getInfo(Integer.valueOf(aid));

How to set value to NULL in my dropdown list?

I have a dropdown list of users that I can assign to a WorkOrder. Where User to WorkOrder is a OneToMany relationship. The problem is how to assign a NULL value to a user Id ? If I don't set it to NULL it works fine and I can assign any name from the list.
If I use this code and pick NULL <form:option value="${null}" label="null" /> in my jsp i get an error:
Failed to convert property value of type java.lang.String to required type int for property user.id; nested exception is java.lang.NumberFormatException: For input string: ""
Here's my WorkorderDAOImpl
#Override
public void saveWorkOrder(WorkOrder theWorkOrder) {
// get the current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
User user = theWorkOrder.getUser();
System.out.println("workorder: " + theWorkOrder);
System.out.println("user: " + user);
//save/update the work order
currentSession.saveOrUpdate(theWorkOrder);
}
My workorder-form.jsp I omitted some of the labels
<form:errors path="workorder.*"/>
<form:errors path="user.*"/>
<form:form action="saveWorkOrder" modelAttribute="workorder" method="POST">
<!-- need to assotiate the data with workorder id -->
<form:hidden path="id"/>
<table>
<tbody>
<tr>
<td><label>User name:</label></td>
<td><form:input path="user.userName"/></td>
</tr>
<tr>
<td><label>User:</label></td>
<td><form:select path="user.id">
<form:option value="${null}" label="null" />
<form:options items="${users}"
itemLabel="userName" itemValue="id"
/>
</form:select>
Turns out int in Java cannot be NULL so changed my id from int to Integer. Integer can be null.
I also added an if statement to my WorkOrderDAOImpl.java to check if user.id was set to null.
Here's my updated code.
#Override
public void saveWorkOrder(WorkOrder theWorkOrder) {
System.out.println(" \n Printing from WorkOrder : \n");
// get the current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
User user = theWorkOrder.getUser();
if (user.getId() == null) {
theWorkOrder.setUser(null);
}
//save/update the work order
currentSession.saveOrUpdate(theWorkOrder);
}

Disable dropdown list without any event

I have one jsp and want to disable dropdown list using scriplet without any onclick method or event in dropdown menu
<%
boolean something= true;
if(something){
// here I want to get plc1 using id and want to disable it if it is true
}else{
//do some thing
}
%>
my dropdown html code is here
<td bgcolor='' align="center" ><select id = "plc1" name="place1" onclick="this.parentNode.style.backgroundColor = this.value">
<option value='red'>Park here</option>
<option value='green'>Cancel</option>
</select></td>
how to do it? any hint please?
just use disabled attribute: <select id="plc1" disabled>
<%
String state = "";
if(something){
state = "disabled";
}
%>
<select id="plc1" <%= state %>>
<%
boolean something=false;
String state = "";
if(something){
state = "disabled";
// here I want to get plc1 using id and want to disable it if it is ture
}else{
state = "enable";
}
%>
Html
<select <%= state %> id = "plc1" >
Now its working Thanks

Set a checkbox in Javascript dynamically

Can someone please tell me how to set a checkbox dynamically in Javascript?
function displayResults(html){
var v = html.split(",");
document.getElementById('fsystemName').value = v[0];
if (v[1] == "true"){
document.getElementById('fUpdateActiveFlag').checked = true;
}
}
So I am passing some values from my controller separated by commas. For the checkbox, when the value is true I want it to tick the box.
EDIT:
When a value is changed from a dropdown box it calls this displayResults method as its return statement:
$('#uINewsSystemList').change(function() {
$.get("/live-application/SystemById", {systemid: $("#systemList").val()}, displayResults, "html");
I want it to update some other values such as textboxes and checkboxes. I can get the fsystemName to populate with the appropriate value but the fUpdateActiveFlag always stays unchecked.
In your question, you posted a javascript example, not JSP.
In JSP you can use a for loop to write the checkbox like this:
<% for (Element element : elementList) { %>
<input type="checkbox" name="<%=element.getName() %>" value="<%=element.getValue() %>" <%=element.getChecked() ? "checked" : "" %> />
<% } %>
Will result in:
<input type="checkbox" name="option1" value="Milk"> Milk<br>
<input type="checkbox" name="option2" value="Butter" checked> Butter<br>
<input type="checkbox" name="option3" value="Cheese"> Cheese<br>

Categories

Resources