Getting all parameters in Servlets from HTML form - java

I have aN HTML form where I have check boxes. In the Servlet, I am trying to print all the Parameter names with Values and In case it has no value i.e it's unchecked , print "BLANK", But surprisingly, the parameter itself is not printed if it has no value/is unchecked.Follows the code:
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n<td>");
String[] paramValues = request.getParameterValues(paramName);
if(paramValues.length == 0)
out.println("BLANK"); //Why does this not work?
// Read single valued data
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0)
out.println("<i>No Value</i>");
else
out.println(paramValue);
}
else {
// Read multiple valued data
out.println("<ul>");
for(int i=0; i < paramValues.length; i++) {
out.println("<li>" + paramValues[i]);
}
out.println("</ul>");
}
}
out.println("</tr>\n</table>\n</body></html>");
}

The checkboxes that are NOT checked in a form post are NOT sent as parameters. Only checked checkboxes are posted in the HTTP POST request.
If you want to post the "unchecked" check boxes, you will have to emply a small hack. Please refer this SO post.

Instead of manually looking for each property Use JSTL
tags , where you can just specify the java class and with same field name as in form and values directly maps to the bean

Related

JSP - ArrayList in session attribute null

I am trying to store some data in a arraylist in each users session however when I try and grab the list it is apparently null...
Code:
<%
List<String> attacks = new ArrayList<>();
if (request.getSession().getAttribute("attackList") != null){
attacks = (List<String>) request.getAttribute("attackList");
int x = 1;
for (String attack : attacks){
String[] attacc = attack.split(":");
out.print("" +
"<tr>\n" +
" <th scope=\"row\">"+x+"</th>\n" +
" <td>"+attacc[0]+"</td>\n" +
" <td>"+attacc[1]+"</td>\n" +
" <td>"+attacc[2]+"</td>\n" +
" <td>"+attacc[3]+"</td>\n" +
" </tr>");
x++;
}
}else{
out.print("empty");
}
%>
That ^ is the code I am using to fetch the data, it is printing "empty", so its essentially null...
How I am adding the data:
if (request.getAttribute("attackList") != null) {
attacks = (List<String>) request.getAttribute("attackList");
request.removeAttribute("attackList");
}
attacks.add("data here");
request.setAttribute("attackList", attacks);
I have not tried anything due to me not knowing what to try here.
First, I suggest you, if it is possible, you can start working with expression language, instead of jsp directly, because turn your code more readable.
Look your problem, do you want to work with a List in a Request our a Session scope?
I ask because sometimes you get your list from request scope but your IF is verifying the Session.
And at no time are you adding your list to the session.
You could do this, after your logic, with:
request.getSession().setAttribute("attackList", attacks);
Here is more about session methods:
https://beginnersbook.com/2013/11/jsp-implicit-object-session-with-examples/

How can I retrieve HttpServletRequest data while using Jersey

