I am attempting to learn how to use a querystring. My goal is to modify a servlet and from that be able to pull data from a querystring in my URL. I specifically need to show the "action". My URL querystring is to be entered as
?param1=val1¶m2=val2. I attempted to modify my servlets processRequest with the following line:
out.println("<p>" + request.getParameter("<p> Action is" [value] "</p>") +</p>);
Any ideas of where to go from here? I'm getting several errors.
You are retrieving invalid values from the request parameters.
More specifically, based on your querystring you should retrieve the parameters param1 and param2, which will contain values val1 and val2 respectively, like so:
String p1 = request.getParameter("param1");
String p2 = request.getParameter("param2");
System.out.println("params: 1:"+p1+" 2:"+p2);
Related
In JSP how do I get parameters from the URL?
For example I have a URL www.somesite.com/Transaction_List.jsp?accountID=5
I want to get the 5.
Is there a request.getAttribute( "accountID" ) like there is for sessions or something similar?
About the Implicit Objects of the Unified Expression Language, the Java EE 5 Tutorial writes:
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
The interesting parts are in bold :)
So, to answer your question, you should be able to access it like this (using EL):
${param.accountID}
Or, using JSP Scriptlets (not recommended):
<%
String accountId = request.getParameter("accountID");
%>
In a GET request, the request parameters are taken from the query string (the data following the question mark on the URL). For example, the URL http://hostname.com?p1=v1&p2=v2 contains two request parameters - - p1 and p2. In a POST request, the request parameters are taken from both query string and the posted data which is encoded in the body of the request.
This example demonstrates how to include the value of a request parameter in the generated output:
Hello <b><%= request.getParameter("name") %></b>!
If the page was accessed with the URL:
http://hostname.com/mywebapp/mypage.jsp?name=John+Smith
the resulting output would be:
Hello <b>John Smith</b>!
If name is not specified on the query string, the output would be:
Hello <b>null</b>!
This example uses the value of a query parameter in a scriptlet:
<%
if (request.getParameter("name") == null) {
out.println("Please enter your name.");
} else {
out.println("Hello <b>"+request. getParameter("name")+"</b>!");
}
%>
Use EL (JSP Expression Language):
${param.accountID}
If I may add a comment here...
<c:out value="${param.accountID}"></c:out>
doesn't work for me (it prints a 0).
Instead, this works:
<c:out value="${param['accountID']}"></c:out>
request.getParameter("accountID") is what you're looking for. This is part of the Java Servlet API. See http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/ServletRequest.html for more information.
String accountID = request.getParameter("accountID");
www.somesite.com/Transaction_List.jsp?accountID=5
For this URL there is a method call request.getParameter in java , if you want a number here cast into int, similarly for string value cast into string. so for your requirement , just copy past below line in page,
int accountId =(int)request.getParameter("accountID");
you can now call this value useing accountId in whole page.
here accountId is name of parameter you can also get more than one parameters using this, but this not work. It will only work with GET method if you hit POST request then their will be an error.
Hope this is helpful.
example you wanted to delete the subject record with its subject_id
#RequestMapping(value="subject_setup/delete/{subjectid}",method = RequestMethod.GET)
public ModelAndView delete(#PathVariable int subjectid) {
subjectsDao.delete(subjectid);
return new ModelAndView("redirect:/subject_setup");
}
and the parameter will be used for input on your query
public int delete(int subjectid) {
String sql = "update tbl_subject set isdeleted= '1' where id = "+subjectid+"";
return template.update(sql);
}
page 1 :
Detail
page 2 :
<% String id = request.getParameter("userid");%>
// now you can using id for sql query of hsql detail product
How can I change the url in the address bar through java code in browser(not through javascript or any front end languages)?
I have the url in the address bar like " http://www.abcde.com/home?abc=def&ghi=jkl " but I need to change that url through java code like " http://www.abcde.com/home ". I'm using jsp's for view.
Can anyone help?
If the URL with the request parameters comes from a page on which you have no control (or if it is a link) you can do the following :
use a servlet on that URL
if it finds request parameters in the query strings, it gets them and store them in session, then redirects to itself with no query string
if there is no query string, get the parameter from session, remove them from the session to avoid to reuse them by mistake and process the query
If the parameters exists in query string, because of a form using GET method, simply change the method to POST to pass the parameters in the request body instead of the query string.
In HttpServletRequest, getParameterMap returns a Map of all query string parameters and post data parameters.
Is there a way to get a Map of ONLY query string parameters? I'm trying to avoid using getQueryString and parsing out the values.
You can use request.getQueryString(),if the query string is like
username=james&password=pwd
To get name you can do this
request.getParameter("username");
Contrary to what cularis said there can be both in the parameter map.
The best way I see is to proxy the parameterMap and for each parameter retrieval check if queryString contains "&?<parameterName>=".
Note that parameterName needs to be URL encoded before this check can be made, as Qerub pointed out.
That saves you the parsing and still gives you only URL parameters.
The servlet API lacks this feature because it was created in a time when many believed that the query string and the message body was just two different ways of sending parameters, not realizing that the purposes of the parameters are fundamentally different.
The query string parameters ?foo=bar are a part of the URL because they are involved in identifying a resource (which could be a collection of many resources), like "all persons aged 42":
GET /persons?age=42
The message body parameters in POST or PUT are there to express a modification to the target resource(s). Fx setting a value to the attribute "hair":
PUT /persons?age=42
hair=grey
So it is definitely RESTful to use both query parameters and body parameters at the same time, separated so that you can use them for different purposes. The feature is definitely missing in the Java servlet API.
As the other answers state there is no way getting query string parameters using servlet api.
So, I think the best way to get query parameters is parsing the query string yourself. ( It is more complicated iterating over parameters and checking if query string contains the parameter)
I wrote below code to get query string parameters. Using apache StringUtils and ArrayUtils which supports CSV separated query param values as well.
Example: username=james&username=smith&password=pwd1,pwd2 will return
password : [pwd1, pwd2] (length = 2)
username : [james, smith] (length = 2)
public static Map<String, String[]> getQueryParameters(HttpServletRequest request) throws UnsupportedEncodingException {
Map<String, String[]> queryParameters = new HashMap<>();
String queryString = request.getQueryString();
if (StringUtils.isNotEmpty(queryString)) {
queryString = URLDecoder.decode(queryString, StandardCharsets.UTF_8.toString());
String[] parameters = queryString.split("&");
for (String parameter : parameters) {
String[] keyValuePair = parameter.split("=");
String[] values = queryParameters.get(keyValuePair[0]);
//length is one if no value is available.
values = keyValuePair.length == 1 ? ArrayUtils.add(values, "") :
ArrayUtils.addAll(values, keyValuePair[1].split(",")); //handles CSV separated query param values.
queryParameters.put(keyValuePair[0], values);
}
}
return queryParameters;
}
Java 8
return Collections.list(httpServletRequest.getParameterNames())
.stream()
.collect(Collectors.toMap(parameterName -> parameterName, httpServletRequest::getParameterValues));
I am afraid there is no way to get the query string parameters parsed separately from the post parameters. BTW the fact that such API absent may mean that probably you should check your design. Why are you using query string when sending POST? If you really want to send more data into URL use REST-like convention, e.g. instead of sending
http://mycompany.com/myapp/myservlet?first=11&second=22
say:
http://mycompany.com/myapp/myservlet/11/22
This may or may not be the dumbest question ever.
I'm using Restlet. When the client (which I do not control) POSTs to the URL, I can call the function:
representation.getText();
Which produces the following example list of key-value pairs in string form:
CallStatus=in-progress&CallerCountry=US&CalledZip=24013&ApiVersion=2008-08-01&CallerCity=ARLINGTON&CalledCity=ROANOKE&CallSegmentGuid=&CalledCountry=US&DialStatus=answered&CallerState=VA&CalledState=VA&CallerZip=22039
How can I access this data as a Map of key-value pairs in Restlet?
ANSWER:
Form newForm = new Form(getRequest().getEntity());
Check out these examples quoted from restlet.org (a Form is like a Map):
Getting values from a web form
The web form is in fact the entity of the POST request sent to the server, thus you have access to it via request.getEntity().
There is a shortcut which allows to have a list of all input fields :
Form form = request.getEntityAsForm();
for (Parameter parameter : form) {
System.out.print("parameter " + parameter.getName());
System.out.println("/" + parameter.getValue());
}
Getting values from a query
The query is a part of the identifier (the URI) of the request resource. Thus, you have access to it via request.getResourceRef().getQuery().
There is a shortcut which allows to have a list of all "key=value" pairs :
Form form = request.getResourceRef().getQueryAsForm();
for (Parameter parameter : form) {
System.out.print("parameter " + parameter.getName());
System.out.println("/" + parameter.getValue());
}
I am using query string for sending parameter to other page in form action tag
but when I am fetching the value on the next page, it is showing null and null is stored in the database.
My code is as follows:
out.println("<html>");
out.println("<form action=SubmitTimesheet?manager="+manager+">");
and on the other page I am trying to fetch the value of parameter in following manner:
String manager=request.getParameter("manager");
out.println(manager);
But it is printing null and further if I am trying to store the fetched value in database it is storing null.
Please help.
i have use session object and passed the value of manager in session variable instead of query string.
i have used the following code:
ses.putValue("manager", manager);
on the first servlet page and then on the second servlet page i fetched the value like this :
String manager=ses.getValue("manager").toString();
out.println(manager);
now it is printing the correct value instead of null
Don't add the manager query parameter if the manager value is null.
Also remember to encode query parameters.
And finally, the value of the action attribute should be quoted.
out.print("<form action=\"SubmitTimesheet");
if (manager != null)
out.print("?manager=" + URLEncoder.encode(manager, "UTF-8"));
out.println("\">");
Instead of the "UTF-8" string literal, you can also use StandardCharsets.UTF_8.
UPDATE
In reality, you shouldn't add query parameters to the action of a <form>. The form will post all the values of <input> and other form related elements, so what you should do, is add the manager value as a hidden input field:
out.println("<html>");
out.println("<form action=\"SubmitTimesheet\">");
if (manager != null)
out.print("<input name=\"manager\" type=\"hidden\" value=\"" +
StringEscapeUtils.escapeHtml4(manager) + "\">");
The above uses the library suggested by answer to question Recommended method for escaping HTML in Java.