Take out parameter from url - java

I have a very long url with numbers of parameter like
http://localhost:8080/BUUK/dbcc?dssin=9371062001&roundid=JS&KIPL=02&PLATFORM=1&FREQUENCY=2&DRBEARER=1&BUYTYPE=1&EUP=12&TID=72123456435653654&SHORTCODE=54300&ADCODE=234rfdfsf&Buytag=3&Checkpoint=5,6,7&CHARGEMODEL=complete&restbalance=1
I want retrieve all the parameter from this url.
I was wondering if i can use request.getParamter("restbalance");
I will provide more info if required.
Thanks

If you're dealing with HttpServletRequest you can use
String restbalance = request.getParameter("restbalance");
or...to get all the parameteres, you can do:
String[] params = request.getParameterValues();
Here's the javadoc for the HttpServletRequest class, with all the available methods listed.

For each request your web server more precisely your web container creates a two object request and response.
HttpServletRequest and HttpServletResponse
The servletcontainer is attached to a webserver which listens on HTTP requests on a certain port number, which is usually 80. When a client (user with a webbrowser) sends a HTTP request, the servletcontainer will create new HttpServletRequest and HttpServletResponse objects and pass it through the methods of the already-created Filter and Servlet instances whose url-pattern matches the request URL, all in the same thread.
The request object provides access to all information of the HTTP request, such as the request headers and the request body. The response object provides facility to control and send the HTTP response the way you want, such as setting headers and the body (usually with HTML content from a JSP file). When the HTTP response is committed and finished, then both the request and response objects will be trashed.
request.getParameter("request_param"); will give you request_param value.
So there is nothing to get surprise accessing request parameter from request object

Yes you can use request.getParameter where request is the object of HttpServletRequest.
From the javadocs
getParameter
java.lang.String getParameter(java.lang.String name) Returns the value
of a request parameter as a String, or null if the parameter does not
exist. Request parameters are extra information sent with the request.
For HTTP servlets, parameters are contained in the query string or
posted form data. You should only use this method when you are sure
the parameter has only one value. If the parameter might have more
than one value, use getParameterValues(java.lang.String).
If you use this method with a multivalued parameter, the value
returned is equal to the first value in the array returned by
getParameterValues.
If the parameter data was sent in the request body, such as occurs
with an HTTP POST request, then reading the body directly via getInputStream() or getReader() can interfere with the execution of this method.

Try getParameterMap()
Map params = request.getParameterMap();
Iterator i = params.keySet().iterator();
while ( i.hasNext() )
{
String key = (String) i.next();
String value = ((String[]) params.get( key ))[ 0 ];
}

Well , request.getparameter() will work fine only if the request hits your Servlet from where you want to get hold of the request parameters . Please go through the documentation ServletRequest interface for all the relevant methods for your purpose.
getParameter();
getParameterNames();
getParameterValues();
getParameterMap();
You can also use HttpServletRequest#getQueryString() for custom parsing.
For normal Java code , you can parse the string returned by URL.getQuery() yourself to extract the data .

Related

How to send values from one jsp page to other but redirect to some other page?

