Java httpServletRequest Into Arrays - java

I have a jsp page that calls a JavaScript function to dynamically create content like this:
<input type="text" name="loadLocation1" id="loadLocation1" class="loadLocation />
<input type="text" name="loadMagnitude1" id="loadMagnitude1" class="loadMagnitude / >
<input type="text" name="loadLocation2" id="loadLocation2" class="loadLocation />
<input type="text" name="loadMagnitude2" id="loadMagnitude2" class="loadMagnitude / >
and so on
My goal is to end up with two separate arraysLists containing:
[loadLocation1, loadLocation2, etc.]
[loadMagnitude1, loadMagnitude2, etc.]
Right now I have a servlet that is separating out the data into two different arrays in a rather stupid way:
if(req.getParameter("loadLocation1" ) != null ) {
beam.appendForceDistance( Double.parseDouble(req.getParameter("loadLocation1" )));
beam.appendForce( Double.parseDouble(req.getParameter("loadMagnitude1" )));
if(req.getParameter("loadLocation2" ) != null ) {
beam.appendForceDistance( Double.parseDouble(req.getParameter("loadLocation2" )));
beam.appendForce( Double.parseDouble(req.getParameter("loadMagnitude2" )));
etc.
Which isn't expandable at all. I've looked at the HttpServletRequest documentation, without much luck. I was able to iterate over a map and get the strings of keys and values to print out which wasn't much help since I couldn't separate results by class name.
Also, the getAttribute() looked promising, but when I called it on a request:
req.getAttribute("loadLocation")
it returns null.
Is there any way to separate the two types of data based on class into two different arrays while maintaining the order?

No, this is not possible.
When the form is submitted only the form elements with the "name" attribute will be submitted.
The order will remain exactly the same so that part is solved.
What I would suggest is to create the Object with javascript and post that with ajax.
// One Load object
function Load(args) {
this.kind = args.kind || null; // Location or Magnitude
this.value = args.value || null;
this.clazz = args.clazz || null;
}
var arr = new Array();
var loads = document.getElementsByName('load');
for (var i=0; i< loads.length; i++) {
arr[i] = new Load({
kind: loads[i].id,
value: loads[i].value.
clazz: loads[i].getAttribute('class').
});
}
Use JQuery to post this:
$.postJSON(getHost() + "save/load",arr, function(data) {
});
And your jsp looks like this
<input type="text" name="load" class="loadLocation />
<input type="text" name="load" class="loadMagnitude / >
<input type="text" name="load" class="loadLocation />
<input type="text" name="load" class="loadMagnitude / >
The code is not tested or perfect but you get the idea I hope.

Related

Pagination issue with JSP

I am able to display a table when a user clicks a search button. But now I want to split the table into chunks of 20 rows where the user can click next or previous to go forward and backward through all of the data. I am not allowed to use JavaScript for this assignment. Only JSP, Java, HTML.
The two debugging out.print() calls are not showing up. A different page is being loaded after one of the buttons is clicked, but the two debugging out.print calls are not displaying any HTML. I have checked out How to know which button is clicked on jsp this post but had no luck.
<form method="GET">
<center>
<input type="submit" name="previous_table" value="Previous" />
<input type="submit" name="next_table" value="Next" />
</center>
</form>
</br>
<%
String val1 = request.getParameter("previous_table");
String val2 = request.getParameter("next_table");
try {
if ("Previous".equals(val1)) { // Get previous results
out.println("<h1>HELLO 1</h1>");
buildTable(rs, out, false);
}
else if ("Next".equals(val2)) { // Get next results
out.println("<h1>HELLO 2</h1>");
buildTable(rs, out, true);
}
} catch(Exception e) {
out.print("<center><h1>"+e.toString()+"</h1></center>");
}
%>
I also have a follow up question. If the user clicks next or previous button, will my current table on the page be overwritten by the new one? That is my intent but I don't know if it will work that way.
I WAS ABLE TO FIX IT BY DOING THIS:
<form method="POST">
<center>
<input type="submit" name="previous_table" value="Previous" />
<input type="submit" name="next_table" value="Next" />
</center>
</form>
</br>
<%
String val1 = request.getParameter("previous_table");
String val2 = request.getParameter("next_table");
you should add name with value for button after that you can get by parameter click value.
`<input type="hidden" name="myprevious" value="previous"/>
<input type="hidden" name="mynext" value="next" />
<%
String val1 = request.getParameter("myprevious");
String val2 = request.getParameter("mynext");
try {
if (val1 == "previous") { // Get previous results
out.println("<h1>HELLO 1</h1>");
buildTable(rs, out, false);
}
else if (val2 == "next") { // Go next results
out.println("<h1>HELLO 2</h1>");
buildTable(rs, out, true);
}
} catch(Exception e) {
out.print("<center><h1>"+e.toString()+"</h1></center>");
}
%>
`
I hope it will help you.
Thanks.
Try to use the subList() method of a List<>().
As explained here.
HOW TO IMPLEMENT IT ##
you can put an hidden input in your form to give you the last index for your list like :
<input type="hiden" value="${last_index_of_your_list + 1}" name="index">
Then in your servlet part you put like this :
int index = Interger.ParseInt(request.getParameter("index"));
if(index <= 0){
datalist = datalist(0, 19>datalist.size()? datalist.size() : 19);
}else{
if(clicked_on_next){
datalist = datalist(index, index+19>datalist.size()? datalist.size() : index+19 );
}else{
datalist = datalist(index - 40, index-20>datalist.size()? datalist.size() : index-20 );
}
}
You are using hidden fields but you need to use submit button for next and previous.
<input type="submit" name="myprevious" value="previous"/>
<input type="submit" name="mynext" value="next" />
Make sure both are define in form. when we submit form after that you will get button value in parameter.same my previous answer. because we can not get parameter value without submit form.
Thanks.

checkbox index value in java

I am working in spring mvc, I used the following line to generate the checkboxes from DB table.
<td><input type="checkbox" name="loanId" value="${loan.id}" class="it"></td>
I need to get the index of this selected values in my java controller. I am able to get the values which are selected, but how to get the index values?
following code is I am using
String[] loanIds = request.getParameterValues("loanId");
for (String string : loanIds) {
System.out.println("loanIds****"+string);
}
You need javascript to get the index of checkbox and set it to hidden field :
var ids = document.getElementsByName('loanId');
var ind = document.getElementById('loanIndex');
var put = function() {
var arr = [];
var i = -1;
while (ids[++i])
if (ids[i].checked) arr.push(i);
ind.value = arr.join(',');
alert('selected index: ' + ind.value);
};
var i = -1;
while (ids[++i])
ids[i].onchange = put;
<input type="checkbox" name="loanId" />
<input type="checkbox" name="loanId" />
<input type="checkbox" name="loanId" />
<input type="checkbox" name="loanId" />
<input type="hidden" name="loanIndex" id="loanIndex" value="" />
In controller:
String[] loanIndex= request.getParameter("loanIndex").split(",");
There is no direct method for this purpose.
You can have index as value which is passed on selecting checkbox. You can use this index-value later to get selected record data from in-memory collection i.e. when user selects checkbox and submits request, on server side you will fetch ParameterValues from request and list data from datasource, compare ids then derive selected list.
Using Jquery
var indexString;
var index;
$('#.it').each(function () {
$(this).find('.SomeCheckboxClass').each(function () {
if ($(this).attr('checked')) {
index = $(this).index();
indexString = index + ",";
}
});
});
post this indexString, it is a comma separated index string.

Recaptcha with scala and play framework

by using tutorial , i am trying to apply captcha in my play project.
HTML
<form action="/applyForWork" method="post" enctype="multipart/form-data">
<input type="text" name="relevant" id="relevant" >
<input type="file" name="file"/>
<br/>
#Html(views.ReCaptcha.render())
<br/>
<input type="submit" value="Upload"/>
</form>
Controller
def applyForWork = Action {
implicit request =>
println(request.body.asFormUrlEncoded) //None
Ok("submitted")
}
Q1.why this println(request.body.asFormUrlEncoded) gives None?
Q2.captcha box is shown in my html but how to validate it is correct
or not?
I am using scala 2.10 with play framework 2.2
A1. The reason of this is enctype of your form. When you use multipart/form-data you can access form data with:
request.body.asMultipartFormData
A2. Anyway, if I were you I would stick to the solution presented in the tutorial you mentioned and create form mapping for recaptcha values.
case class CaptchaForm(challenge: String, response: String)
val captchaForm = Form[CaptchaForm](
mapping(
"recaptcha_challenge_field" -> nonEmptyText,
"recaptcha_response_field" -> nonEmptyText
)(CaptchaForm.apply)(CaptchaForm.unapply)
)
This way you can reuse it anywhere you need to handle Repatcha.
def applyForWork = Action { implicit request =>
captchaForm.bindFromRequest.fold(
formWithErrors => BadRequest("Captcha Param Error"),
captchaForm => {
println(captchaForm.challenge)
println(captchaForm.response)
if (check(request.remoteAddress, captchaForm.challenge, captchaForm.response)) {
//Captcha ok
}
}
)
}
def check(remoteAddress: String, challenge: String, response: String): Boolean = {
val reCaptcha = new ReCaptchaImpl()
reCaptcha.setPrivateKey(privateKey())
val reCaptchaResponse = reCaptcha.checkAnswer(remoteAddress, challenge, response)
reCaptchaResponse.isValid()
}
Hint
Consider using routes mapping in your template instead of hard-coded URLs. In this case replace
action="/applyForWork"
with
action="#routes.YourFormController.handleAction()"
If you ever change your mapping to an action in the routes you won't have to change all your templates that use it.

Dynamically adding duplicate (unique ID) form Div elements using javascript

I have a form having fields like:
<div class="row">
<div class="field">
<input class="" type="text" name="college" id="college"/>
</div>
<div class="field">
<input class="" type="text" name="city" id="city"/>
</div>
<div class="field">
<input class="" type="text" name="zip" id="zip"/>
</div>
</div>
<input type="button" class="buttonWidth" id="btnAddressAdd" value="Add Worksite Addressess"/>
I have a Add extra address button that add's another copy of div "row" to the page. I need to send all data from the page as a request to the Controller. How do I write a script that add's extra div copy onclick of the button and also appends a unique id to each of the new fields?
See working example in Dojo: http://jsfiddle.net/phusick/PeQCN/
And the same code in plain vanilla JavaScript: http://jsfiddle.net/phusick/Rceua/
The Dojo version employs dojo/_base/lang::clone as #Peter Rader mentioned:
// var lang = require("dojo/_base/lang");
// var array = require("dojo/_base/array");
// var query = require("dojo/query");
// var domAttr = require("dojo/dom-attr");
var counter = 0;
function duplicate(/*Node*/sourceNode, /*Array*/attributesToBump) {
counter++;
var out = lang.clone(sourceNode);
if (domAttr.has(out, "id")) { out.id = bump(out.id); }
query("*", out).forEach(function(node) {
array.forEach(attributesToBump, function(attribute) {
if (domAttr.has(node, attribute)) {
domAttr.set(node, attribute, bump(domAttr.get(node, attribute)));
}
})
});
function bump(/*String*/str) {
return str + "_" + counter;
}
return out;
}
How to use the aforementioned duplicate function:
// var dom = require("dojo/dom");
// var domConstruct = require("dojo/dom-construct");
var sourceNode = dom.byId("fieldset");
var node = duplicate(sourceNode, ["id", "name", "placeholder"]);
domConstruct.place(node, sourceNode, "after");
I have written code to achieve this.
Logic:
1) get the innerHTML of desired parent
2) replace id in the text
3) Insert the new html
See a working code
Pardon me for bad style of coding on JS part. I am not use to coding directly on DOM. I prefer JQuery.
Try
to use this snipplet (see usage)
http://dojotoolkit.org/reference-guide/1.8/dojo/_base/lang.html#dojo-base-lang-clone

