See POST parameters in Java EE eclipse debugging - java

I'm not experienced in debugging Java EE (I'm rather a javascript guy) and I need to see what HTTP POST parameters get to the server side. I put a breakpoint in a jsp file that the form is pointing its action to and now I can't find the POST content in the debug variables window.
Where are they? How can I lookup the POST in debug?
[I'd use wireshark, but it's over the https]

In jsp you can use request object and call its method getParameterNames () or getParameter (String name). You can also call request.getMethod () to ensure that you obtain parameters from POST request.
<%
if (request.getMethod().equals("POST")) {
for (String paramName : request.getParameterNames ()) {
String value = request.getParameter (paramName);
}
}
%>

In the breakpoint, just check the HttpServletRequest property of the JspContext instance and then check its parameterMap property.
Or do it the poor man's way by just printing them all in the JSP:
<c:forEach items="${param}" var="p">
Param: ${p.key}=
<c:forEach items="${p.value}" var="v" varStatus="loop">
${v}${loop.last ? '<br>' : ','}
</c:forEach>
</c:forEach>
That said, you'd normally be interested in them inside a servlet class, not inside a JSP. This would indicate that you're doing some business logic inside a JSP file using using scriptlets. This is considered bad practice. Don't do that and move that raw Java code to real Java classes before it's too late. Use JSP for presentation only. You can use taglibs like JSTL to control the page flow and use EL to access backend data.

In debug mode: see
request -> request -> coyoteRequest -> parameters -> paramHashValues

Related

JSTL call parameterized void method [duplicate]

How to call a Java method with arguments which is defined in Java class, from JSP using JSTL/EL. The method is returning arrays. Any return value can be used.
You can only invoke methods with arguments in EL if you're targeting and running at least a Servlet 3.0 compatible container (e.g. Tomcat 7 or newer, WildFly 8 or newer, GlassFish 3 or newer, etc) with a web.xml declared conform at least Servlet 3.0. This servlet version comes along with EL 2.2 which allows invoking arbitrary instance methods with arguments.
Assuming that you've a ${bean} in the scope which refers to an instance of a class which has a method something like public Object[] getArray(String key), then you should be able to do this:
<c:forEach items="${bean.getArray('foo')}" var="item">
${item} <br />
</c:forEach>
or even with another variable as argument
<c:forEach items="${bean.getArray(foo)}" var="item">
${item} <br />
</c:forEach>
But if you don't target a Servlet 3.0 container, then you cannot invoke methods with arguments in EL at all. Your best bet is to just do the job in the preprocessing servlet as suggested by Duffymo.
Object[] array = bean.getArray("foo");
request.setAttribute("array", array);
// ...
As a completely different alternative, you could create an EL function which delegates the method call. You can find a kickoff example as option 2 of this answer How to call a static method in JSP/EL? You'd like to end up something like as:
<c:forEach items="${util:getArray(bean, 'foo')}" var="item">
${item} <br />
</c:forEach>
with
public static Object[] getArray(Bean bean, String key) {
return bean.getArray(key);
}
The web.xml file should absolutely not have a <!DOCTYPE> line in top as that would otherwise still force the Servlet 2.3 modus. You can find examples of proper web.xml declarations in the second half of this answer How to install JSTL? The absolute uri: http://java.sun.com/jstl/core cannot be resolved.
The above solution didnt work for me.
I had a function getRemitanceProfileInformation(user) in my java class.
I created a usebean of java class and then invoked
<c:set var="paymentValueCode" value='remittanceaddr.getRemitanceProfileInformation("${user}")'/>
and it worked.
Give the JSP a reference to an instance of the class that has the method and call it.
You're probably asking who gives the JSP that instance - it's a servlet in the model-2 MVC arrangement.
Here's how the flow will work:
Submit a GET/POST request from a JSP to a servlet.
Servlet acts on that request and does some work on the JSP's behalf. Puts all the necessary objects into request, session, or other appropriate scope.
Servlet routes response to the next JSP, which might be the same as the requesting JSP.
Rinse, repeat.
If you're using JSF, you can use an bean act as a model in View Scope, and load from data source automatic. And if you're using JSP, how about using TLD Tag? And using JSTL tag <c:foreach> ? It's saves the memory from saving in the session, or save in session and remove it when load event done? Some how like this (JSTL+TLD)
<c:forEach items="${myTag:getProductByPage(page)}" var="p">
Product name: ${p.productName}
</c:forEach>

