how to check getParameter is set in the project - java

I am analayising the existing project, in one of the JSP page I saw that
String server=request.getParameter("server");
But I am trying to check How I can find where is this server parameter is set
I searched for setParameter("server"), no luck
can any one suggest on this
Main idea, I need to change the values for the values which is set in "server" parameter.

You can look in any of HTML elements, where they may have tag like <input type='text' id='server' name='server' /> like that. I have given example of text box, it can be anything.
And no, there is no such method called request.setParameter()

You can get this attribute from the html/jsp page from where the form is being submitted.

It is set by the HTTP request that was generated by the client side (such as a browser). For example, an HTML form, upon submission, would result in an HTTP request with parameters for each field. A standalone client (non-browser) can set request parameters by merely adding those parameters to the URL itself.
Therefore, first you have to determine what is generating the HTTP request that results in your JSP page being called. Once you find who's generating the request, it will be very easy for you to find how the parameter itself is set.

In your web.xml first check, from which form present in JSP/HTML the request is coming.
In the corresponding action, you will get all the input fields in the form, which will be fetched in the servelet through request.getParameter('')

This parameter is set when any form is submitted. Check the page which calls this servlet. That page will contain a form having field like <input type='text' name='server' />. If not found then check URL query parameter.
EDIT
In web.xml check which URL is being mapped to your servlet.

Related

How to create a parameter in JSP? [duplicate]

