Pass java date into rest query parameter - java

I have
#PUT
#Path("{id}")
public Response modify(#PathParam("id") Integer id,
#QueryParam("user") String user, #QueryParam("time") Date time) {....
I am trying to use RestClient to call this web service (the above is actually a cut down version of what I have)
When I call
..../123?user=user1
I hit the web service. As soon as I add time I get a 403 Forbidden message
..../123?user=user1&time=2013-09-10T20:00:00Z
Even if I pass nothing into the time query parameter I get the 403.
Is there anything difference about passing the java dates?
Thank in advance

It's not able to deserialize the String to a Date. Two options are either you can modify the date string as accepted by the date class or use another form, such as a long value.

One observation: It seems you are adding an extra slash(/) before your query params:
change this
..../123/?user=user1&time=2013-09-10T20:00:00Z
to
..../123?user=user1&time=2013-09-10T20:00:00Z
Second thing is that you may have to encode your URL to send the date properly to server

Related

How to retrieve an integer URL parameter with JSP? [duplicate]

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 to change url in address bar through java

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.

Spring #RequestParam vs #ModelArribute when getting a java.util.Date

I have a situation where the following code correctly gets the Date, without the time:
#RequestMapping(value="/pdf", method={RequestMethod.GET,RequestMethod.POST})
public void printPdf(#RequestParam("printDateTime") Date printDateTime .... more) {
printDateTime; // contains date, but NOT the time
...more code here...
}
However, when I use modelAttribute, it will correctly get the date AND the time from the client.
#RequestMapping(value="/pdf", method={RequestMethod.GET,RequestMethod.POST})
public void printPdf(#ModelAttribute WorkerSearchParamsDto searchParamsDto .... more) {
searchParamsDto.getPrintDateTime(); // Returns correct date with client time...
...more code here...
}
I am a little confused about why that would be the case and what I could do to resolve this. There are reasons we would like to not use modelAttribute for the print date, be we can work around it. Any ideas would be helpful.
To be clear, we WANT the time, not just the Date
We are running Spring 3.2.4.RELEASE

Path on Client side of RESTful Web Service

Ok so this is the code on the server side i just have question on how is the path gonna be defined on the client's side.
This is the method on the server
#Path("{index}/{product}/{amount}")
#PUT
#Produces("text/plain")
public String editTable (#PathParam("index") Integer index, #PathParam("product") String product, #PathParam("amount") Integer amount)
{...}
Now on the client side
{url = new URL( "http://localhost:8080/OrderService/service/tableservice/"+num+"/"+product+"/"+amount);
.....}
/"+num+"/"+product+"/"+amount);
Is this the correct syntax??
Also can the num and amount be integers while the product a string or am i gonna have a problem with it?
You will have problems if the product name has 'unsafe' URL characters in it. Which will probably be the case. To get around that you could URL encode the name before appending it to the URL.
But I think you should rethink your PATH definition in the first place. A good resource endpoint should uniquely identify it. But in your case you are including an amount field in the URL! Which means depending on who is ordering the product the resource URL is changing:
Customer A orders 2 Furbies:
/OrderService/service/tableservice/9/Furbies/2
Customer B orders 1 Furbie
/OrderService/service/tableservice/9/Furbies/1
But in both cases the customers are trying to order the same thing - a Furbie! This is not RESTful. Instead you should define a unique resource endpoint, then send the additional order information as appended data. So for example:
public class Order {
private Integer productId;
private Integer amount;
}
#PUT
#Path("/{productId}/orders")
#Produces("text/plain")
public String updateOrder(#PathParam("productId"), Order order) { ... }
You will notice I removed the index field as well, you can add that back in if absolutely required. You will notice I also added tacked an orders suffix to the end of the URL. To indicate that you are PUT'ing an updated representation for an order made for a product.
If you are mapping any #QueryParam to Integer, ensure that you are taking care of the following:
From the link on Oracle docs:
If a query parameter exists in the query component of the request URI, then the value will be extracted and parsed as a 32–bit signed integer and assigned to the method parameter. If the value cannot be parsed as a 32–bit signed integer, then an HTTP 400 (Client Error) response is returned.
Just to be safe, have your index and amount as String. Parse them to Integer within your service and handle NumberFormatException instead of HTTP 400.

How do I extract a value from the URL

I have a URL www.test.com/myshort/myapp/mypage.jsp, where myshort is a column value in my database.
I will later query for the id of this shortName (in this example it is 'myshort') which I am doing as
select id from mytable where shortName='myshort';
How can I extract the 'myshort' value from the entire URL? I can't do request.getParameter() since this is not a part of the url parameter. So I am trying to use request.getURI().
Can you please tell me how do I parse and get shortName using request.getURI()?
I suggest the use of Spring MVC framework for this type of server programming. It gives you the ability to map request patterns with the actual urls and extract such values from the URL.
I figured out a solution/alternative to my issue. I could go ahead and edit web.xml and specify the url format there.
But this is how I solved my issue. I took off the shortName coming from the url and sticked it as URL parameter. this is much more easier to access than what I was thinking earlier.

Categories

Resources