How to get the parameter from the URL after '/' - java

https://localhost:8080/invoice_creation/1/
Here /invoice_creation is my resource location and /1 is my invoice number which denotes my database. I want to parse the value 1 alone in my java servlet when I pass this URL in my postman. I've used request.getParamerter() method..but it doesn't help me.. please help me to parse the value 1 in my java servlet page

getParameter is for the x and y in for example: http://localhost:8080/invoice_creation/1?x=5&y=hello.
A webserver listens on port 8080, receives the 'location' that the visitor wishes to visit (such as /invoice_creation/1?x=6&y=hello), and needs to then route this by finding the 'handler' that is supposed to deal with this. It then calls that handler.
Java has a ton of web frameworks, and most cooked up their own way of routing.
The 'original' java web servers uses the servlets API. It's a crappy API that you shouldn't be using; it's a pain to use. But, given that you tagged this question with servlets, you are, evidently, using it. I suggest you look around; perhaps Jersey/JaxRS is nicer, especially if you're attempting to set up a REST API.
At any rate, if you insist on using the servlet API, you've somehow set up routing such that /invoice_creation/_anything goes here_ ends up at some servlet and now you wish the 'anything goes here' part. Exactly how to do that depends on a few factors, but usually its one of these:
req.getPathInfo(). Depending on your Web Server / servlet container you're using, this will either return /1 or returns /invoice_creation/1. You'll have to 'extract' the 1 from this, using either regular expressions (java.util.regexp.Pattern and friends), or basic string manipulation such as str.substring).
req.getTranslatedPath().
req.getRequestURI() - this definitely returns the whole thing (including /invoice_creation/).

Related

Consuming RESTful pagination information from Link header RFC8288

I am interfacing with Shopify and they use RESTful API. When I request a resource that returns an array of items, they use RFC8288 pagination format.
For example, https://example.com/api/inventory_levels.json?limit=10 returns 10 entities along with the following response header:
Link: <https://example.com/api/inventory_levels.json?limit=10&page_info=eyJs9pZHMiO>;
rel="previous", <https://example.com/api/inventory_levels.json?limit=10&page_info=MiZHeyJs9pO>; rel="next"
Appearantly if I want to retrieve all entites from that resource I need to iterate through the 'next' URL until there's no more 'next' returning. But how am I going to parse these info using JAVA or C# code? I could use a regular expression like <(?<next_url>.*)>; rel="next" to retrieve the 'next_url' from it. But it feels like re-inventing the wheel and not robust.
If this is a well-defined feature, shouldn't there be a readily available library/infrastructure that could be used? I just don't want to be caught by surprise if one day the formatting shows up different (like having an extra space and such) and, whilst abiding to the RFC defination, breaks my hastily scrambled up RegEx solution.
Suggestion welcome for Java or C#.

How to use JSP as a template without serving it as a webpage

Per my understanding JSP is something to serve to the client. But is it possible to use JSP simply as a template to dynamically assemble an html page, which I then serve to the client? What I mean is this
A servlet receives the call from the user
After some computation, my servlet calls the JSP to assemble the html page dynamically
The servlet gets or converts the JSP "result" (the resulting html page) to a String
The servlet can now do whatever it wants with that String. It can return it as an html webpage or it can store it in a database, or whatever. After all, the string here is a proper html page/text.
For comparison, Python has Jinja2, which does exactly what I just explained. The closest thing to Jinja2 in Java seems to be JSP.
I need a template to assemble html pages dynamically. If I can use the JSP as above then that will solve my problem in Java. Notice that I don't care for JSP per se. I just need a template similar to Jinja2 (if I could use Jinja2 in Java on App-Engine that would be ideal). Also I am very new to JSP. So if you have an answer, please format it as an example; that would be truly helpful.
I am migrating from Python App-Engine to Java App-Engine for business reasons.
This is possible, but you'll need to jump through quite a few hoops, the details of which are dependent on the specific container - in this case appengine.
A quick summary:
create a fake httpservletresponse, wrapping an output stream you access after rendering. You cannot use a httpservletresponsewrapper, even though the spec permits it this environment won't
store all request attributes in a map, you'll restore these afterwards in case they've been mutated
use requestdispatcher.include, passing in the real request and your synthetic response
restore request attributes
read string from the outputstream
Be particularly careful of side effects to your request/response, for example the constraints around only calling one of getwriter or getoutputstream, as well as finalizing the request (setting status or content length)
Or just use one of velocity, handlebars, freemarker or the various other Java templating languages. They'll all be much more straightforward.

