What actually means "value" in JSP? - java

I have read JSP recently, and have a doubt in the javabeans technolgy it uses. Lets say that the following JavaBeans code :
package mortgage;
public class Mortgage
{
private double amount = -1.0;
public void setAmount(double amount)
{
this.amount = amount;
}
}
And lets say i have to make use of this JavaBeans in my JSP and take the parameter values obtain from the HTML form or from the URL query string and JSP code as follows:
<jsp:useBean id="calc" class="mortgage.Mortgage" />
<p> Testing . . .
<c:set target="${calc}" property="amount" value="${param.mortgageAmount}" />
. . . . .
This example was little modified from my book. My question is what does this value in the above code JSP does? Where does the mortgageAmount came from?(is this the value from the HTML form element?)
And also what does target and property does?
Since I am a novice, i dont know what actually is going on the above code. Please help me and correct me if am wrong?

value represents expression that would be set to the target
Where does the mortgageAmount came from?
it assumed to be coming as param as you have used it in your code by param.mortgageAmount in url like
yourapp/page.jsp?mortgageAmount=someVAlue
In Simlper words
value is and Expression to be evaluated which will be set to
target object's property represented by property
See Also
Javadoc

param is a JSP implicit object. It's a map whose entries are the page parameters - so anything that's come in as a parameter in the query string, or (i think) through a form post.
Target and property govern what the c:set does; it sets the named property on the named target object to the given value.

Related

How to replace a query string in an Apache Velocity template?

In my web application I'm trying to prevent users from inserting JavaScript in the freeText parameter when they're running a search.
To do this, I've written code in the header Velocity file to check whether the query string contains a parameter called freeText, and if so, use the replace method to replace the characters within the parameter value. However, when you load the page, it still displays the original query string - I'm unsure on how to replace the original query string with my new one which has the replaced characters.
This is my code:
#set($freeTextParameter = "$request.getParameter('freeText')")
freeTextParameter: $freeTextParameter
#if($freeTextParameter)
##Do the replacement:
#set($replacedQueryString = "$freeTextParameter.replace('confirm','replaced')")
replacedQueryString after doing the replace: $replacedQueryString
The query string now: $request.getQueryString()
The freeText parameter now: $request.getParameter('freeText')
#end
In the code above, the replacedQueryString variable has changed as expected (ie the replacement has been carried out as expected), but the $request.getQueryString() and $request.getParameter('freeText') are still the same as before, as if the replacement had never happened.
Seeing as there is a request.getParameter method which works fine for getting the parameters, I assumed there would be a request.setParameter method to do the same thing in reverse, but there isn't.
The Java String is an immutable object, which means that the replace() method will return an altered string, without changing the original one.
Since the parameters map given by the HttpServletRequest object cannot be modified, this approach doesn't work well if your templates rely on $request.getParameter('freeText').
Instead, if you rely on VelocityTools, then you can rather rely on $params.freeText in your templates. Then, you can tune your WEB-INF/tools.xml file to make this parameters map alterable:
<?xml version="1.0">
<tools>
<toolbox scope="request">
<tool key="params" readOnly="false"/>
...
</toolbox>
...
</tools>
(Version 2.0+ of the tools is required).
Then, in your header, you can do:
#set($params.freeText = params.freeText.replace('confirm','replaced'))
I managed to fix the issue myself - it turned out that there was another file (which gets called on every page) in which the $!request.getParameter('freeText')" variable is used. I have updated that file so that it uses the new $!replacedQueryString variable (ie the one with the JavaScript stripped out) instead of the existing "$!request.getParameter('freeText')" variable. This now prevents the JavaScript from being executed on every page.
So, this is the final working code in the header Velocity file:
#set($freeTextParameter = "$!m.request.httpRequest.getParameter('freeText')")
#if($freeTextParameter)
#set($replacedQueryString = "$freeTextParameter.replace('confirm','').replace('<','').replace('>','').replace('(','').replace(')','').replace(';','').replace('/','').replace('\"','').replace('&','').replace('+','').replace('script','').replace('prompt','').replace('*','').replace('.','')")
#end

NullPointerException when iterating over ArrayList in jsp

I am displaying a list which contains objects which store message information. The list is loaded through getting the request as such:
ArrayList<MessageModel> list = (ArrayList<MessageModel>) request.getAttribute("msgList");
I am trying to display information contained in each object as such:
for(MessageModel msg : list){
String messageTo = msg.toAddress;
String messageSub = msg.messageSubject;
out.println(messageTo+ " " +messageSub);
}
I am getting a NullPointerException at the for each statement.
As an aside, I am using this approach to debug as I want to check whether or not I can display the content of the MessageModel object at all. I tried using JSTL forEach tag but I could not access the object attributes.
<c:forEach items="${list}" var="current">
<li><c:out value="${current.toAddress}"/></li>
</c:forEach>
I set the attribute like this :
ArrayList<MessageModel> list =(ArrayList<MessageModel>) request.getAttribute("msgList");
pageContext.setAttribute("messages", list);
This results in the following error message when run :
org.apache.jasper.JasperException: /inbox.jsp (line: 37, column: 12) According to TLD or attribute directive in tag file, attribute items does not accept any expressions
And intelliJ says that it cannot resolve the variable list.
EDIT :
I forward the request from a servlet that handles user login as follows :
ArrayList<MessageModel> msglist = MessageModel.getRecievedMessages(username);
request.setAttribute("msgList", msglist);
I am trying to pass the ArrayList that contains the message objects and then iterate over the list and display it in the jsp.
Is there a possibility for the jsp itself to get the information ? I have a separate java class which handles the messages with a bunch of helper functions. So can I call the method that retrieves all those messages and display them without explicitly setting a request attribute in the servlet ? Because I will be navigating between other pages in the application.
Sorry if my vocabulary was off, this is the first time I am working with jsp's and servlets.
The NullPointerException in the foreach loop is probably due to the list variable being null. You may check for listnot being null before iterating over it.
Regarding the JasperException, can you describe how you forward to the JSP ?
Also, it's probably a typo, but you set an attribute named messages, then you iterate over an attribute named list in the <c:foreach>...
I solved this problem by using creating getter and setter methods to get the class members of MessageModel.
EL tag wiki: this article helped me understand how to interface a java class and a jsp.

