POST data sent by Spring MVC is null on IE8 - java

I have two text fields (pageField1) and pageField2) in Spring MVC where an user can input in page numbers. The javascript code retrieves the values in these textfields and sends as POST data to the controller. The code for retreiving the values and sending as POST data in javascript is exactly the same for both fields.
In the Controller, I use request.getParameter("value") to retrieve the POST data.
On Firefox and Chrome, values for both pageField1 and pageField2 are retrieved fine.
On IE8, request.getParameter("value") returns null for pageField1 but the correct value for pageField2.
This is really baffling, and I am stumped. I put an alert just before Spring MVC sends the POST data to the controller. The values are exactly the same for FireFox and IE, but when retrieved on the controller, its null on IE.
Any input would be great! I can post snippet of the code if needed.
Thanks!

Will try using HTTPtea. I already downloaded it, just have to configure it now.
Thanks!! Here is my JavaScript code:
Here is the JavaScript code:
functionPageField1(event){
if (event == null || event.keyCode == 13) {
var domain = document.getElementById('domainTextField').value;
var nameToFindExcl = document.getElementById('searchObjectsExclTextField').value;
var pageNumberExcl = document.getElementById('pageNumberExclTextField').value;
var pageCountExcl = document.getElementById('pageCountExclTextField').value;
var nameToFindIncl = document.getElementById('searchObjectsInclTextField').value;
var pageNumberIncl = document.getElementById('pageNumberInclTextField').value;
if (!isValidInput(pageNumberExcl,pageNumberIncl)){
return;
}
alert("/sysmgr/domains/viewDomainObjects.spr?domain=" + domain + "&nameToFindExcl=" + nameToFindExcl +
"&pageNumberExcl=" + pageNumberExcl + "&nameToFindIncl=" + nameToFindIncl + "&pageNumberIncl=" + pageNumberIncl);
/* Its the pageNumberExcl that is null in the controller, where as all other
values are fine.
In the above alert, I see the correct value for pageNumberExcl, but its null when I retreive it in the controller.
*/
window.location="/sysmgr/domains/viewDomainObjects.spr?domain=" + domain + "&nameToFindExcl=" + nameToFindExcl +
"&pageNumberExcl=" + pageNumberExcl + "&nameToFindIncl=" + nameToFindIncl + "&pageNumberIncl=" + pageNumberIncl;
}
}
//This is the snippet of the html code that defines the pageNumberExcl Field
<td>
<p align="right">
<fmt:message key="form.any.page"/> <input type="text" id="pageNumberExclTextField"
value="${pageNumberExcl}" size="3" onKeyPress="numberPageExcl(event)">
<fmt:message key="form.any.of"/> <input disabled type="text" style="border-style:none; background-color:white; color:black"
id="pageCountExclTextField" value="${pageCountExcl}" size="3">
</p>
</td>`

Related

How to remove hard coded values from JSP and achieve redirection in one line of code?

I am trying to remove the hardcode name from JSP file. I need to give the names in Config file and call in the jsp so that when a user does view page source he should not see the names.
How can I do it in JSP.
My code:
if (((tech == 'google.com') && ((id == 'email') || id == 'domain'))) || ((tech == 'google') && id == 'test')))
window.location = (url.substring(0, res + 5) + ("google/") + url.substring(res + 5, url.length));
now how to remove the hardcoded values and give it in the config file and call it here so that when I view page source I should not see google.com names
My New Code try:
Config.properties
envs=google.com,yahho.com
name= google,yahoo
tokenurl=google/,yahoo/
sample.jsp
<%# page import = "java.util.ResourceBundle" %>
<% ResourceBundle resource = ResourceBundle.getBundle("config");
String names=resource.getString("name");
String env=resource.getString("envs");
String turls=resource.getString("tokenurl");
%>
if (((tech == env[0]) && ((id == 'email') || id == 'domain'))) || ((tech
== 'names[0]') && id == 'test')))
window.location = (url.substring(0, res + 5) + ("turls[0]") +
url.substring(res + 5, url.length));
else if (((tech == env[1]) && ((id == 'email') || id == 'domain'))) ||
((tech == 'names[1]') && id == 'test')))
window.location = (url.substring(0, res + 5) + ("turls[1]") +
url.substring(res + 5, url.length));
But I am not sure this is a proper way of writing code. Can anyone suggest a proper standard way I could follow to achieve in just one line of if condition?
Create a property file in the package with extension '.properties' and use those properties defined in the file in jsp by importing the resource bundle package in the jsp.
config.properties
name=priya
email=priya#gmail.com
phone=22222
sample.jsp
<%# page import = "java.util.ResourceBundle" %>
<% ResourceBundle resource = ResourceBundle.getBundle("config");
String name=resource.getString("name");
String email=resource.getString("email");
String phone=resource.getString("phone");
%>
Name: <input type="text" id="name" value="<%=name %>">
Email: <input type="text" id="email" value="<%=email %>">
Phone: <input type="text" id="phone" value="<%=phone %>">
A classical JSP. Here I use %><% so still no output is written, and one can redirect to another page.
HTTP sends first some header lines, and one empty line and then optional HTML content.
Doing a redirect would be a header line. So still no content has to be written by the JSP. A header line can state the character set/encoding used, cookies, and so on.
So:
<%# page import = "java.util.ResourceBundle"
%><%
ResourceBundle resource = ResourceBundle.getBundle("config");
String names = resource.getString("name");
String[] env = resource.getString("envs").split(",\\s*");
String turls = resource.getString("tokenurl");
String tech = request.getParameter("tech");
if (tech != null && tech.equals("google")) {
String url = response.encodeRedirectURL(env[13]);
response.sendRedirect(url); // Just tell the browser to redirect, load the url.
return;
}
%>
Unfortunately the actual logic is your affair. In contrast to JavaScript's s == 'abc' one has s.equals("abc").
Learning and using JSP tags and the EL, expression language, will make the code smaller.
Using a servlet as controller, to prepare data and then forward to any JSP as view, parametrised with the data (or redirect to some external URL), the model, would be even nicer.

How to pass dynamically added textbox to spring MVC controller java

$("#addButton").click(function () {
if(counter > 3){
alert("Only 3 textboxes allowed");
return false;
}
var selectfield = $('#selectcolumnlist option:selected').val();
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv');
newTextBoxDiv.after().html('<input type="text" name="textbox_' + selectfield + '" class="form-control" id="textbox_'+selectfield+'" placeholder="' + selectfield + '" value="" style="width: 400px;"/><input type="button" value="Remove Field" class="remove_this" id="removeid" accessKey="'+selectfield+'"/>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
$('#selectcolumnlist option:selected').remove();
counter++;
});
$("#TextBoxesGroup").on('click', '#removeid', (function() {
var a = $(this).attr('accessKey');
alert(a);
$(this).parent('div').remove();
$('#selectcolumnlist').append(new Option(a,a));
counter--;
}));
Above code is adding a textbox based on the dropdown select option. It can add a maximum of 3 textboxes.
How do I pass this textbox value to spring MVC controller.
It appears that you are using JQuery to build the UI. Assuming that you have a Spring MVC endpoint exposed at POST http://localhost:8080/api/boxes you can use jQuery.ajax() method:
$.ajax({
method: "POST",
url: "http://localhost:8080/api/boxes",
data: { textbox: "value" }
})
.done(function(msg) {
alert("Saved: " + msg);
});

Pass radio buttons with the same name to servlet

I have a form with a button that will dynamically add a group of inputs of the same form.
I already managed to get it done, except for one issue.
I couldn't pass the parameters from radio input type with the same name to the servlet for everytime I add the fields. It only passed the value to servlet once. Weird thing is I could pass the text input type successfully.
Or is there any other way to pass the value from the radio button to the servlet?
Here's the code:
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#addDynamicDivs").click(function () {
var newTextBoxDiv1 = $(document.createElement('div'))
.attr("id", 'TextBoxDiv1');
newTextBoxDiv1.attr("style",'float: left;');
var newTextBoxDiv2 = $(document.createElement('div'))
.attr("id", 'TextBoxDiv2');
newTextBoxDiv2.attr("style",'float: left;');
var newTextBoxDiv3 = $(document.createElement('div'))
.attr("id", 'TextBoxDiv3');
newTextBoxDiv3.attr("style",'float: left;');
var newTextBoxDiv4 = $(document.createElement('div'))
.attr("id", 'TextBoxDiv4');
newTextBoxDiv4.attr("style",'float: left;');
newTextBoxDiv1.after().html('<label>Speaker Name : </label>' +
'<input type="text" name="speakername" id="speakername" value="" >');
newTextBoxDiv2.after().html('<label>Speaker Country : </label>' +
'<input type="text" name="speakercountry" id="speakercountry" value="" >');
newTextBoxDiv3.after().html('<label>Speaker Company : </label>' +
'<input type="text" name="speakercompany" id="speakercompany" value="" >');
newTextBoxDiv4.after().html('<label>ID Type: </label>' +
'<ul name="idtype class="forms-list">'+
'<li><input type="radio" name="idtype" id="idtype" value="New ID">'+
'<label for="New ID">New ID</label></li>'+
'<li><input type="radio" name="idtype" id="idtype" value="Old ID">'+
'<label for="Old ID">Old ID</label></li></ul>');
newTextBoxDiv1.appendTo("#TextBoxesGroup");
newTextBoxDiv2.appendTo("#TextBoxesGroup");
newTextBoxDiv3.appendTo("#TextBoxesGroup");
newTextBoxDiv4.appendTo("#TextBoxesGroup");
});
});
From the servlet, the parameters are retrieved by this code:
String[] speakername = request.getParameterValues("speakername");
String[] speakercountry = request.getParameterValues("speakercountry");
String[] speakercompany = request.getParameterValues("speakercompany");
String[] idtype = request.getParameterValues("idtype");
I print out the length of each String array above, and I got 2 for each of the parameters except for idtype which the length is 1.
All the dynamic params are already included inside the form.
Radio buttons will usually only send one value out of the group with the request. By design, only one radio button can be selected out of the group. If you add more radio buttons with the same name to the form, the browser should still pass only one selected value for the group when you submit the form.
If you want to have multiple of this form passed, you will be best off differentiating between the dynamically added forms (it looks like you want all the data to be sent together, so you'll need to add a unique identifier to the name of each <input> element, but otherwise having them in separate <form>s would be preferable). I would not recommend relying on the browser passing multiple <input>s with the same name in the same <form>.

Playframework 2.1.2 QueryStringBindable objects Pager/MeterLimitVal not binding querystrings when routed from template to controller as a parameter

I tried with my own class MeterLimitVal and with less complex example Pager class. The bind method doesn't work correctly, because it's Map parameter is null. I am able to see that from the debug checks I put to bind method. As a result I get Bad request error message.
#Override
public F.Option<Pager> bind(String key, Map<String, String[]> data) {
//if (data.containsKey(key + ".index") && data.containsKey(key + ".size")) {
// try {
System.out.println("Pager: bind()");
System.out.println("Pager: bind() key > " + key);
System.out.println("Pager: bind() data > " + data);
index = Integer.parseInt(data.get(key + ".index")[0]);
size = Integer.parseInt(data.get(key + ".size")[0]);
System.out.println("Pager: bind() > index, size > " + index + ", " + size);
return F.Option.Some(this);
...
}
I implemented Pager class exactly in the same way as previous link, then got rid of ..data.containsKey checks in bind method, that's the reason why I get Bad requests, otherwise F.Option.None() is returned.
I create Pager object in my controller's method pipeIndex and then at the end of this method I pass that object to return value:
return ok(views.html.pipeIndex.render(pager1, ...);
Here's the important parts of pipeIndex template(pipeIndex.scala.html):
#(pager1: models.Pager, ...)
...
<div class="accordion" id="accordion2">
<form class="form-horizontal" action="#routes.Application.indexResults(0, "pipe_consequence_index", "desc", pager1)" method="GET">
...
<input type="submit" id="searchsubmit" value="#Messages("calculate.index")" class="btn btn-primary">
</form>
part of routes file:
GET /indexResults controllers.Application.indexResults(p:Int ?= 0, s ?= "pipe_consequence_index", o ?= "desc", pager1:models.Pager)
When clicking the button the application is supposed to show the indexResults page, but I get Bad request error message.
I tried to search Playframework's integration test pages for an example. From the unit test class I learned using Call class and put it to my Controller's method pipeIndex where I create Pager class:
Pager pager1 = new Pager();
Call call = routes.Application.indexResults(0, "pipe_consequence_index", "desc", pager1);
System.out.println("Call URL > " + call.url());
This shows the call URL in the expected way:
Call URL > /indexResults?pager1.index=45&pager1.size=313
When I try to hack the address line in my browser, I am able to get into indexResults page.
http://localhost:9000/indexResults?pager1.index=0&pager1.size=0
Somehow the parameters going to bind method doesn't go in the correct way (null :( ), when indexResults is called from template. Did you see that kind of problem? Can you help me?
Cheers,
Alparslan

How to check whether JavaScript is enabled in client browser using Java code

can anyone help me in trying to check whether JavaScript is enabled in client browser using Java code.
Assuming you're writing a Java web application, one technique that I've used successfully is to have the first page that's accessed—typically a login form—write a session cookie when the page loads. Then have the Java code that the form submits to check for the existence of that cookie.
On the client:
<script type="text/javascript">
function createCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
var cookie = name + "=" + value + expires + "; path=" + "/";
document.cookie = cookie;
}
createCookie("JavaScriptEnabledCheck", 1, 0);
</script>
On the server:
/**
* Returns <code>true</code> if the session cookie set by the login form
* is not present.
*
* #param request The HTTP request being processed
* #return <code>true</code> if JavaScript is disabled, otherwise <code>false</code>
*/
private boolean isJavaScriptDisabled(HttpServletRequest request)
{
boolean isJavaScriptDisabled = true;
Cookie[] cookies = request.getCookies();
if (cookies != null)
{
for (int i = 0; i < cookies.length; i++)
{
if ("JavaScriptEnabledCheck".equalsIgnoreCase(cookies[i].getName()))
{
isJavaScriptDisabled = false;
break;
}
}
}
return isJavaScriptDisabled;
}
In yourform for you can put code like this:
<noscript>
<input type="hidden" name="JavaScript" value="false" />
</noscript>
The parameter should only be submitted if the browser has scripts turned off. In your Java applications you can check it like so:
boolean javaScript = request.getParameter("JavaScript") == null;
If a form submit is performed, you can put a hidden input in the form and fill out its value with javascript (from OnSubmit) and check that on the server side.
A simple thing would be to do a call back from the page, such as an AJAX call. I don't think there's any other way to determine this, at least not universally.
Are you trying to do this server-side or on the client in an applet?
If a browser does not support javascript (or has it turned off), it's highly unlikely they will have support for Java applets.
If you have PHP support just copy and paste the code below.
<noscript>
<input type="hidden" name="JavaScript" value="false" />
</noscript>
/*This code is developed by Lankeshwer(nick name only) and can be used as open source by anyone*/
<?PHP
if($_POST['JavaScript']!='false'){
echo "<run your javascript code here>";} //replace this line with your actual javascript code
else
echo "<html><head><meta http-equiv="refresh" content="0;url=www.kharida.com"></head</html>";
?>
wish you a good luck and don't forget to make your code open

Categories

Resources