Servlet not forwarding attributes to JSP (JSP receives null) - java

Servlet
ArrayList<String[]> itemsInCart = new ArrayList<String[]>();
String[] test = {"bah","3.50","false"};
itemsInCart.add(test);
ArrayList<Integer> testALEmpty = new ArrayList<>();
ArrayList<Integer> testALItems = new ArrayList<>();
testALItems.add(1);
testALItems.add(2);
testALItems.add(3);
String testStr = "This is a test string";
request.setAttribute("testALEmpty", testALEmpty);
request.setAttribute("testALItems", testALItems);
request.setAttribute("testStr", testStr);
request.setAttribute("cartAttribute", itemsInCart);
try {
getServletContext().getRequestDispatcher("/Cart.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
JSP
if (request.getAttribute("cartAttribute") == null) {
%>
<b>No Cart</b>
<%
}
When the servlet forwards to the JSP, I have No Cart because for some reason the servlet is not passing the attributes to the JSP.

set request attribute to session attribute:
request.getSession().setAttribute("parameter", "test");
or
There are two ways you can accomplish this.
Using a JSP expression you would use <%= %> as (notice no ; at the end)
<%= parameter %>
The second and preferred way is to use JSP EL syntax and reference the request attribute directly using ${ } as
${parameter}
The first option requires you to pull the attribute out of its scope first. The second doesn't.
String parameter = (String) request.getAttribute("parameter");

Related

Not able to retrieve value returned by parameterzied method in jsp page

I have to put parameter in method defined in bean as.The parameters are static.I did this in jsp page as-
<%
String n= "p49_readback";
ref.getDbTable(n);
%>
Through this I'm getting value in java bean method and the method is
public String getDbTable(String parameter)
{
String tolerance =null;
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();//Holds the beamline name and status
try
{
con = getConnection();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
String sql="select Tolerance from Reference.dbo.Set_range where Parameter_Name='"+parameter+"'";
System.out.println("sql "+sql);
stmt.executeQuery(sql);
rs = stmt.getResultSet();
while(rs.next())
{
tolerance= (rs.getString(1));
System.out.println("value of tolerance is "+tolerance);
}
}
catch( Exception e )
{
System.out.println("\nException in getDbTable "+e);
}
finally
{
closeConnection(stmt, rs, con);
}
return tolerance;
Now I want to call this method in jsp and store its value into a variable.But I'm not able to retrieve or call this method in jsp page .
I tried as
<c:set value="${ref.getDbTable(param.p49_readback)}" var="db"></c:set>
But its a wrong approach,I'm not getting value returned by the method.How to do that?
If you are using plain JSPs, you could just do this...
<%
String n= "p49_readback";
String reference = ref.getDbTable(n);
%>
Now anywhere you want to use this, just do...
<%=reference%>
You could even do...
<%
String n= "p49_readback";
String reference = ref.getDbTable(n);
%>
<c:set var="reference" value="<%=reference%>"/>

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 pass array from java to javascript

I want to pass a String Array From java to javascript. How can i acheive the same.
using loadUrl, i am passing the Java String [] to a javascript Function. (String[] StringName--> ["hello", "hi"])
But when i try to access the same in javascript
function displayString(StringName) {
for(var i=0;i<StringName.length;i++) {
alert("path : " + StringName[i]);
}
}
i am expecting length to be 2 as there are only 2 items in the Java String[].
But in javascript it is cominng as a String.
Whatformat i have to use to get it as an array
Two ideas come to my mind. You can create a javascript array using jsp or you can use a separator for the java array and create into a string, then read back in javascript using split() on the string.
Method 1:
<% String array[] = // is your initialized array %>
<script>
var jsArray = new Array();
<% for(String element:array){
%> jsArray[jsArray.length] = <% element %>
<% } %>
</script>
This should create a ready to use Javascript array with the values contained in your Java array.
Method 2: (Using separator as #)
<% StringBuilder sb = new StringBuilder();
for(String element:array){
sb.append(element + "#");
}
%>
<script>
var temp = <% sb.toString() %>
var array = temp.split('#');
...
</script>
Java to JSON and JSON to Java is fairly well covered ground.
you should check this out.
https://stackoverflow.com/questions/338586/a-better-java-json-library
<%
String[] jArray= new String[2];
jArray[0]="a";
jArray[1]="b";
StringBuilder sb = new StringBuilder();
for(int i=0;i<jArray.length;i++)
sb.append(jArray[i]+",");
%>
<script type="text/javascript">
temp="<%=sb.toString()%>";
var array = new Array();
array = temp.split(',','<%=jArray.length%>');
alert("array: "+array);
</script>

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 =)

getParameter only returning part of the string

Kindly assist here, the getParameter is only printing the first portion of the String element in the tag.
here is the select tag
<select name="ActionSelect" id="ActionSelect" >
<%Iterator itr;%>
<% List data = (List) request.getAttribute("data");
for (itr = data.iterator(); itr.hasNext();) {
String value = (String) itr.next();
%>
<option value=<%=value%>><%=value%></option>
<%}%>
</select>
and here is the code in the servlet
PrintWriter pw = response.getWriter();
String connectionURL = "jdbc:mysql://localhost/db";
Connection connection;
try{
this.ibrand = request.getParameter("ActionSelect");
pw.println(ibrand);
} catch (Exception e) {
pw.println(e);
}
Use double quotes around value in the option tag:
<option value="<%=value%>"><%=value%></option>
As it is right now, you probably have a space in your value so only the part of the value before space is returned.
Incidentally, it's not necessary to declare the Iterator uptop; you can do so directly in the for loop:
for (Iterator itr = data.iterator(); itr.hasNext();) {
Finally, consider using tag libraries instead of writing java code directly as scriptlets in your JSP.

Categories