read parameters passed by one jsp to another

I want to read parameter passed by one JSP to another using HTTP POST method.
Following are my two JSP files.
One.jsp
<body>
<form action="Two.jsp" method="post">
<input type="text" value="test value" name="txtOne">
<input type="submit" value="Submit">
</form>
</body>
Two.jsp
<body>
<% response.getWriter().println(request.getParameter("txtOne")); %>
</body>
I can access the parameter in Two.jsp file using scriplet.
I want to avoid scriplet, so I am looking for JavaScript or jQuery solution.
So far I have searched and found JavaScript solution which only reads parameters sent using GET method(query string only).
Any suggestion will be appreciated.
Thanks in advance.
Solution:
I was able to get the value using JSTL:
${param.txtOne}
Try expression language - ${txtOne}, of if the method in one.jsp is GET instead of POST, you would be able to read URL in javascript and extract parameter value from there.
Yes you can get the value by use of JSTL
${param.txtOne}
Update
From EL info page
In EL there are several implicit objects available.
EL Scriptlet (out.print and null checks omitted!)
---------------------------------- ---------------------------------------------
${param.foo} request.getParameter("foo");
${paramValues.foo} request.getParameterValues("foo");
${header['user-agent']} request.getHeader("user-agent");
${pageContext.request.contextPath} request.getContextPath();
${cookie.somename} Too verbose (start with request.getCookies())
Implicit Objects
The JSP expression language defines a set of implicit objects:
pageContext: The context for the JSP page. Provides access to various objects including:
servletContext: The context for the JSP page’s servlet and any web components contained in the same application. See Accessing the Web Context.
session: The session object for the client. See Maintaining Client State.
request: The request triggering the execution of the JSP page. See Getting Information from Requests.
response: The response returned by the JSP page. See Constructing Responses.
In addition, several implicit objects are available that allow easy access to the following objects:
param: Maps a request parameter name to a single value
paramValues: Maps a request parameter name to an array of values
header: Maps a request header name to a single value
headerValues: Maps a request header name to an array of values
cookie: Maps a cookie name to a single cookie
initParam: Maps a context initialization parameter name to a single value
Finally, there are objects that allow access to the various scoped variables described in Using Scope Objects.
pageScope: Maps page-scoped variable names to their values
requestScope: Maps request-scoped variable names to their values
sessionScope: Maps session-scoped variable names to their values
applicationScope: Maps application-scoped variable names to their values
I want to avoid scriplet, so I am looking for JavaScript or jquery solution.
Simply you cannot.
request object can only accessible on server side, i.e in your JSP. You cannot access request or response object in client side that i.e javascript/jquery/whatever.
If you want access jsp value in javascript, try something like
var news=<%= request.getParameter("txtOne")) %>;
As a side note: Avoid scriplets and go for Expression language.
It is time for you to move to some MVC framework like struts than plain JSP. Then you can fill an ActionForm from parameters and use them on Two.jsp.

How to access a request attribute set by a servlet in JSP?

I'm trying to retrieve attribute values set by a servlet in a JSP page, but I've only luck with parameters by ${param}. I'm not sure about what can I do different. Maybe its simple, but I couldn't manage it yet.
public void execute(HttpServletRequest request, HttpServletResponse response) {
//there's no "setParameter" method for the "request" object
request.setAttribute("attrib", "attribValue");
RequestDispatcher rd = request.getRequestDispatcher("/Test.jsp");
rd.forward(request,response);
}
In the JSP I have been trying to retrieve the "attribValue", but without success:
<body>
<!-- Is there another tag instead of "param"??? -->
<p>Test attribute value: ${param.attrib}
</body>
If I pass a parameter through all the process (invoking page, servlets and destination page), it works quite good.
It's available in the default EL scope already, so just
${attrib}
should do.
If you like to explicitly specify the scope (EL will namely search the page, request, session and application scopes in sequence for the first non-null attribute value matching the attribute name), then you need to refer it by the scope map instead, which is ${requestScope} for the request scope
${requestScope.attrib}
This is only useful if you have possibly an attribute with exactly the same name in the page scope which would otherwise get precedence (but such case usually indicate poor design after all).
See also:
Our EL wiki page
Java EE 6 tutorial - Expression Language
Maybe a comparison between EL syntax and scriptlet syntax will help you understand the concept.
param is like request.getParameter()
requestScope is like request.getAttribute()
You need to tell request attribute from request parameter.
have you tried using an expression tag?
<%= request.getAttribute("attrib") %>
If the scope is of request type, we set the attribute using request.setAttribute(key,value) in request and retrieve using ${requestScope.key} in jsp .

