mixing up ajax and jsp to get data into a servlet - java

I've got a jsp file with two text fields (signUp and post). Now, I want the post text and the signUp text to be called to a servlet. Normally its going with request.getParameter(), but now I want the post text going to the servlet with an AJAX function and the signup text with the normal way (that means the name of the input within the jsp file and then request.getParameter).
Is it possible to mix both parts within one servlet because i have this:
<form name="form1" method="POST" action="PostWallServlet" id="form1">
form1 is the ajax code. I don't know how this should work. Normally there stands
`<form action="PostWallServlet" method="POST" >
and everything is callable through the Servlet. But, for now I don't know how I can mix up both components.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PostWall pw=new PostWall();
SimpleDateFormat df = new SimpleDateFormat("YYYY/MM/DD hh:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println("Current Date Time : " + df.format(cal.getTime()));
String message = "";
String sender = request.getParameter("sender");
String post = request.getParameter("message");
String a= df.format(cal.getTime()).toString();
pw.setSender(sender);
pw.setPost(post);
pw.setDate(a);
if (pwi.addPost(pw)) {
message = "Student Successfuly Added";
} else {
message = "Student Adding Failed";
}
//RequestDispatcher rd = request.getRequestDispatcher("post.jsp");
//rd.forward(request, response);
}
$(document).ready(function(){
$('#Add').click(function(){
sendData();
});
});
function sendData(){
var mge = $('#newText').val();
alert(mge);
$.ajax({
type: "POST",
url: "PostWallServlet",
data: { message : mge }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
</script>
<form name="form1" method="GET" action="PostWallServlet" id="form1"></form>
<table border="0" width="100%">
<tr>
<td colspan="3"> ${message}</td>
</tr>
<tr>
<td>Sender</td>
<td>:</td>
<td><input type="text" name="sender" value="" size=20/></td>
</tr>
<tr>
<td>Post</td>
<td>:</td>
<td><input type="text" name="post" value="" size=500 id="newText"/ ></td>
</tr>
<tr>
<td></td>
<td></td>
<td><input type="submit" value="Add" name="Add" /></td>
</tr>
</table>
Any solutions?

Put your ending tag for form AFTER all your inputs:
<form name="form1" method="GET" action="PostWallServlet" id="form1">
...
<td><input type="text" name="sender" value="" size=20 /></td>
...
<td><input type="text" name="post" value="" size=500 id="newText" /></td>
...
<td><input type="submit" value="Add" name="Add" /></td>
...
</form>
Your inputs must be INSIDE the form, not after the form.
Also make sure to end your input tags with /> not / >. You have a space between / and > on one of them.
For the Ajax part you need to give your inputs ids as well as names:
<td><input type="text" name="sender" id="sender" value="" size=20 /></td>
And then in your Ajax function for data:
data: { sender: $('#sender').val(), post: $('#post').val() }

Related

Which dynamic created button was pressed in Servlet

I have dynamically created buttons.
<form action="/" method="post">
<table cellpadding="4">
<%
List<Room> rl = (List<Room>) request.getAttribute("roomList");
if(rl != null) {
for (Room r : rl) {
String name = r.getName();
%>
<tr>
<td><%=name%></td>
<td><input type="submit" value="Add a Booking" name=<%=name%> /></td>
</tr>
<%
}
}
%>
</table>
I know which button was clicked with the following code;
String addButton = req.getParameter("addButton");
However, in this situation, I am not able to know the name of the button. Because the name of the button could be anything. How could I know which button was pressed? Thanks in advance!
You can possibly have at least two solutions:
1. Solution in Java code on the server side
in JSP each of the submit button will be named with the submit_ prefix
<input type="submit" value="Add a Booking" name=<%="submit_"+name%> />
When request is send to the server you will loop parameters and search for one with this prefix, saving its value to submit attribute:
private void setSubmitValue(HttpServletRequest request) {
String SUBMIT_PREFIX = "submit_";
for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) {
String key = (String) e.nextElement();
if (key.startsWith(SUBMIT_PREFIX)) {
String value = key.substring(SUBMIT_PREFIX.length());
request.setAttribute("submit", value);
break;
}
}
}
2. Solution with JavaScript on the client (browser) side
Introduce in the form new hidden widget that will hold the number of room clicked. When button is clicked its value is stored in that widget.
When request is send, on the server side you just read the value of that parameter (widget name).
Below is an example: room-nr will have value of clicked button
var form = document.forms['add-room'];
$(form).on('click', 'button', function(e) {
e.preventDefault();
var name = $(this).attr('name')
form['room-nr'].value = name.replace(/\D+/, '');
console.log(form['room-nr'].value);
//form['add-booking'].click();
});
.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form name="add-room" action='.'">
<input type="hidden" name="room-nr" value="" />
<table cellpadding="4">
<tr>
<td>room1</td>
<td>
<button type="button" name="room-1">Add</button>
</td>
</tr>
<tr>
<td>room2</td>
<td>
<button type="button" name="room-2">Add</button>
</td>
</tr>
<tr>
<td>room3</td>
<td>
<button type="button" name="room3">Add</button>
</td>
</tr>
</table>
<input type="submit" value="Add a Booking" name="add-booking" class="hide" />
</form>
You need to do the following:
<input type="submit" value="<%name%>" name="Add Booking"
/>

servlets: get the null parameters by ajax in servlets

String isno1=request.getParameter("isbn");
String bktitle2=request.getParameter("booktitle");
String authr3=(String) request.getParameter("author");
System.out.println(isno1+bktitle2+authr3);
Enumeration paramaterNames = request.getParameterNames();
when i am taking the parameters in servlet then i am gettin my values as 'null'
what wrong am i doing.
this is the way i am setting the parameters...
from a jsp page using script tag
<script type="text/javascript">
function getHTTPObject()
{
var httpobject;
if(!httpobject && typeof(XMLHttpRequest) != 'undefined')
{
try{
httpobject=new XMLHttpRequest();
}
catch(e){
xmlhttp=false;
}
}
return httpobject;
}
var httpob=getHTTPObject();
function handleHttpResponse(){
if(httpob.readyState==4){
//alert("sd");
var result=httpob.responseText;
alert(result);
/* document.write("hi your book is submitted !!!!!"); */
}
}
function auth(){
var params="isbn="+document.mayurform.isbn.value+"&booktitle="+document.mayurform.booktitle.value+"&author="+document.mayurform.author.value;
alert("params sending"+params);
httpob.open("POST","addbook",true);
httpob.setRequestHeader("Content-type","application/x-www-form-urlencoded");
httpob.setRequestHeader("Content-length",params.length);
httpob.setRequestHeader("Connection","close");
/* httpob.setRequestHeader("Content-type","application/x-www-from-urlencoded");
httpob.setRequestHeader("Content-length",params.length);
httpob.setRequestHeader("Connection","close"); */
httpob.onreadystatechange=handleHttpResponse;
httpob.send();
}
</script>
and this my form.....
<form style="margin: 100px;" name="mayurform">
<table align="center">
<tr>
<td align="center">ISBN NO.</td>
<td><input align="middle" type="text" size="20" name="id" id="isbn">
</tr>
<tr>
<td align="center">Book-Title</td>
<td><input align="middle" type="text" size="20" name="pwd" id="booktitle">
</td>
</tr>
<tr>
<td align="center">Author</td>
<td><input align="middle" type="text" size="20" name="pwd" id="author">
</tr>
<tr>
<td><input align="middle" type="button" size="20" name="Add-Book" onclick="auth()">
</tr>
</table>
</form>
You are fetching parameters with ID's you should give Names.
for example
String isno1=request.getParameter("isbn"); //here is isbn is id
you should write
<input align="middle" type="text" size="20" name="id" id="isbn">
String isno1=request.getParameter("id");-----------^
and also
<td><input align="middle" type="text" size="20" name="pwd" id="booktitle">
<td><input align="middle" type="text" size="20" name="pwd" id="author">
both inputs have the same **name** please check it
http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Form-Data.html
Use like below ajax send() to send data
function auth(){
var params="isbn="+document.mayurform.isbn.value+"&booktitle="+document.mayurform.booktitle.value+"&author="+document.mayurform.author.value;
alert("params sending"+params);
.......
...
httpob.send(params);//change is here
}
call httpob.send(),passing in the parameters that will be sent (without the "?" prefix).

Submitting a Spring Form in AJax is always null

I am trying to submit a spring form via ajax but the values within the form are always coming across as null (The actual form is not null).
This is how I send the form from the JSP:
$('#fSystemSave').click(function() {
$.post("/live-application/systemSave", {systemForm: $("#systemForm").serialize()}, displayModifiedSystemResults, "html");
});
This is the form:
<form:form id="systemForm"
method="post" action="/live-application/systemSave"
commandName="systemForm">
<tr>
<td colspan="1" align="left">
<strong>SYSTEM SETTINGS</strong>
</td>
</tr>
<tr>
<td valign="top">Name: </td>
<td valign="top"><form:input path="fName" size="20" /> </td>
</tr>
<tr>
<td valign="top" align="left">
<button type="button" id="fSystemSave">Save</button>
</td>
</tr>
</form:form>
And this is the Java controller side:
#RequestMapping(value = "/systemSave", method = RequestMethod.POST)
public void saveSystem(#ModelAttribute("systemForm") SystemForm systemForm, OutputStream outputStream) throws IOException {
logger.info("Save System1: " + systemForm);
logger.info("Save System2: " + systemForm.getfName());
}
So 'Save System1' returns an Object tostring and 'Save System2' returns null. Can anyone spot what I am doing wrong?
Thanks,
I don't know Spring but I think {systemForm: $("#systemForm").serialize()} should just be $("#systemForm").serialize().

populating the uploaded file name and size in a html table, appending new values when user choose files at second time

Question is i have table in which i want to populate the values of file name and file size after user click the choose file button and select any number of files, Now the issue is if the user click choose files button second time i want to append the new values in the table and add the new file in the array so that it can uploaded.. my code is,
html form code:
<form id="simpleuploadform" method="post" action="upload" enctype="multipart/form-data">
<table class="span10" border="0">
<tr>
<td colspan="3">
<legend>Simple Upload</legend>
</td>
</tr>
<tr>
<td>
<input type="file" name="files[]" multiple="multiple" onchange="getFileSizeandName(this);"/>
<div id="successdiv" hidden="true" class="label label-success">Image uploaded successfully</div>
<div id="errordiv" hidden="true" class="label label-error">Image not successfully uploaded</div>
<div id="streamdiv" hidden="true" class="label label-warning">Issue while uploading try again</div>
</td>
<td id="renameFile" align="right"></td>
<td id="removeFile" align="right"></td>
</tr>
<tr>
<td colspan="3">
<div id="uploaddiv">
<table id="uploadTable" class="table table-striped table-bordered" width="200" height="200" scrolling="yes">
<thead>
<tr>
<th>Title</th>
<th>Size</th>
</tr>
</thead>
<tbody id="tbodyid">
<tr id="tr0">
<td id="filetd0" height="10px" width="50px"></td>
<td id="filesizetd0" height="10px" width="5px"></td>
</tr>
<tr id="tr1">
<td id="filetd1" height="10px" width="50px"></td>
<td id="filesizetd1" height="10px" width="5px"></td>
</tr>
<tr id="tr2">
<td id="filetd2" height="10px" width="50px"></td>
<td id="filesizetd2" height="10px" width="5px"></td>
</tr>
<tr id="tr3">
<td id="filetd3" height="10px" width="50px"></td>
<td id="filesizetd3" height="10px" width="5px"></td>
</tr>
<tr id="tr4">
<td id="filetd4" height="10px" width="50px"></td>
<td id="filesizetd4" height="10px" width="5px"></td>
</tr>
</tbody>
<tfoot>
<tr>
<td id="filecount" height="10px" width="50px"></td>
<td id="totalsize" height="10px" width="5px"></td>
</tr>
</tfoot>
</table>
</div>
</td>
</tr>
<tr>
<td colspan="3">
<input type="submit" class="btn btn-primary" onClick="CloseAndRefresh();" value="Start Upload" id="startButton" disabled>
<input type="reset" class="btn btn-primary" onClick="Clear();" value="Clear" id="clearButton" disabled>
<input type="button" class="btn" onClick="window.close();" value="Close">
</td>
</tr>
</table>
javascript code:
<script type="text/javascript">
var totalsizeOfUploadFiles = 0;
function getFileSizeandName(input)
{
var select = $('#uploadTable tbody');
$('#renameFile').empty();$('#removeFile').empty();
if(input.files.length > 0)
{
$('#renameFile').append($('<a id="renameRec">Rename Selected</a>'));
$('#removeFile').append($('<a id="removeRec">Remove Selected</a>'));
$('#startButton').removeAttr("disabled", "disabled");
$('#clearButton').removeAttr("disabled", "disabled");
}
//if(input.files.length <= 5)
//{
for(var i =0; i<input.files.length; i++)
{
var filesizeInBytes = input.files[i].size;
var filesizeInMB = (filesizeInBytes / (1024*1024)).toFixed(2);
var filename = input.files[i].name;
//alert("File name is : "+filename+" || size : "+filesizeInMB+" MB || size : "+filesizeInBytes+" Bytes");
if(i<=4)
{
$('#filetd'+i+'').text(filename);
$('#filesizetd'+i+'').text(filesizeInMB);
}
else if(i>4)
select.append($('<tr id=tr'+i+'><td id=filetd'+i+'>'+filename+'</td><td id=filesizetd'+i+'>'+filesizeInMB+'</td></tr>'));
totalsizeOfUploadFiles += parseFloat(filesizeInMB);
$('#totalsize').text(totalsizeOfUploadFiles.toFixed(2)+" MB");
if(i==0)
$('#filecount').text("1file");
else
{
var no = parseInt(i) + 1;
$('#filecount').text(no+"files");
}
}
//}
}
function CloseAndRefresh()
{
var daa = '<%=status%>';
if(daa == "true")
$('#successdiv').show();
else if(daa == "false")
$('#errordiv').show();
else
$('#streamdiv').show();
opener.location.reload(true);
self.close();
}
function Clear()
{
$('#uploadTable tbody tr td').each(function(){
$(this).text("");
});
$('#uploadTable tfoot tr td').each(function(){
$(this).text("");
});
}
i am trying to do as like this http://www.shutterfly.com/ image upload.
any help will be appreciated, thank you friends...
You are navigating away using javascript, function CloseAndRefresh on clicking submit button.
What actually happens is that the uploading request is being submitted while the CloseAndRefresh function is being executed at almost the same time using different thread. If the upload request is not fast enough, the web page will get refresh first and your upload request get terminated immediately. There is no easy way to prevent this using your existing code.
You should use advanced method of uploading like jQuery uploading plugin to send the request. The plugin provide an binder to execute function on successful/failed submittsion.
Thank you gigadot, i solve the issue as like below,
The html form have the same code as i posted earlier, in the previous js code i have the CloseAndRefresh() method i remove it now from js as well as from the submit button onclick event.
When the form action called the controller, in which i have the code
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String UploadReceipts(#RequestParam("files[]") List<MultipartFile> file, Model model) throws IOException {
boolean status = false;
try
{
for(int i=0; i< file.size(); i++)
{
if(!file.get(i).isEmpty())
{
CommonsMultipartFile cm = (CommonsMultipartFile) file.get(i);
status = simpleUploadService.uploadFileandSave(cm);
model.addAttribute("status", status);
}
}
}
catch (IOException e) {
status = false;
model.addAttribute("status", status);
}
return "pages/simpleUploadStatus";
}
Now i redirect it to another page in which i throws the appropriate messages for the user.
that's all...

Spring MVC Request Param

I have a login page with form action of j_security_check. As of now this form just have two fields namely username
and password. I want to add a new dropdown to this form and collect the selected value in controller using
#RequestParam. For some reason I am not able to pass this dropdown value from JSP to my controller as its throwing the
exception: MissingServletRequestParameterException (Which occurs anytime a request param is missing).
In the code below I added the Visuals dropdown. Do I need to use Spring:Bind tag here?
Also on successful login, the control is directed to a controller with request mapping /controller1.html and this is where
I am trying to collect the dropdown value.
<form name="appLogin" action="j_security_check" method="POST">
<table width="100%">
<tr>
<td align="center">
<table>
<tr>
<td>Username: </td>
<td><input id="userName" name="j_username" value=""/></td>
</tr>
<tr>
<td>Password: </td>
<td><input name="j_password" type="password" value="" /></td>
</tr>
<tr>
<td>Visual: </td>
<td><Select name="visuals" id="visuals"/>
<option value="S1">S1</option>
<option value="S2">S2</option>
<option value="S3">S3</option>
<option value="S4">S4</option>
</Select>
</td>
</tr>
</table>
<table>
<tr>
<td>
<button type="submit" name="submit" value="Sign In">Sign In</button>
<input type="submit"/>
</td>
</tr>
</table>
</div>
</div>
</td>
</tr>
</table>
</form>
Controller Code:
#RequestMapping( value = " /controller1.html", method = RequestMethod.GET )
public String setupForm( #RequestParam(value = "visuals", required=false) String visuals,
ModelMap model )
{
List<String> studentNames = new ArrayList<String>();
List<String> teacherNames = new ArrayList<String>();
model.addAttribute("someData", teacherNames);
model.addAttribute("anotherData", studentNames);
model.addAttribute("visuals", visuals);
log.info("Role from Dropdown: " + visuals);
return "school/classTen";
}
You need to create yyour own Filter by extending AbstractAuthenticationProcessingFilter
I don't have the entire code in front of my eyes, but the following article could help you:
http://mark.koli.ch/2010/07/spring-3-and-spring-security-setting-your-own-custom-j-spring-security-check-filter-processes-url.html

Categories