getting Null value from on Servlet from request.getParameter() from JSP - java

I am sending text values from jsp to servlet but in servlet request.getParameter() gives me null values. Below I am mentioning my JSP, Servlet and web.xml
REGISTER.JSP
<form id="contactform" action="servlet/SaveInfo" method="post">
<p class="contact"><label for="email">Email</label></p>
<input id="email" name="email" placeholder="example#domain.com" required="" tabindex="1" type="email">
<p class="contact"><label for="username">User Name</label></p>
<input id="username" name="username" placeholder="username" required="" tabindex="2" type="text">
<p class="contact"><label for="password">Password</label></p>
<input type="password" id="password" name="password" required="" tabindex="3">
<p class="contact"><label for="repassword">Confirm Password</label></p>
<input type="password" id="repassword" name="repassword" required="">
<p class="contact"><label for="phone">Mobile Phone</label></p>
<input id="phone" name="phone" placeholder="phone number" required="" tabindex="4" type="text"> <br>
<p class="contact"><label for="name">Organization Name</label></p>
<input id="Orgname" name="name" placeholder="Organization name" required="" tabindex="5" type="text">
<p class="contact"><label for="Address">Address</label></p>
<input id="address" name="name" placeholder="Street,Area,city" required="" tabindex="6" type="text"> <br>
<!-- <select class="select-style" name="BirthMonth"> -->
<label>State</label><br>
<select class="select-style" name="BirthMonth">
<%
ResultSet rs = null;
Connection con = null;
PreparedStatement pmst1= null;
int countryid = 208;
try{
con = DBConnectivity.getOracleDBConnection();
pmst1 = con.prepareStatement(Sqlquery.getRegion());
pmst1.setInt(1, countryid);
rs=pmst1.executeQuery();
while(rs.next()){
String name = rs.getString("name");
%>
<option value="<%=name %>"><%=name %></option>
<% } %>
<%
}catch(Exception e){
}
%>
</select><br><br>
<p class="contact"> <input id="check" name="name" style="margin-right: 10px" type="checkbox">
<label for="name"> Not Yet Registered GSTIN</label> </p>
<p class= "GSTIN"><label for="GSTIN">GSTIN No.</label></p><br>
<input id = "GSTINNO" maxlength="15" name= "GSTIN" placeholder="GSTIN No." type ="text"><br><br>
<input class="buttom" name="submit" id="submit" tabindex="5" value="Sign me up!" type="submit">
SaveInfo.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try{
ResultSet rs = null;
Connection con = null;
PreparedStatement pmst1= null;
String Orgname = request.getParameter("Orgname");
String check =request.getParameter("check");
String GSTINNO = request.getParameter("GSTINNO");
con = DBConnectivity.getOracleDBConnection();
int clientid = 1000014;
MClient Client = new MClient (Env.getCtx(), clientid, null);
I want all the values in my servlet class and save that values in database below I am mentioning my web.xml file
Kindly help me out
<servlet>
<description></description>
<display-name>SaveInfo</display-name>
<servlet-name>SaveInfo</servlet-name>
<servlet-class>com.org.register.SaveInfo</servlet-class>
<servlet-mapping>
<servlet-name>SaveInfo</servlet-name>
<url-pattern>/servlet/SaveInfo</url-pattern>
</servlet-mapping>

In Servlet you need to get parameters by name attribute, not id.
For example, You have the following,
<input id="Orgname" name="name" placeholder="Organization name" required="" tabindex="5" type="text">
Here you have given id to be Orgname and name parameter is name. So in Servlet you will do,
request.getParameter("name");
But you are doing,
String Orgname = request.getParameter("Orgname");
Secondly, you cannot have same name for two parameters. For both the following you have given name to be name
<input id="Orgname" name="name" placeholder="Organization name" required="" tabindex="5" type="text">
<input id="address" name="name" placeholder="Street,Area,city" required="" tabindex="6" type="text"> <br>
Give some different name to the parameters.

The getParameter function of request object works with name attribute. So please replace your jsp with following.
<form id="contactform" action="servlet/SaveInfo" method="post">
<p class="contact"><label for="email">Email</label></p>
<input id="email" name="email" placeholder="example#domain.com" required="" tabindex="1" type="email">
<p class="contact"><label for="username">User Name</label></p>
<input id="username" name="username" placeholder="username" required="" tabindex="2" type="text">
<p class="contact"><label for="password">Password</label></p>
<input type="password" id="password" name="password" required="" tabindex="3">
<p class="contact"><label for="repassword">Confirm Password</label></p>
<input type="password" id="repassword" name="repassword" required="">
<p class="contact"><label for="phone">Mobile Phone</label></p>
<input id="phone" name="phone" placeholder="phone number" required="" tabindex="4" type="text"> <br>
<p class="contact"><label for="name">Organization Name</label></p>
<input id="Orgname" name="Orgname" placeholder="Organization name" required="" tabindex="5" type="text">
<p class="contact"><label for="Address">Address</label></p>
<input id="address" name="address" placeholder="Street,Area,city" required="" tabindex="6" type="text"> <br>
<!-- <select class="select-style" name="BirthMonth"> -->
<label>State</label><br>
<select class="select-style" name="BirthMonth">
<%
ResultSet rs = null;
Connection con = null;
PreparedStatement pmst1= null;
int countryid = 208;
try{
con = DBConnectivity.getOracleDBConnection();
pmst1 = con.prepareStatement(Sqlquery.getRegion());
pmst1.setInt(1, countryid);
rs=pmst1.executeQuery();
while(rs.next()){
String name = rs.getString("name");
%>
<option value="<%=name %>"><%=name %></option>
<% } %>
<%
}catch(Exception e){
}
%>
</select><br><br>
<p class="contact"> <input id="check" name="name" style="margin-right: 10px" type="checkbox">
<label for="name"> Not Yet Registered GSTIN</label> </p>
<p class= "GSTIN"><label for="GSTIN">GSTIN No.</label></p><br>
<input id = "GSTINNO" maxlength="15" name= "GSTIN" placeholder="GSTIN No." type ="text"><br><br>
<input class="buttom" name="submit" id="submit" tabindex="5" value="Sign me up!" type="submit">

JSP post parameters using their attribute name. you wrote the wrong attribute name in 3 parameters.
Change:
<input id="check" name="name"
<input id="Orgname" name="name"
<input id="address" name="name"
To:
<input id="check" name="check"
<input id="Orgname" name="Orgname"
<input id="address" name="address"

Related

How to use getParts in java to get only image parts?

I'm trying to upload a file to cloudinary. I'm stucked at how to only get parts of image from the form. It keeps on throwing exception: Invalid image file. If I remove all text inputs in the form, the uploading is successful. I guess that happens because the form also has text inside. Please help me solve this. I'm really grateful for your support.
Here is my code:
Form.jsp:
<form role="form" action="<c:url value="/admin/product/update"/>" method="post" enctype="multipart/form-data">
<input name="id" value="${product.id}" hidden="">
<div class="form-group">
<label>Name:</label> <input class="form-control" value="${product.name}" name="name" />
</div>
<div class="form-group">
<label>Price:</label> <input class="form-control" value="${product.price}" type="number" name="price" />
</div>
<div class="form-group">
<label>Quantity:</label> <input class="form-control" value="${product.quantity}" type="number" name="quantity" />
</div>
<div class="form-group">
<label>Image:</label> <input class="form-control" value="${product.image}" name="image" />
</div>
<div class="form-group">
<label>Description </label> <br>
<textarea rows="4" cols="50" name="description" value="${product.description}" ></textarea>
</div>
<div class="form-group">
<label>Category</label>
<div class="checkbox">
<select name="catid">
<c:forEach items="${categorylist}" var="c">
<option value="${c.id}">${c.name}</option>
</c:forEach>
</select>
</div>
</div>
<div class="form-group">
<label>image</label> <input type="file" name="image" value="${product.image }" />
</div>
Servlet.java
BeanUtils.populate(product, request.getParameterMap());
//if (catid != product.getCategory().getId()) {
// Category category = new Category();
category = dao2.getCategoryByID(catid);
product.setCategory(category);
Map result = null;
Collection<Part> fileParts = request.getParts();
for (Part part : fileParts) {
String fileName = part.getSubmittedFileName();
result = UploadImage.uploadImage(fileName, part);
String url = String.valueOf(result.get("url"));
product.setImage(url);
if (result == null) {
throw new RuntimeException("Loi upload");
}
}
dao.update(product);
The Cloudinary upload method supports uploading media files from the sources like a local path, a remote URL, a private storage URL (S3 or Google Cloud storage), a base64 data URI, or an FTP URL.
Based on your code, it seems that you are only supplying the filename of the image.
String fileName = part.getSubmittedFileName();
result = UploadImage.uploadImage(fileName, part);
You would need to update the code to input the local path of the image.

ArrayIndexOutOfBoundsException when use getParameterValues in Servlet

Here is is my HTML .....
I take one input for count how many input .. and then highest four entry can be given....
No Of Members: <select name="member" class="form-control">
<option value="0">Select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<table class="table table-bordered">
<tbody>
<tr>
<td><input type="text" name="studentid" class="form-control" id="" placeholder="Enter Student ID"></td>
<td><input type="text" name="name" class="form-control" id="" placeholder="Enter Name"></td>
<td><input type="text" name="email" class="form-control" id="" placeholder="Enter Email"></td>
<td><input type="text" name="cgpa" class="form-control" id="" placeholder="Enter CGPA"></td>
<tr/>
<tr>
<td><input type="text" name="studentid" class="form-control" id="" placeholder="Enter Student ID"></td>
<td><input type="text" name="name" class="form-control" id="" placeholder="Enter Name"></td>
<td><input type="text" name="email" class="form-control" id="" placeholder="Enter Email"></td>
<td><input type="text" name="cgpa" class="form-control" id="" placeholder="Enter CGPA"></td>
<tr/>
<tr>
<td><input type="text" name="studentid" class="form-control" id="" placeholder="Enter Student ID"></td>
<td><input type="text" name="name" class="form-control" id="" placeholder="Enter Name"></td>
<td><input type="text" name="email3" class="form-control" id="" placeholder="Enter Email"></td>
<td><input type="text" name="cgpa" class="form-control" id="" placeholder="Enter CGPA"></td>
<tr/>
<tr>
<td><input type="text" name="studentid" class="form-control" id="" placeholder="Enter Student ID"></td>
<td><input type="text" name="name" class="form-control" id="" placeholder="Enter Name"></td>
<td><input type="text" name="email" class="form-control" id="" placeholder="Enter Email"></td>
<td><input type="text" name="cgpa" class="form-control" id="" placeholder="Enter CGPA"></td>
<tr/>
</tbody>
</table>
My Servlet
At first i take member no at a int type variable.. and then all the four field in four different array by getParameterValues.
try{
int member=Integer.parseInt(request.getParameter("member"));
String stdID[]=request.getParameterValues("studentid");
String name[]=request.getParameterValues("name");
String email[]=request.getParameterValues("email");
String cgpa[]=request.getParameterValues("cgpa");
for(int i=0;i<=member;i++){
System.out.println(stdID[i]+name[i]+email[i]+cgpa[i]);
}
}catch(Exception e){
System.out.println(e);
e.printStackTrace();
}
When i run this code and select No member (4) and fill all the field and then press submit....
In my console below errors show
How can i solve this ? any idea ?
for(int i=0;i<=member;i++){
to
for(int i=0;i<member;i++){
why have you changed the email to email3 in the third entry?

How to navigate between html & jsp pages in spring

I have a Html page called kind.html inside the WEB-INF directory and an other jsp page called registration.jsp inside the WEB-INF folder. I need to put this registration.jsp page inside the WEB-INF directory so it cannot be accessible if a user attempts to get access to it by typing its URL. So my problem is how can i navigate from kind.html to registration.jsp with link called home I am newbie in this Thank you.
below is my code snippet and png file
kind.html..............................................
<li class='active'><a href='kind.html'><span>Home</span></a></li>
<li class='has-sub'><span>Register</span>
.............................registrationcontroller........................................
#RequestMapping(value="/registration",method = RequestMethod.POST)
public #ResponseBody
String firstRegistration(HttpServletRequest req,
HttpServletResponse response) {
response.setContentType("text/html");
RegistrationModel registrationModel = new RegistrationModel();
registrationModel.setFirstName(req.getParameter("first_name"));
System.out.println("controller " + req.getParameter("first_name") );
registrationModel.setLastName(req.getParameter("last_name"));
registrationModel.setPassword(req.getParameter("password"));
registrationModel.setEmailID(req.getParameter("email"));
System.out.println("controller email " + req.getParameter("email"));
SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd");
try {
Date date = format.parse(req.getParameter("BirthDate"));
registrationModel.setDOB(date);
} catch (Exception e) {
e.printStackTrace();
}
String phoneno=req.getParameter("phoneNo");
Integer phoneNo = Integer.parseInt(phoneno);
System.out.println("phone no ...."+phoneNo);
registrationModel.setPhoneNo(phoneNo);
registrationModel.setGender(req.getParameter("gender"));
String age=req.getParameter("Age");
Long AGE = Long.parseLong(age);
registrationModel.setAge(AGE);
registrationModel.setAvtar(req.getParameter("Avtar"));
System.out.println("avtar"+ req.getParameter("Avtar"));
Address address = new Address();
address.setAddressline(req.getParameter("Full-Address"));
address.setCity(req.getParameter("city"));
address.setLandmark(req.getParameter("landmark"));
address.setState(req.getParameter("state"));
String zipCode =req.getParameter("Zipcode");
Long zipcode = Long.parseLong(zipCode);
address.setZipcode(zipcode);
registrationModel.setAddress(address);
registrationService.resgistration(registrationModel);
return "registration.jsp";
}
..........................registration.jsp.........................................................
<form action="registration" method="post">
<fieldset>
<legend>Register Form</legend>
<div>
<input type="text" name="first_name" placeholder="First Name" />
</div>
<div>
<input type="text" name="last_name" placeholder="Last Name" />
</div>
<div>
<input type="password" name="password" placeholder="Password" />
</div>
<div>
<input type="text" name="email" placeholder="Email" />
</div>
<div>
<input type="text" name="BirthDate" placeholder="BirthDate" />
</div>
<div>
<input type="number" name="Age" placeholder="Age" />
</div>
<div>
<select name="gender">
<option value="select">i am..</option>
<option value="m">Male</option>
<option value="f">Female</option>
</select><br> <br>
</div>
<div>
<input type="number" name="phoneNo" placeholder="PhoneNo" />
</div>
<div>
<input type="text" name="Full-Address"
placeholder="Full-Address" />
</div>
<div>
<input type="text" name="landmark" placeholder="landmark" />
</div>
<div>
<input type="text" name="city" placeholder="city" />
</div>
<div>
<input type="text" name="state" placeholder="state" />
</div>
<div>
<input type="number" name="Zipcode" placeholder="Zipcode" />
</div>
<div>
<input type="file" name="Avtar" placeholder="Avtar" />
</div>
<input type="submit" name="submit" value="Send" />
</fieldset>
</form>![folder structure of project][2]
1st to call your pages html is static so you can use mvc resources "" for it, for jsp you have to use ViewResolver for jstl use InternalResourceViewResolver in its configuration as :
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/view/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
then in your controller use
return "registration";
also you will need method to handle GET request and change below line
<li class='has-sub'><span>Register</span>
if you are using Spring boot you will find these configuration automated.

How to pass the radio button value which is clicked to controller?

I am using Spring MVC controller.
Below is my JSP code in which it will show three radio button. One is Insert, second radio button is Update and third radio button is Delete.
Once I click Insert radio button, it show two text box next to Insert radio button, and same thing with other two radio button.
<script type="text/javascript">
function doDisplay(radio) {
switch (radio.value) {
case "Insert":
document.getElementById("inserts").style.display = "inline";
document.getElementById("updates").style.display = "none";
document.getElementById("delete").style.display = "none";
break;
case "Update":
document.getElementById("inserts").style.display = "none";
document.getElementById("updates").style.display = "inline";
document.getElementById("delete").style.display = "none";
break;
case "Delete":
document.getElementById("inserts").style.display = "none";
document.getElementById("updates").style.display = "none";
document.getElementById("delete").style.display = "inline";
break;
}
}
</script>
<body>
<form method="post" action="testOperation">
<input type="radio" name="tt" value="Insert"
onclick="doDisplay(this);" /> Insert <input type="hidden" name="name" value="insert"><span id="inserts"
style="display: none"> <label for="Node"> Node </label> <input
type="text" name="node" size="20" /> <label for="Data"> Data </label>
<input type="text" name="data" size="100" />
</span> <br /> <input type="radio" name="tt" value="Update"
onclick="doDisplay(this);" /> Update <input type="hidden" name="name" value="update"> <span id="updates"
style="display: none"> <label for="Node"> Node </label> <input
type="text" name="node" size="20" /> <label for="Data"> Data </label>
<input type="text" name="data" size="100"/>
</span> <br /> <input type="radio" name="tt" value="Delete"
onclick="doDisplay(this);" /> Delete <input type="hidden" name="name" value="delete"><span id="delete"
style="display: none"> <label for="Node"> Node </label> <input
type="text" name="node" size="20" /> <label for="Data"> Data </label>
<input type="text" name="data" size="100"/>
</span> <br />
<input type="submit">
</form>
Now what I am trying to do is as soon as I click on Insert radio button, it will show me two textbox next to Insert radio button. And after putting some values inside those two text box, I press submit button on the form. And then it goes to testOperations method in which name field has these many things -
insert,update,delete
How can I force it to have only one field which I am clicking only? Meaing if I am clickign insert radio button, then name variable should have insert value? Below is my method -
#RequestMapping(value = "testOperation", method = RequestMethod.GET)
public Map<String, String> testOperation() {
final Map<String, String> model = new LinkedHashMap<String, String>();
return model;
}
#RequestMapping(value = "testOperation", method = RequestMethod.POST)
public Map<String, String> testOperations(#RequestParam String name,
#RequestParam String node,
#RequestParam String data) {
final Map<String, String> model = new LinkedHashMap<String, String>();
System.out.println(name);
System.out.println(node);
System.out.println(data);
return model;
}
Meaning, Suppose I click Insert radio button and type Hello in the first text and World in the second text box, then I will hit the submit button, and after that I should see insert value in the name variable and hello value in the node variable and world value in the data variable.
And same thing with update and delete.
Is this possible to do?
You have done correct. All you need to do is while click the radio button set the value on name. One hidden variable is enough. Your html part look like this,
<form method="post" action="testOperation">
<!-- I used only one hidden box to store value -->
<input type="hidden" name="name" id="dynamicName">
<input type="radio" name="tt" value="Insert"
onclick="doDisplay(this);" /> Insert <span id="inserts"
style="display: none"> <label for="Node"> Node </label> <input
type="text" name="node" size="20" /> <label for="Data"> Data </label>
<input type="text" name="data" size="100" />
</span> <br /> <input type="radio" name="tt" value="Update"
onclick="doDisplay(this);" /> Update <span id="updates"
style="display: none"> <label for="Node"> Node </label> <input
type="text" name="node" size="20" /> <label for="Data"> Data </label>
<input type="text" name="data" size="100"/>
</span> <br /> <input type="radio" name="tt" value="Delete"
onclick="doDisplay(this);" /> Delete <span id="delete"
style="display: none"> <label for="Node"> Node </label> <input
type="text" name="node" size="20" /> <label for="Data"> Data </label>
<input type="text" name="data" size="100"/>
</span> <br />
<input type="submit">
</form>
And in script,
<script type="text/javascript">
function doDisplay(radio) {
switch (radio.value) {
case "Insert":
document.getElementById("inserts").style.display = "inline";
document.getElementById("updates").style.display = "none";
document.getElementById("delete").style.display = "none";
document.getElementById("dynamicName").value = "insert";
break;
case "Update":
document.getElementById("inserts").style.display = "none";
document.getElementById("updates").style.display = "inline";
document.getElementById("delete").style.display = "none";
document.getElementById("dynamicName").value = "update";
break;
case "Delete":
document.getElementById("inserts").style.display = "none";
document.getElementById("updates").style.display = "none";
document.getElementById("delete").style.display = "inline";
document.getElementById("dynamicName").value = "delete";
break;
}
}
</script>
Hope this helps.
You have inputs with same names, you don't need other hidden. A single node and data inputs are enough
This HTML is enough:
<input type="radio" name="tt" value="Insert" onclick="doDisplay(this);" /> Insert<br/>
<input type="radio" name="tt" value="Update" onclick="doDisplay(this);" /> Update<br/>
<input type="radio" name="tt" value="Delete" onclick="doDisplay(this);" /> Delete<br/>
<label for="Node"> Node </label> <input type="text" name="node" size="20" /><br/>
<label for="Data"> Data </label> <input type="text" name="data" size="100"/><br/>
<input type="submit">
Here is the controller function:
public Map<String, String> testOperations(
#RequestParam(value="tt", required=false) String name,
#RequestParam(value="node", required=false) String node,
#RequestParam(value="data", required=false) String data) {
//...
}

Fill form using ajax in a multipart/form-data

I have a problem with Ajax: I want to fill the form when someone insert a book's isbn, if the book already exist.
I tried this solution, but it doesn't work
Here is the form.
<form action="/Libreria_Tweb/Operation" method="post" enctype="multipart/form-data" name="operation" onsubmit="return controlla()">
<p class="submit">
<select name="tipoInfo" onchange="showDiv(this)">
<option value="addBook"> Inserisci libro </option>
<option value="alterBook"> Modifica libro </option>
</select>
</p>
<div id="alter" style="text-align: left; display: none;"> <p>
<label>Vecchio ISBN </label> <input type="text" name="oldIsbn" />
</p></div>
<p>
<label>ISBN:</label> <input type="text" name="isbn" onchange="makeRequest(this.value)"/>
</p>
<p>
<label>Titolo:</label> <input type="text" name="titolo" />
</p>
<p>
<label>Autore: </label><input type="text" name="autore" />
</p>
<p>
<label>Categoria: </label>
<select name="categoria">
<option value="musica">Musica</option>
<option value="letteratura">Letteratura</option>
<option value="cucina">Cucina</option>
<option value="informatica">Informatica</option>
</select>
</p>
<p>
<label>Prezzo:</label> <input type="text" name="prezzo" />
</p>
<p>
<label>Copertina:</label> <input type="file" name="copertina" />
</p>
<p class="submit">
<input type="submit" name="operation" value="Invia" />
<input type="reset" value="Reset" />
</p>
</form>
Here is the method makeRequest(isbn):
function makeRequest(isbn) {
var xmlHttpReq = getXMLHttpRequest();
xmlHttpReq.onreadystatechange = getReadyStateHandler(xmlHttpReq);
xmlHttpReq.open("POST", "/Operation?operation=getBook&isbn="+isbn, true);
xmlHttpReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttpReq.send(null);
}
And here is the Servlet for take data:
Object[] arr = dbm.getElemById(request);
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print(arr);
where getElemById return an array wich contains all book's data.
PS: I can't use JQuery, Json, etcetera..., only Ajax and "simple" Java.
(Sorry for my English)

Categories

Resources