Get HTML nodes that have the same parent - JAVA

I have a document containing several forms similar to the example posted below. I want to extract all the name/value pairs from the hidden input fields of one of the forms, the form is identified by its name and I don't know in advance how many hidden fields will be present.
I am able to select all the relevant input fields in the document using the selector query: input[type=hidden][name][value]
Is there a way to only select the input fields which has FORM[name=lgo] as parent? Using some kind filter maybe?
<FORM METHOD='POST' onSubmit='javascript:isWaitForm();' ACTION='https://abc-azerty.querty.se/carmon/servlet/action/change_1 ' name='lgo'>
<input type='hidden' name='LogInFlag' value='1'>
<input type='hidden' name='LogInTime' value='2011-07-26 11:10'>
<input type='hidden' name='cCode2' value='SE'>
<a href='javascript:isWaitForm();javascript:document.lgo.submit();' class='linkNone'>Business Monitor</a>
<a href='javascript:isWaitForm();javascript:document.lgo.submit();' class='linkNone'>
<input type='image' src='/images/button_arrow_right.gif' height=19 width=22 border=0 style='float:left;'></A>
</FORM>
Based on this info, at least one of following should work -
doc.select("form[name=lgo] > input[type=hidden]");
Or, you can chain your selects -
doc.select("form[name=lgo]").select("input[type=hidden]");
The select method is available in a Document, Element, or in Elements. It is contextual, so you can filter by selecting from a specific element, or by chaining select calls.
<script type="text/javascript">
var inputs = document.getElementsByName('lgo')[0].getElementsByTagName('input');
for(var i = 0 ; i < inputs.length ; i++){
if(inputs[i].getAttribute('type') == "hidden") {
// This will get the name: inputs[i].getAttribute('name')
// This will get the value: inputs[i].value)
console.log(inputs[i].getAttribute('name') + ": " + inputs[i].value);
}}
</script>

Categories