I want to send values from jsp1.jsp to jsp2.jsp but redirect jsp1.jsp to jsp3.jsp . I used the following code in servlet for jsp1
response.sendRedirect("welcome1.jsp");
request.setAttribute("usern",user);
RequestDispatcher rd = request.getRequestDispatcher("afterlogin.jsp");
rd.forward(request,response);
but it keeps on giving this error "org.apache.jasper.JasperException: PWC6033: Error in Javac compilation for JSP".
you can use the possiblites of sessions in those case so you can access the parameter in jsp2 and redirect the jsp 1 to 3
https://www.javatpoint.com/servlet-http-session-login-and-logout-example
http://java.candidjava.com/tutorial/Servlet-Jsp-HttpSession-Login-logout-example.htm
You can use a HttpSession object as a user session, or use the ServletContext object for sharing global application information. Then use methods getAttribute (String attb) and setAttribute (String attb, String value) for sharing information within JSPs. The issue when you use a request is that the domain of the request is constraining you to use this information only when you receive this request.
You can also use JavaBeans to share information within JSPs
EDIT: Have you included your Java code inside a scriptlet? Using <% your code here %>
when you are using the sendRedirect function it will immediately redirect to that page it will not read next line code.
So according to your code your compiler is smart enough to check it so it is giving you an error.
please see below
1) SendRedirect ():
This method is declared in HttpServletResponse Interface.
Signature: void sendRedirect(String url)
1)In case of sendRedirect request is transfer to another resource to different domain or different server for further processing.
2)When you use SendRedirect container transfers the request to client or browser so URL given inside the sendRedirect method is visible as a new request to the client.
3)In case of SendRedirect call old request and response object is lost because it’s treated as new request by the browser.
4)SendRedirect is slower because one extra round trip is required because completely new request is created and old request object is lost.Two browser request required.
5)But in sendRedirect if we want to use we have to store the data in session or pass along with the URL.
2) Forward():
This method is declared in RequestDispatcher Interface.
Signature: forward(ServletRequest request, ServletResponse response)
1)When we use forward method request is transfer to other resource within the same server for further processing.
2)In case of forward Web container handle all process internally and client or browser is not involved.
3)When forward is called on requestdispather object we pass request and response object so our old request object is present on new resource which is going to process our request
4)Using forward () method is faster then send redirect.
5)When we redirect using forward and we want to use same data in new resource we can use request. setAttribute() as we have request object available.
more in : https://www.javatpoint.com/q/3577/difference-between-requestdispatcher-and-sendredirect

Forwarding to httpRequest that is not the current HttpRequest

I'm making a Java webapp which uses the Spring 4 framework.
When a user makes any request, if the user is not logged in, I use an interceptor to store this request object inside the user's session. Afterwards I redirect the user to a login screen.
When the user succesfully logs in, I want the login controller to not return a model and view (for example, the homepage) but instead fetch the stored previous request from the session and "execute" it as if the user just launched that request.
I'm having some problems with filling in some variables:
public ModelAndView login(RedirectAttributes redirectAttributes)
{
... //Do login stuff.
HttpServletRequest previousRequest = (HttpServletRequest) httpServletRequest.getSession().getAttribute("previousRequest");
httpServletRequest.getRequestDispatcher(previousRequest.getServletPath()).forward(previousRequest, ????????);
//end of method, I must return a ModelAndView but I don't have any view, I just want the request to be forwarded??
return null; //???????????
}
When getting the request dispatcher, you need to give it an url. I used httpServletRequest.getServletPath() but I'm not sure if this is correct.
When forwarding, you need to give a request and response object. But I don't have the response object at this time. I could perhaps also store the response object just like I did with the request. Or is there any other way? What would happen if I supply the CURRENT reponse object instead of the PREVIOUS response object?
My method expects me to return a modelandview, but I don't have any. How can I tell Spring to stop doing its normal "modelandview" scheme and instead start working on the forwarding of the request?
The setup described above is impossible in Jboss. You cannot forward and pass an arbitrary request object, because the servlet container will display an error. The forward method is meant to forward the CURRENT request object that is begin processed by the container.
A possible strategy, although still not ideal, is to wrap the stored request together with a freshly incoming request, and override the important methods like getParameters()´ andgetAttribute()´ to use the stored request instead of the actual request. This is the way Spring security solves this.
It seems to be impossible to tell a servletcontainer to stop handling the current request and redirect or forward to an arbitrary request object you just so happen to have available in your servlet.

How to remove a parameter from HttpServletRequest request?