What is the difference between getAttribute() and getParameter() methods within HttpServletRequest class?
getParameter() returns http request parameters. Those passed from the client to the server. For example http://example.com/servlet?parameter=1. Can only return String
getAttribute() is for server-side usage only - you fill the request with attributes that you can use within the same request. For example - you set an attribute in a servlet, and read it from a JSP. Can be used for any object, not just string.
Generally, a parameter is a string value that is most commonly known for being sent from the client to the server (e.g. a form post) and retrieved from the servlet request. The frustrating exception to this is ServletContext initial parameters which are string parameters that are configured in web.xml and exist on the server.
An attribute is a server variable that exists within a specified scope i.e.:
application, available for the life of the entire application
session, available for the life of the session
request, only available for the life of the request
page (JSP only), available for the current JSP page only
request.getParameter()
We use request.getParameter() to extract request parameters (i.e. data sent by posting a html form ). The request.getParameter() always returns String value and the data come from client.
request.getAttribute()
We use request.getAttribute() to get an object added to the request scope on the server side i.e. using request.setAttribute(). You can add any type of object you like here, Strings, Custom objects, in fact any object. You add the attribute to the request and forward the request to another resource, the client does not know about this. So all the code handling this would typically be in JSP/servlets. You can use request.setAttribute() to add extra-information and forward/redirect the current request to another resource.
For example,consider about first.jsp,
//First Page : first.jsp
<%# page import="java.util.*" import="java.io.*"%>
<% request.setAttribute("PAGE", "first.jsp");%>
<jsp:forward page="/second.jsp"/>
and second.jsp:
<%# page import="java.util.*" import="java.io.*"%>
From Which Page : <%=request.getAttribute("PAGE")%><br>
Data From Client : <%=request.getParameter("CLIENT")%>
From your browser, run first.jsp?CLIENT=you and the output on your browser is
From Which Page : *first.jsp*
Data From Client : you
The basic difference between getAttribute() and getParameter() is that the first method extracts a (serialized) Java object and the other provides a String value. For both cases a name is given so that its value (be it string or a java bean) can be looked up and extracted.
It is crucial to know that attributes are not parameters.
The return type for attributes is an Object, whereas the return type for a parameter is a String. When calling the getAttribute(String name) method, bear in mind that the attributes must be cast.
Additionally, there is no servlet specific attributes, and there are no session parameters.
This post is written with the purpose to connect on #Bozho's response, as additional information that can be useful for other people.
The difference between getAttribute and getParameter is that getParameter will return the value of a parameter that was submitted by an HTML form or that was included in a query string. getAttribute returns an object that you have set in the request, the only way you can use this is in conjunction with a RequestDispatcher. You use a RequestDispatcher to forward a request to another resource (JSP / Servlet). So before you forward the request you can set an attribute which will be available to the next resource.
-getParameter() :
<html>
<body>
<form name="testForm" method="post" action="testJSP.jsp">
<input type="text" name="testParam" value="ClientParam">
<input type="submit">
</form>
</body>
</html>
<html>
<body>
<%
String sValue = request.getParameter("testParam");
%>
<%= sValue %>
</body>
</html>
request.getParameter("testParam") will get the value from the posted form of the input box named "testParam" which is "Client param". It will then print it out, so you should see "Client Param" on the screen. So request.getParameter() will retrieve a value that the client has submitted. You will get the value on the server side.
-getAttribute() :
request.getAttribute(), this is all done server side. YOU add the attribute to the request and YOU submit the request to another resource, the client does not know about this. So all the code handling this would typically be in servlets.getAttribute always return object.
getParameter - Is used for getting the information you need from the Client's HTML page
getAttribute - This is used for getting the parameters set previously in another or the same JSP or Servlet page.
Basically, if you are forwarding or just going from one jsp/servlet to another one, there is no way to have the information you want unless you choose to put them in an Object and use the set-attribute to store in a Session variable.
Using getAttribute, you can retrieve the Session variable.
from http://www.coderanch.com/t/361868/Servlets/java/request-getParameter-request-getAttribute
A "parameter" is a name/value pair sent from the client to the server
- typically, from an HTML form. Parameters can only have String values. Sometimes (e.g. using a GET request) you will see these
encoded directly into the URL (after the ?, each in the form
name=value, and each pair separated by an &). Other times, they are
included in the body of the request, when using methods such as POST.
An "attribute" is a server-local storage mechanism - nothing stored in
scoped attribues is ever transmitted outside the server unless you
explicitly make that happen. Attributes have String names, but store
Object values. Note that attributes are specific to Java (they store
Java Objects), while parameters are platform-independent (they are
only formatted strings composed of generic bytes).
There are four scopes of attributes in total: "page" (for JSPs and tag
files only), "request" (limited to the current client's request,
destroyed after request is completed), "session" (stored in the
client's session, invalidated after the session is terminated),
"application" (exist for all components to access during the entire
deployed lifetime of your application).
The bottom line is: use parameters when obtaining data from the
client, use scoped attributes when storing objects on the server for
use internally by your application only.
Another case when you should use .getParameter() is when forwarding with parameters in jsp:
<jsp:forward page="destination.jsp">
<jsp:param name="userName" value="hamid"/>
</jsp:forward>
In destination.jsp, you can access userName like this:
request.getParameter("userName")
Basic difference between getAttribute() and getParameter() is the return type.
java.lang.Object getAttribute(java.lang.String name)
java.lang.String getParameter(java.lang.String name)

How to re-populate form fields on a jsp page after failed server validation

I have a very simple Java MVC web application and am using a servlet to handle form validation. If the form is validated, the request is forwarded to the appropriate view. However, if the form fails validation, the request is forwarded back to the form, which then displays the appropriate error message(s).
My question is this -- what is the most efficient way to re-populate all of the form fields with the data that was originally entered in the form by the user?
I am not using an MVC framework, just simple HttpServlets as the controller with .jsp as the view.
The easiest and probably least effort is to just use
<input name="foo" type="text" value="${param.foo}"/>
This should default to "" when the user first visits the form.
A little more can be done to create a custom tag which binds to the request. However this is probably not the solution you were looking for.
Edit: You may want to use <c:out value="${param.foo}"/> to protect against XSS attack.
Pass the fields back to the jsp as part of the request object. request.setAttribute(..)
Use those attributes to set the form fields.

uploading files by url

I need to implement a servlet that uploads files to a server, I realize everyone says it has to be a POST method in regard to uploading files and not with GET method. However is there a way to upload a file and have the parameters of the request show up in the url even if the request is coming from POST method? If not, is there another approach?
Currently my servlet using post method is http://example.com/FileUpload/UploadFile
What I want is somehting like http://example.com/FileUpload/UploadFile?id=125&fileNum=5
Thanks for your input.
Simply POST to
http://example.com/FileUpload/UploadFile?id=125&fileNum=5
instead of
http://example.com/FileUpload/UploadFile
There is no such restriction that you cannot post to an URL having parameters. You can process the post data as you are doing now, plus, you can get the get parameters also.
I think it would not be an elegant solution, but you could use JavaScript to alter the action of the form element before submitting it to include querystring parameters.
The form will be something like:
<form method="POST" id="myForm" onSubmit="submitMyForm(this)>
<input type="text" id="id">
Then you will need JavaScript to change the action element of the form:
function submitMyForm(theForm) {
theForm.action="http://example.com/FileUpload/UploadFile?id=" +
getElementById("id").value;
theForm.submit();
}
Is there some reason you cannot just submit the parameters with post and pull them out on the server side?
Alternatively, if you do a multipart/form-data post you can include multiple parameters along with your file. The parameters are sent as part of the post body, along with the file.
You can send parameters and files in the POST. For example in the html you can have a form with this values, they can be of hidden type.
In the servlet you can get the values in the same way you do using the GET.
It is also better to use the POST method because the user can't change the value in the URL direction bar.

Does form with enctype="multipart/form-data" cause problems accessing a hidden field

I have created a hidden form element
<form name="UploadImage" enctype="multipart/form-data" method="post" action="UploadImage">
<label>
</label>
<input name="imgUploadObjId" id="imgUploadObjId" value="52" type="hidden">
//rest of the form here
</form>
And I am trying to get the value with this line in a servlet (as I have done before):
int objId = Integer.parseInt(request.getParameter("imgUploadObjId"));
But I get this (line 33 is the line above):
java.lang.NumberFormatException: null
java.lang.Integer.parseInt(Unknown Source)
java.lang.Integer.parseInt(Unknown Source)
web.objects.UploadImage.doPost(UploadImage.java:33)
javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
Is there something different about a form with enctype="multipart/form-data"? Or can you see some other error.
The servlet parses the parameters by default using application/x-www-form-urlencoded encoding. The multipart/form-data encoding however isn't supported in servlets until Servlet 3.0. The getParameter() calls will all return null.
In Servlet 3.0, you should have used HttpServletRequest#getParts() instead to get all parts of a multipart/form-data request, including normal form fields. Prior to Servlet 3.0, you should have used Apache Commons FileUpload to parse multipart/form-data requests. See also the following answer for a detailed example of both approaches: How to upload files to server using JSP/Servlet?
Note that if you aren't using any <input type="file"> field at all, then you can just leave the encoding away from the <form>. It will then default to application/x-www-form-urlencoded.
As a workaround, you can also add the required hidden parameters as GET parameters in the form's action attribute:
<form name="UploadImage" enctype="multipart/form-data" method="post" action="UploadImage?imgUploadObjId=52">
//rest of the form here
</form>
this will allow the request.getParameter("imgUploadObjId") call to work.
Indeed there is something different.
request.getParameter will only work for hardcoded URL parameters specified in action attribute of <form> element. In your case it does not contain any.
All other parameters will be incoded into the form itself, which you have to process by parsing HTTP request's input stream directly.
Fortunately, you are not the first and there are some good open-source libraries that take care of this.
I've been using Apache FileUpload. You create a parser and pass a request object to it and then iterate through different items. One of them will be your hidden field.
The multi-part encoding shouldn't affect hidden text fields. It is likely something else. Can you post more of the HTML/Servlet code?
Not sure if this helps, but I have used multipart forms in jsp pages which are submitted to a struts servlet and these pages have hidden fields which are received in my Struts Action classes (wrapped in Struts ActionForm), so I don't think there is any hard stop here.
Have you tried receiving this value as String and seeing what actually comes there?
You'd check the servlet code itself. Are you getting the request? Can you debug the app in order to see which variables are present in the environment when you try to get the value and parse it.
I only had the id atttribute set for the field and it didn't show up in the List items list. When I added the name attribute, it showed up.

Using request.setAttribute in a JSP page

Is it possible to use request.setAttribute on a JSP page and then on HTML Submit get the same request attribute in the Servlet?
No. Unfortunately the Request object is only available until the page finishes loading - once it's complete, you'll lose all values in it unless they've been stored somewhere.
If you want to persist attributes through requests you need to either:
Have a hidden input in your form, such as <input type="hidden" name="myhiddenvalue" value="<%= request.getParameter("value") %>" />. This will then be available in the servlet as a request parameter.
Put it in the session (see request.getSession() - in a JSP this is available as simply session)
I recommend using the Session as it's easier to manage.
The reply by Phil Sacre was correct however the session shouldn't be used just for the hell of it. You should only use this for values which really need to live for the lifetime of the session, such as a user login. It's common to see people overuse the session and run into more issues, especially when dealing with a collection or when users return to a page they previously visited only to find they have values still remaining from a previous visit. A smart program minimizes the scope of variables as much as possible, a bad one uses session too much.
You can do it using pageContext attributes, though:
In the JSP:
<form action="Enter.do">
<button type="SUBMIT" id="btnSubmit" name="btnSubmit">SUBMIT</button>
</form>
<% String s="opportunity";
pageContext.setAttribute("opp", s, PageContext.APPLICATION_SCOPE); %>
In the Servlet (linked to the "Enter.do" url-pattern):
String s=(String) request.getServletContext().getAttribute("opp");
There are other scopes besides APPLICATION_SCOPE like SESSION_SCOPE. APPLICATION_SCOPE is used for ServletContext attributes.
If you want your requests to persists try this:
example: on your JSP or servlet page
request.getSession().setAttribute("SUBFAMILY", subFam);
and on any receiving page use the below lines to retrieve your session and data:
SubFamily subFam = (SubFamily)request.getSession().getAttribute("SUBFAMILY");
Try
request.getSession().setAttribute("SUBFAMILY", subFam);
request.getSession().getAttribute("SUBFAMILY");
Correct me if wrong...I think request does persist between consecutive pages..
Think you traverse from page 1--> page 2-->page 3.
You have some value set in the request object using setAttribute from page 1, which you retrieve in page 2 using getAttribute,then if you try setting something again in same request object to retrieve it in page 3 then it fails giving you null value as "the request that created the JSP, and the request that gets generated when the JSP is submitted are completely different requests and any attributes placed on the first one will not be available on the second".
I mean something like this in page 2 fails:
Where as the same thing has worked in case of page 1 like:
So I think I would need to proceed with either of the two options suggested by Phill.
i think phil is right request option is available till the page load. so if we want to sent value to another page we want to set the in the hidden tag or in side the session if you just need the value only on another page and not more than that then hidden tags are best option if you need that value on more than one page at that time session is the better option than hidden tags.

Categories

Resources