I know that this is an easy one if I am not using Jersey and would use something like this:
Enumeration<String> params = request.getParameterNames();
while(params.hasMoreElements()){
String paramName = (String)params.nextElement();
System.out.println("Parameter Name - "+paramName+", Value - "+request.getParameter(paramName));
}
params = request.getHeaderNames();
while(params.hasMoreElements()){
String paramName = (String)params.nextElement();
System.out.println("Header Name - "+paramName+", Value - "+request.getHeader(paramName));
}
params = request.getAttributeNames();
while(params.hasMoreElements()){
String paramName = (String)params.nextElement();
System.out.println("Attribute Name - "+paramName+", Value - "+request.getAttribute(paramName));
}
I am also aware that I can do this and be done with it.
#FormParam("location") String location
But what if I do want to dump all the contents of the form submitted via POST?
The problem is that I am using Jersey as the implementation of JAX-RS and using the code above outputs this:
Attribute Name - org.glassfish.jersey.server.spring.scope.RequestContextFilter.REQUEST_ATTRIBUTES, Value - org.glassfish.jersey.server.spring.scope.JaxrsRequestAttributes#11e035a
Attribute Name - org.glassfish.jersey.message.internal.TracingLogger, Value - org.glassfish.jersey.message.internal.TracingLogger$1#16e45c8
I am guessing that my data is contained here: JaxrsRequestAttributes I am not sure though.
I know I am missing something here. This isn't supposed to be difficult isn't it?
UPDATE
As suggested Sotirios,
This is the code get the dump of the form.
try {
InputStream is = request.getInputStream();
int i;
char c;
while((i=is.read())!=-1)
{
// converts integer to character
c=(char)i;
// prints character
System.out.print(c);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
In order for this to work, I had to remove #FormParam in my parameter and leave out #Context HttpSerlvetRequest request.
Are there no other way to output this in a more elegant way with out the need to remove #FormParam? Maybe get the values from JaxrsRequestAttributes?
I tried to create a variable JaxrsRequestAttributes but it's a default class a can not access it directly.
Based on Sotirios comment's, here's the answer:
Here's the method signature
public Response authenticateUser(MultivaluedMap<String, String> form)
Iterator<String> it = form.keySet().iterator();
while(it.hasNext()){
String theKey = (String)it.next();
System.out.println("Parameter Name - "+theKey+", Value - "+form.getFirst(theKey));
}
System.out.println(form);
The HttpServletRequest can be accessed using :
#Context
private HttpServletRequest request;
Isn't that enough?

Passing multiple values from Servlet to JSP but I get only 1 value in JSP

I am trying to pass both latitude and longitude values from a Servlet to a JSP but I get only 1 value in the JSP
Servlet page
for(int i=0;i<json.length();i++)
{
String lat=json.getJSONObject(i).get("lat").toString();
String lon=json.getJSONObject(i).get("lon").toString();
lats[i]=lat;
lons[i]=lon;
request.setAttribute("lats", lats[i]);
request.setAttribute("lons", lons[i]);
System.out.println(lats[i]+","+lons[i]);
}
JSP page
var len=<%=request.getAttribute("len")%>;
lats[0]=<%=request.getAttribute("lats")%>;
<% String[] lats=(String[]) request.getAttribute("lats");%>
<% String[] lons=(String[]) request.getAttribute("lons");%>
for(i=0;i<len;i++)
{
var locations =[
['<%=request.getAttribute("cid")%>',lats,lon]
];
alert(locations);
}
Where am I going wrong?
As currently written, you overwrite the 2 request attributes (lats and lon) at each iteration. A request attribute is not a magic container, but the simple object last used in addAttribute. So in you JSP, you later only get the value of last lats and lon.
Assuming lats and lon and arrays in your code, you should write :
for(int i=0;i<json.length();i++)
{
String lat=json.getJSONObject(i).get("lat").toString();
String lon=json.getJSONObject(i).get("lon").toString();
lats[i]=lat;
lons[i]=lon;
System.out.println(lats[i]+","+lons[i]);
}
request.setAttribute("lats", lats);
request.setAttribute("lons", lons);
To put the arrays in the request attributes.
Then in the JSP ${lat} and ${lon} will refer to the arrays, and you can use ${lat[O]}, or ${lat[i]}, provided for last expression that i is a scoped variable containing a integer value less than array size.
You should pass Hashtable from servlet to JSP.
Servlet
HashMap latsMap = new HashMap();
HashMap lonMap = new HashMap();
for(int i=0;i<json.length();i++)
{
String lat=json.getJSONObject(i).get("lat").toString();
String lon=json.getJSONObject(i).get("lon").toString();
lats[i]=lat;
lons[i]=lon;
latsMap.put("lats"+i,lats[i]));
lonMap.put("lons"+i,lons[i]));
System.out.println(lats[i]+","+lons[i]);
}
//You can put these as Session attribute also
request.setAttribute("lats", latsMap);
request.setAttribute("lons", lonMap);
JSP
<% HashMap latsMap==(HashMap)request.getAttribute("lats");
HashMap lonMap=(HashMap)request.getAttribute("lons");
int len = latsMap.size();
for(int i=0;i<len;i++)
{
String lats = latsMap.get("lats"+i);
String lon= lonMap.get("lons"+i);
String locations ="[['"+request.getAttribute("cid")+"',"+lats+","+lon+"]]";
//If request.setAttribute("cid",<SomeValue>); is not present in servlet then
//remove request.getAttribute("cid") from JSP , Change it to
//String locations ="[,"+lats+","+lon+"]]";
out.println(locations);
}
%>
Try like follows:
for(int i=0;i<json.length();i++) {
String lat=json.getJSONObject(i).get("lat").toString();
String lon=json.getJSONObject(i).get("lon").toString();
lats[i]=lat;
lons[i]=lon;
System.out.println(lats[i]+","+lons[i]);
}
request.setAttribute("lats", lats[i]);
request.setAttribute("lons", lons[i]);
This is what i have done to store coordinates..
<% Integer len =(Integer)request.getAttribute("len");
int ilen =len.intValue();
String[][] locations =new String[ilen][3];%>
<% String[] lats=(String[]) request.getAttribute("lats");
String[] lons=(String[]) request.getAttribute("lons");
for(int i=0;i<ilen;i++)
{
System.out.println("i = "+i+", latlong= "+lats[i]+","+lons[i]);
locations[i][0] = (String) request.getAttribute("cid");
locations[i][1] = lats[i];
locations[i][2] = lons[i];
}
%>
with this can u provide me some help with the markers..