JSP Request Parameter truncated after passing to javascript function

I have an issue with a parameter that I'm trying to pass into a Javascript function where the parameter gets cut off.
In my Servlet, I have set a parameter request.setAttribute("questions", service.getQuestions("123"))
It sets a list of questions with each question containing several values;
I loop through them with a JSTL loop <c:forEach var="data" items="${questions}">...</c:forEach> which I can then access the values as so ${data.question}, ${data.options} etc.
console.log(${data.question}) returns a value of the form 123,45,35|43,94,73|23,91,34 which is as expected.
But when I try to pass this ${data.question} into a javascript function such as <script>MyFunction(${data.question})</script>, it only receives 123.
MyFunction(data) {
console.log(data); //Only shows 123
//Split the string into arrays for processing
}
You receive first element becouse your function expect one parameter, and your value 123,45,35|43,94,73|23,91,34 is split by comma so it looks for function like diferent parametrs. Use arguments property insted or pass all value as string in '' like this
<script>MyFunction('${data.question}')</script>
Sorry for my english.. still working on it

Passing nullable parameters to a Page via PageParameters in Wicket 6

I need to pass a parameter to my page and I can't find a way to pass parameters that might be null.
If I do:
PageParameters pageParameters = new PageParameters ();
pageParameters.add ("key", null);
This will result in an exception
java.lang.IllegalArgumentException: Argument 'value' may not be null.
at org.apache.wicket.util.lang.Args.notNull(Args.java:41)
If I use Google Guava's Optional, I can't find any way to cast the object even if the the Optional object is not holding a null ie not equals to Optional.absent() :
In my landing page's constructor I do
StringValue sv = parameters.get ("key");
sv.to ( Optional.of (MyEnum.SOME_ENUM_CONSTANT).getClass () );
and when I run it I get this error:
org.apache.wicket.util.string.StringValueConversionException: Cannot
convert 'Optional.of(SOME_ENUM_CONSTANT)'to type class
com.google.common.base.Present.
Am I doing something wrong?
Is there any other way to pass a possibly null object in wicket 6?
I noticed in wicket 1.4 they have PageParameters.NULL which seems to have dissapeared in wicket 6.
Thank you
This might be too simple, but what's wrong with
Object value = ?
if (value != null) {
pageParameters.add ("key", value);
}
and
StringValue sv = pageParameters.get("key");
if (!sv.isNull()) {
// process string value
}
All page parameters in wicket will be treated as Strings eventually. The idea is that a page parameter will be on the URL of the request.
From the javadoc:
Suppose we mounted a page on /user and the following url was accessed /user/profile/bob?action=view&redirect=false. In this example profile and bob are indexed parameters with respective indexes 0 and 1. action and redirect are named parameters.
If you add something like x=y&x, the parameter x will appear twice, once with the String y and another with the empty string.
Depending on what you are trying to accomplish I would suggest to either
Don't pass the parameter at all when there is a null value required and use the isNull or toOptional methods.
Use indexed parameters and test for presence of a certain word

Storing integer as attribute in jsp

I want to pass an Integer value as an attribute in JSP. But when i try
int i = Integer.parseInt(request.getAttribute("count"));
an error is returned. Could you tell me a method to store Integer numbers as attributes in JSP?
I am getting a casting error saying parseInt() is not suited for handling objects.
request.getAttribute returns an Object. you need to cast this to String like this:
Integer.parseInt((String)request.getAttribute("count"));
To access the request in a JSP use request with a lowercase r. It also needs to be in a scriptlet, however the use of scriptlets is not advised since you can easily use JSP EL.
<%
int i=Integer.parseInt((String)request.getAttribute("count"));
%>
If you are displaying this value on the page, you can easily use the expression language:
${count}
request.getAttribute() - returns an Object.
So this object has to be typecasted as follows
int i = (Integer.parseInt)(String.valueOf(request.getAttribute("count")));
I have working example with me..have a look
String Balance = (String.valueOf(session.getAttribute("CostOfTotalTicket")));
int i = Integer.parseInt(Balance);
where CostOfTotalTicket variable i have stored in session is of String type
Try this
<%Object object = request.getAttribute("count");
int val =Integer.parseInt(object.toString());%>
it's working for me
It depends on the type of data type you need to send, for this example I 'm sending data of integer type.
in the first servlet:
request.setAttribute("count", count); //To send data
in the second servlet:
request.getAttribute("count"); //To receive data
this worked for me.

Categories

Resources