In my web application I am sending two parameters: action and productCode from JSP to Servlet. Based on that action some processing will happen.
Now after action is performed I am forwarding control to a JSP. The problem is that when the new JSP is opened the URL still contains the name of Servlet and the Parameters. So in case if someone refreshes the page, the same action will be performed again and again.
If somehow I am able to remove the parameters from URL then I handled a no parameter situation in servlet.
Can anyone please tell me how can I remove the parameter from request object?
You can't remove a parameter from a HttpServletRequest. The very definition of a parameter is that it came from the client (browser).
Perhaps you mean a request attribute ?
For that you can use:
request.getAttribute(String name)
request.setAttribute(String name, Object o)
request.removeAttribute(String name)
A forward operation is transparent to the client and forwards the request on to another handler for processing. Perhaps a forward is not exactly what you want to do.
For the record (if someone does not find the other questions/answers):
The good practice is to wrap the request object in another object
using a servlet filter. (...)
Subclass HttpServletRequestWrapper and override the getParameter
methods. (...)
You can't remove a parameter from a HttpServletRequest - but you can change its value by passing new values for this parameter.
For example, after login to hide a password value you can forward to next servlet/page this way:
"*/PAM_show_orders?orderDate=2020-04-16&**password=+++***".
What you can do is set that parameter to null and check before performing any operation if that attribute is set to null. This way you still will be able to use request forwarding.
For example:
request.setAttribute("Your_attribute",null);
checking for not null while performing action can be done using
String para=request.getAttribute("Your_attribute");
if(para.equals(null)){
//do this
}
else{
//do something else
}
When your request handler is over you can just use:
response.setParameter("action") = "";
response.setParameter("productCode") = "";
Hope this helps.

Why setParameter() is not available for ServletRequest?

I have read about Servlet's in many tutorials. The Servlet parameters has getParameter() method. As the parameter has return type as only String. Why the ServletRequest do not have setParameter() method ?
I have read about that only attributes in Servlet's can be changed, and the parameters can not. Can anyone explain the basic concept why there is no provision for updating the parameter in request with method like setParameter()?
As per ServletRequest documentation, it is mentioned that :
Defines an object to provide client request information to a servlet.
That means ServletRequest object is used to transfer client side information to server methods. For ex. text field values from jsp page to servlet's doGet or doPost method.
ServletRequest Object is an client request to a Servlet, and ServletResponse object is the response sent to the client so always you get the required information from the request and you set the information in the response............!
Application developers use parameter for getting information from client, where as attributes are used by application developer for overall internal management purposes. You can not change (setParameter()) the values given to you by clients in parameters; you can simply get those values using getParameter()

How the attribute field of a HttpServletRequest maps to a raw HTTP request?

In Java, the attribute field of a HttpServletRequest object can be retrieved using the getAttribute method:
String myAttribute = request.getAttribute("[parameter name]");
Where the HttpServletRequest attribute data is stored in a raw HTTP request? Is it in the body of the request?
For example, I'm trying to create a raw GET HTTP request that will be sent to my servlet using some client program. My servlet.doGet() method would be something like this:
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
String myAttribute = request.getAttribute("my.username");
...
}
Where should I put the 'my.username' data in the raw HTTP request so that the 'myAttribute' String receives the value "John Doe" after the attribution?
Just to be clear as I think #Jon's answer doesn't make it perfectly clear. The values for getAttribute and setAttribute on HttpServletRequest are not present on what is actually sent over the wire, they are server side only.
// only visible in this request and on the server
request.getAttribute("myAttribute");
// value of the User-Agent header sent by the client
request.getHeader("User-Agent");
// value of param1 either from the query string or form post body
request.getParameter("param1");
To add to #gid's answer, attributes are not present in any way in the HTTP request as it travels over the wire. They are created (by your code) when processing the request. A very common use is to have a server set (aka create) some attributes and then forward to a JSP that will make use of those attributes. That is, an HTTP request arrives and is sent to a Servlet. The Servlet attaches some attributes. Additional server-side processing is done, eventually sending the page to a JSP, where the attributes are used. The response is generated in the JSP. The HTTP request and the HTTP response do not contain any attributes. Attributes are 100% purely server-side information.
When a single given HTTP request has completed, the attributes become available for garbage collection (unless they are persisted in some other location, such as a session). Attributes are only associated with a single request object.
I think what he is really asking is "how do I get parameteres into my program", not attributes. If that is the question, then send parameters in the GET request as part of the URL (after a question mark, http://myhost.com/myapp?name=joe&age=26) then retrieve them using request.getParameter("name") and request.getParameter("age"), or whatever you need.

Categories

Resources