how to extract a value of variable from a javascript function in the html page while parsing an html page

I have to parse an html page. I have to extract the value of the name element in the below html which is assigned to a javascript function. How do I do it using JSoup.
<input type="hidden" name="fields.DEPTID.value"/>
JS:
departmentId.onChange = function(value) {
var departmentId = dijit.byId("departmentId");
if (value == null || value == "") {
document.transferForm.elements["fields.DEPTID.value"].value = "";
document.transferForm.elements["fields.DEPTID_DESC.value"].value = "";
} else {
document.transferForm.elements["fields.DEPTID.value"].value = value;
document.transferForm.elements["fields.DEPTID_DESC.value"].value = departmentId.getDisplayedValue();
var locationID = departmentId.store.getValue(departmentId.item, "loctID");
var locationDesc = departmentId.store.getValue(departmentId.item, "loct");
locationComboBox = dijit.byId("locationId");
if (locationComboBox != null) {
if (locationID != "") {
setLocationComboBox(locationID, locationDesc);
} else {
setLocationComboBox("AMFL", "AMFL - AMY FLORIDA");
}
}
}
};
I'll try to teach you form the top:
//Connect to the url, and get its source html
Document doc = Jsoup.connect("url").get();
//Get ALL the elements in the page that meet the query
//you passed as parameter.
//I'm querying for all the script tags that have the
//name attribute inside it
Elements elems = doc.select("script[name]");
//That Elements variable is a collection of
//Element. So now, you'll loop through it, and
//get all the stuff you're looking for
for (Element elem : elems) {
String name = elem.attr("name");
//Now you have the name attribute
//Use it to whatever you need.
}
Now if you want some help with the Jsoup querys to get any other elements you might want, here you go the API documentation to help: Jsoup selector API
Hope that helped =)

DisplayTag Sort and Pagination links(url) generated is too long

When using displaytag the URL it's generating for paging and sorting is too long for IE.
Is there a way around this without resorting to external paging and sorting?
Cheers.
Hopefully this will help someone. And if there is another way, then let me know.
The way I have got round this is by excluding all parameters on the display table tag.
<display:table excludedParams="*"> ... </display:table>
Which means the url doesn't fill up with parameters.
Great, but how do you keep a handle on the list of objects that we're using?
I did this by setting an attribute on the context's request. And as I'm using the Stripes framework I did this by using the ActionBeanContext.
public class SchemeActionBeanContext extends ActionBeanContext {
public void setThings(List<Things> things) {
getRequest().getSession().setAttribute("stuff", things);
}
public List<Things> getThings() {
return (List<Things>)getRequest().getSession().getAttribute("stuff");
}
And then you can set and get them throughout the lifecycle of the page/request.
I was facing a similar issue where url with all the form fields were getting appended to url during pagination and sorting. This was resolved by identifying all the pagination links mentioned below by either the unique title that it forms (Go to page ) and the inner htmls such as 'Next' 'Prev' etc it forms.
The javascript params in the method below are explained here
1) head1/head2 - sorting column names passed.
2) formName - name of the form,
3) masterName - the method called in your controller
I have a logic on an input box named 'strNamesearch' on the basis of which my calling method changes.
Also note, once you do this, don't forget to add excludedParams="*" in display:table tag
Here is the code:
function findAnchorGen(head1,head2,formName,masterName) {
var formObj = eval("document."+formName);
var methodName;
var strSearch = trim(formObj.strNamesearch.value);
if(strSearch == null || strSearch == '') {
methodNameP = "fetch"+masterName;
} else {
methodNameP = "search"+masterName;
}
var anchors = document.links; // your anchor collection
var i = anchors.length;
while (i--) {
var a = anchors[i];
var aRef = a.href;
var aTitle = a.title;
index = aTitle.indexOf("Go to page");
var inHtml = a.innerHTML;
if(index >= 0 || inHtml == 'Last' || inHtml == 'Next' || inHtml == 'First' || inHtml == 'Prev' || inHtml == head1 || inHtml == head2) {
//alert("Ref = " + aRef + " | title = " + aTitle + " | inner html = " + a.innerHTML);
a.href="#";
a.onclick = (function(aRef,formName,methodNameP){return function(){fSubmit(aRef,formName,methodNameP);}})(aRef,formName,methodNameP);
}
}
}
function fSubmitGen(aRef,formName,methodNameP) {
var formObj = eval("document."+formName);
formObj.action = aRef;
formObj.method.value = methodNameP;
formObj.submit();
}
This is a workaround and is working well for us. I hope it works for you too.

Categories