Permanent REST web service url with many and long parameters

Since I found it very difficult to explain my problem in the heading I'm going to explain it a little further:
I want to /I'm writing a JAX-RS web service (Jersey/Servlet3.0) and the corresponding JS library for a geographic use case. The input of the web service are two lists (source & target points) of geographic points (latitude, longitude) and each point having a list of parameters. Since there is basically no limit on the number of points I don't know how to combine the URL length limit and the unlimitedness of the parameter list.
Here are the restrictions again:
Easy to share URL (so POST probably wont quite cut it?) for social media sharing and of course easy debugging
An example configuration can be seen here please note that there can be nested sets of parameters (point 1 has parameters of it's own)
Needs to able to be integrated in external website (with bookmarkable url)
Not all of the parameters are mandatory, what is the best way to deal with defaults/missing values?
What I thought of so far is:
create a boatload of parameters
jsonify the configuration and send it to server via url parameter
But I don't really like these options. Am I missing something?
Sorry for this rather vague question.
Daniel
Ok to your points
for easy sharing why not just implement a tinyURl or bit.ly style sharing system - obviously you can't have both an easy to pass-in url (a URL that makes it easy to give the server detailed information) that is easy to share (human friendly and short) - but you could very easily save the results (or inputs and calculate each time) to a database and link that to a tinyURl.
as an aside POST will be the only way to handle this due to the amount of data.
Just pass as JSON - easy to nest paramaeters that way
Don't quite get this part - for an external site to use this they could post the data and you return the answers - or using point 1 method of 'tinyurl / bit.ly style system it could call this in an iframe?
You would deal with missing parameters / defaults at server side - create a function for each parameter - if parameter is expected then throw error - if parameter has a default include this in your function and if parameter is not included then don't run the function.
Hope that makes sense?

Java website protection solutions (especially XSS)

I'm developing a web application, and facing some security problems.
In my app users can send messages and see other's (a bulletin board like app). I'm validating all the form fields that users can send to my app.
There are some very easy fields, like "nick name", that can be 6-10 alpabetical characters, or message sending time, which is sended to the users as a string, and then (when users ask for messages, that are "younger" or "older" than a date) I parse this with SimpleDateFormat (I'm developing in java, but my question is not related to only java).
The big problem is the message field. I can't restrict it to only alphabetical characters (upper or lowercase), because I have to deal with some often use characters like ",',/,{,} etc... (users would not be satisfied if the system didn't allow them to use these stuff)
According to this http://ha.ckers.org/xss.html, there are a lot of ways people can "hack" my site. But I'm wondering, is there any way I can do to prevent that? Not all, because there is no 100% protection, but I'd like a solution that can protect my site.
I'm using servlets on the server side, and jQuery, on the client side. My app is "full" AJAX, so users open 1 JSP, then all the data is downloaded and rendered by jQuery using JSON. (yeah, I know it's not "users-without-javascript" friendly, but it's 2010, right? :-) )
I know front end validation is not enough. I'd like to use 3 layer validation:
- 1. front end, javascript validate the data, then send to the server
- 2. server side, the same validation, if there is anything, that shouldn't be there (because of client side javascript), I BAN the user
- 3. if there is anything that I wasn't able to catch earlier, the rendering process handle and render appropriately
Is there any "out of the box" solution, especially for java? Or other solution that I can use?
To minimize XSS attacks important thing is to encode any field data before putting it back on the page. Like change > to > and so on. This would never allow any malicious code to execute when being added to the page.
I think you are doing lot of right things by white listing the data you expect for different fields. Beyond that for fields which can allow other characters which can be problematic encoding would fix the issue for you.
Further since you are using Ajax it gives you some protection as people cannot override values in URL parameters etc.
Look at the AntiSamy library. It allows you to define rulesets for your application, then run your user input through AntiSamy to clean it per your rules.
The easiest way is to do a simple replacement for the following
< with <
> with >
' with \'
That will solve most database vulnerability.

Mask urls in JSP

Related to this question:
URL characters replacement in JSP with UrlRewrite
I want to have masked URLs in this JSP Java EE web project.
For example if I had this:
http://mysite.com/products.jsp?id=42&name=Programming_Book
I would like to turn that URL into something more User/Google friendly like:
http://mysite.com/product-Programming-Book
I've been fighting with UrlRewrite, forwarding and RequestDispatcher to accomplish what I want, but I'm kind of lost. I should probably have a filter for all http requests, re format them, and forward the page.
Can anyone give some directions? Tips?
Thanks a lot.
UPDATE: Servlets did it. Thanks Yuval for your orientation.
I had been using UrlRewrite, as you can see at the first sentence of the question I also asked a question about that. But I couldn't manage to get UrlRewrite work the way I wanted. Servlets did the job.
You could use a URLRewrite filter. It's like how mod_rewrite is for Apache's HTTP web server.
http://tuckey.org/urlrewrite/
"Redirect one url
<rule>
<from>^/some/old/page\.html$</from>
<to type="redirect">/very/new/page.html</to>
</rule>
Tiny/Freindly url
<rule>
<from>^/zebra$</from>
<to type="redirect">/big/ugly/url/1,23,56,23132.html</to>
</rule>
"
It's been a while since I mucked about with JSPs, but if memory serves you can add URL patterns to your web.xml (or one of those XML config files) and have the servlet engine automatically route the request to a valid URL with your choice of paramters. I can look up the details if you like.
In your case, map http://mysite.com/product-Programming-Book to the URL
http://mysite.com/products.jsp?id=42&name=Programming_Book and the user no longer sees the real URL. Also, you can use this more user-friendly URL within your application, as a logical name for that page.
Yuval =8-)
Generally you're fronting your application with Apache. If so, look into using Apache's mod_rewrite. http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html
For one thing I'd recommend you deal with this within your application, and not rely on external rewrites, say via Apache mod_rewrite (unless you have determined this is the fastest way to do so.)
But a few things first:
I would not convert this:
http://mysite.com/products.jsp?id=42&name=Programming_Book
Into this:
http://mysite.com/product-Programming-Book
See, if I go only by your book example, I don't see what is wrong with the former URL. After, all it works for Amazon. And there is no such thing as google friendly URLs (only user friendly.) You have to consider why you want to do that type of rewriting, and how. For example, in your rewrite option, where is the id?
That is, you have to define a logical rule that define
the unique pages you want to show, and
the unique combination of parameters that can identify each page.
For example, using your book case. Let's say you can identify any book using the following rules:
by ISBN
by Author Name, Title and if
applicable version (if version is
missing, assume latest)
if ISBN is included with Author
Name, Title and/or edition, ignore
all except ISBN. That is, treat it
as the former (or more precisely,
ignore all other book identification
parameters when ISBN is present.)
With a ?parametrized url scheme, then you'd have the following possibilities:
http://yoursite/products?isbn=123465
http://yoursite/products?author=johndoe&title="the cookbook" << this assumes the latest edition, or 1 if first.
http://yoursite/products?author=johndoe&title="the cookbook"&edition=3
http://yoursite/products?title="the cookbook"&author=johndoe
http://yoursite/products?edition=3&title="the cookbook"&author=johndoe
....
and so on for all combinations. So before you look for a technical implementation, you have to think very carefully how you will do it. You'd have to create a syntax and a hierarchy of parameters (say, author will always come before title, and title will always come before edition).
So you'll end up with the following (using the same example as John Doe the author, with his book being in the 3rd edition):
http://yoursite/product/isbn/12345
http://yoursite/product/author/johndoe/the%20cookbook << see the %20 for encoding spaces (not a good idea, but something to take into account)
http://yoursite/product/author/johndoe/the%20cookbook/3
Any other combination should either generate an error or smartly figure out how to rewrite to the "cannon" versions and send a HTTP 3xx to the client with the appropriate URL target.
Once you have ironed those details out, you can ask yourself it the effort is worth it or necessary.
So if you find yourself that you need to, then easiest and cheapest DIY way is to write a filter that parses the url, breaks the parameters down, creates a ?parametrized url string for a JSP page, get its RequestDispatcher and forward to it.
You do not want to do URL rewrites because these incur in HTTP 303/307 back and forth between your server and your client. Or at least you want to keep that to a minimum.

Categories

Resources