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.
Related
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));
This is my Code that retrieves information from database and displays it in Table with an addition button that will used to submit(add to fav) to another new table with that row values and id of the user Below code displaying all records correctly with in table and every row is wrapped inside a form with button so when i click on a Particular row button then Values of that row only should be passed to target page,But for each and every row only the first record values are passing...
<%pst = con.prepareStatement("select * from reg_faculty");
res = pst.executeQuery();
while(res.next()) {
String uname = res.getString(1);
String id = res.getString(2);
String branch = res.getString(5);
String subject = res.getString(4);
%>
<tr><td align="center"><b><%=uname%></b></td><td align="center"><b><%=branch%></b></td>
<td align="center"><b><%=subject%></b></td>
<input type="hidden" name="fac_id" value="<%=id%>">
<input type="hidden" name="std_id" value="<%=ht%>">
<input type="hidden" name="fac_name" value="<%=uname%>">
<td align="center"><img src="viewimagef.jsp?id=<%=id%>&type=<%="faculty"%> " alt="" width="100" height="60" /></td>
<td align="center"><input type="submit" value="Add"/></td>
</tr>
<%
}
%>
Target page where the selected row values should pass to database but for any row selected the first record values are passing
String std_id1=request.getParameter("std_id");
String fac_id2=request.getParameter("fac_id");
String name=request.getParameter("fac_name");
try{
pst=con.prepareStatement("select * from fav_faculty where std_id=? AND fac_id=?");
pst.setString(1, std_id1);
pst.setString(2, fac_id2);
res=pst.executeQuery();
boolean exists = false;
if(res.next()){
out.println("Faculty Already exist in your List");
out.println("Faculty: "+fac_id2+" Student Id: "+std_id1+" Name: "+name);
}else{
pst=con.prepareStatement("insert into fav_faculty values(?,?)");
pst.setString(1, std_id1);
pst.setString(2,fac_id2);
int j=pst.executeUpdate();
if(j>0){
out.println("You successfully added "+name+" to your Faculty List");
}
}
}catch (Exception e) {
out.println("Unable To Add");
}
the problem is in the submit buttons you are using, a submit button belongs to the whole form, a working scenario would be changing the value of the submit button to the faculty id but keeping the same name for all the submit buttons.
another and probably a better solution would be adding a checkbox instead of a submit buttons.
<tr><td align="center"><b><%=uname%></b></td><td align="center"><b><%=branch%></b></td>
<td align="center"><b><%=subject%></b></td>
<input type="hidden" name="fac_id" value="<%=id%>">
<input type="hidden" name="std_id" value="<%=ht%>">
<input type="hidden" name="fac_name" value="<%=uname%>">
<td align="center"><img src="viewimagef.jsp?id=<%=id%>&type=<%="faculty"%> " alt="" width="100" height="60" /></td>
<td align="center"><input type="ckeckbox" name="fac_id" value="<%=id%>">
</tr>
%><%-- end of the while loop --%>
<input type="submit" value="add all">
and in the target page
String allSelectedFacultyIds[]= request.getParameterValues("fac_id");
for (int i=0;i<allSelectedFacultyIds.length;i++)
{
pst=con.prepareStatement("select * from reg_faculty where id="+allSelectedFacultyIds[i]);
//now you have the name, id, ... so the rest of your code should apply with minor changes
}
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.
I have used setTimeout method to do this and passed a variable which contains time but my settimeout method takes only the initialized value of that variable and not the value that is fetched from database.
Here is my code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Givetest</title>
<script type = "text/javascript">
function submitForm() {
document.forms[0].submit();
}
</script>
<script language="JavaScript" src="http://scripts.hashemian.com/js/countdown.js"></script>
</head>
<%
String ts=request.getParameter("testname");
session.setAttribute("tname", ts);
Connection con=null;
Statement s1=null;
Statement s=null;
ResultSet r1=null;
ResultSet r=null;
int t=120000;
String time=null;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:online_testing");
s=con.createStatement();
s1=con.createStatement();
r=s.executeQuery("select * from "+ts+"");
r1=s1.executeQuery("select duration from tests where testname="+ts+"");
if(r1.next())
{
time=r1.getString("duration");
t=Integer.parseInt(time)*60000;
logger.info(time);
}
else {
logger.info("No row found in db for test " + ts);
System.out.println("No row found in db for test " + ts);
out.println("<br>!! <b>No row found in db </b>for test " + ts + "<br><br><br>");
}
r1.close();
}
catch(Exception e1)
{
response.setContentType("text/html");
out.println(e1.toString());
}
%>
<body onload="setTimeout('submitForm()',<%=t%>)">
<div class="header"></div>
<div class="view" style="color: #050505">
<form action="Givetest" method="post">
<h1 align="center" style="color: #050505"><%=ts%></h1>
<%
int i=1;
while(r.next()){
String a = r.getString("question");
String b = r.getString("option1");
String c = r.getString("option2");
String d = r.getString("option3");
String e = r.getString("option4");
%>
Question <%=i%>:- <label> <%=a%></label><br>
<input type="radio" name="r<%=i%>" value="<%=b%>" checked><label><%=b%></label><br>
<input type="radio" name="r<%=i%>" value="<%=c%>"><label><%=c%></label><br>
<input type="radio" name="r<%=i%>" value="<%=d%>"><label><%=d%></label><br>
<input type="radio" name="r<%=i%>" value="<%=e%>"><label><%=e%></label><br>
<br>
<input type="hidden" name="h" value="<%=ts%>">
<%
i++;
}
r.close();
s.close();
con.close();
%>
<input type="submit" class="button">
</form>
</div>
<div class="copyright" align="center"> © SAUMYARAJ ZALA</div>
</body>
</html>
The mistake is in the where clause which should be like:-
r1=s1.executeQuery("select duration from tests where testname="+ts+"");
Moreover this code should be executed in servlets before it is passed to jsp
<body onload="setTimeout('submitForm()',<%=t%>)">
You are giving the value only once. DO you mean it gets value
int t=120000;
and not what is in data base? If so are you sure no error is being thrown?
By the way this is not the best way to write a web app - all in jsp - though it works, better is to make servlets and POJOs/ helper .java files for data base etc. Make sure your tomcat/ app server's temp folder are cleaned every time you restart - to make sure its taking latest jsp.
In jsp can have a text like 'Version 001' and increase that manually so your sure correct code version is running.
Use loggers or system.out.println if you do not have logger
r1=s1.executeQuery("select duration from tests where testname="+ts+"");
//if should be enough as you will only have 0 or 1 row per test?
if(r1.next())
{
time=r1.getString("duration");
t=Integer.parseInt(time)*60000;
} else{
logger.warn("No row found in db for test " + ts);
//okay for debug
out.println("<br>!! <b>No row found in db </b>for test " + ts + "<br><br><br>");
}
r1.close();
}
catch(Exception e1)
{
response.setContentType("text/html");
out.println("<br><br> <b> ERROR</b>" + e1.toString());
}
sql
testname="+ts+""
is very bad should use a prepared statement or you are asking for a SQL injection attack. look at owasp https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
I have a simple form
form action="email.jsp" method="post"
<label for="firstname">Your Name: </label>
input type="text" id="name"<br/>
<label for="email">Your Email: </label>
input type="text" id="address"<br/>
<label for="message">Message: </label>
textarea size="30" rows="4" class="expand" id="comments"</textarea<br/>
input type="submit" value="Send" input type="reset"
/form
and am posting to a email.jsp page running in tomcat 5.5, working for another website i use that is in flash
this email.jsp is coming up with null values every time i post data to it - code below
can anyone see what i'm doing wrong?
<%# page import="sun.net.smtp.SmtpClient, java.io.*, javax.servlet.http.HttpServletResponse, javax.servlet.jsp.PageContext" %>
<%
String name = request.getParameter("name");
out.print(name);
String address = request.getParameter("address");
String comments = request.getParameter("comments");
String from="test#there.com.au";
String to="test#where.com";
try{
SmtpClient client = new SmtpClient("localhost");
client.from(from);
client.to(to);
PrintStream message = client.startMessage();
message.println("From: " + from);
message.println("To: " + to);
message.println();
message.println("Enquiry :-) from " + name + " at " + address);
message.println();
message.println("Details: "+ comments);
client.closeServer();
}
catch (IOException e){
System.out.println("ERROR SENDING EMAIL:"+e);
}
out.print("Email Sent Correctly");
%>
Your HTML is a bit garbled, but it looks like you're not specifying the "name" attribute for your inputs. The "id" attribute is good for referencing your field from a <label> or for accessing your inputs from Javascript, but the browser will not use it in the POST request.
The solution is simple, add the "name" attribute to your input elements, like this:
<input type="text" id="name" name="name" />