using EL inside java tag

I have an attribute which I have forwarded from a servelet to a jsp file and while I can use this object with EL I'd like to know how to access it inside the java tags. An example is something like the following:
Searching for "${search_phrase}" returned
<c:forEach var="video" items="${results}">
${video.getVideoName()}
${video.getVideoID()}
</c:forEach>
So results here is an ArrayList of type Video which is forwarded from a servlet to a jsp
I would like to access this ArrayList inside <% %> tags in order to perform some more involved tasks that I cant do with EL.
Anybody know how to do this?
On a side note, this ArrayList I'm creating could potentially get large. Where is this stored? On the server or in some users temp files? If it's stored in server memory does it get cleaned after some period of time / an event such as the user that requested the ArrayList closes connection to server?
It all depends where you stored the list. If you stored it in a request attribute (and not anywhere else), then it will be eligible to garbage-collection when the request has been handled.
If you stored it in a session attribute, then it will be stored in the server memory (and/or the file system or the database depending on the container configuration) until the session times out or is invalidated, or until you remove it. HTTP is a stateless protocol. The user doesn't have a connection to the server.
Java code between <% %> is not a java tag. It's scriptlet, and should not be used in a JSP. If you need to do something that EL or JSP tags can't do easily, then either
write a custom JSP tag yourself, put the Java code in this JSP tag, and invoke the tag from the JSP, or
or write a custom EL function, and invoke this function from the JSP
or prepare the work in a controller (servlet, MVC framework action) before dispatching to the JSP, so that the JSP can generate the markup easily.
The list is accessible using the getAttribute method corresponding to the setAttribute method you used to store the list:
HttpServletRequest.setAttribute() --> HttpServletRequest.getAttribute()
HttpSession.setAttribute() --> HttpSession.getAttribute()
ServletContext.setAttribute() --> ServletContext.getAttribute()
I think you should use something like
<c:forEach var="video" items="${results}">
<c:forEach var="videoType" items="${video.types}"> //suppose videoType is an object
<c:out value="${videoTypeDetails}" />
</c:forEach>
</c:forEach>

Passing customized messages from Servlet to a JSP page?

I am new to JSP and Servlets.
What i want to know is the best way to pass some customized message to client web pages.
For example suppose i have a web page say student.jsp which has a form,to register a new student to our online application.after successfully inserting all the fields of the form,
user submits the form and data is submitted to our servlet for further processing.Now,Servlet validates it and add it to our database.so,now servlet should send a message indicating a
successful insertion of data entered by end user to end user (In our case student.jsp).
So,i could i pass this type of message to any client web page.
I don't want to pass this message as URL query String.
is there ant other better and secure way to pass these type of messages ...
use request.setAttribute("message", yourMessage) and then forward (request.getRequestDispatcher("targetPage.jsp").forward()) to the result page.
Then you can read the message in the target page via JSTL (<c:out value="${message}" />) or via request.getAttribute(..) (this one is not preferable - scriptlets should be avoided in jsp)
If you really need response.sendRedirect(..), then you can place the message in the session, and remove it after it is retrieved. For that you might have a custom tag, so that your jsp code doesn't look too 'ugly'.
I think it looks like this in JSTL:
<c:remove var="message" scope="session" />
I also think that, if "message" is a Java String, it can be set to the empty string after it's been used like this:
<c:set var="message" scope="session" value="" />
Actually, it also looks like it works if "message" is an array of Java Strings: String[]...

Categories