I have a form on my jsp with fields - Name, IP, username, token.
It is mapped to a table with same column names. I have created a Bean class too.
Now, I am not sure what is an ideal way to send all the parameters from jsp to the java code.
I know few options like -
Create input with type hidden and then set its value in the jsp.
<input type="hidden" id="name" name="name"/>
and then retrieve its value in the code using request.getParameter("name")
Somehow I dont feel this is an ideal way.
Create a JSON with all the values of the input boxes and set the json file as one input and read it on the java code using org.json;
Which one of the two is the better way to do it? Is there any simpler, effective and much better way?
Everything which is built using HTTP methods must send values to the server in one of three places:
Parameters in the url itself (GET requests)
Content in the body of the request (POST requests)
Key-value pairs in the header of the request (HTTP method agnostic)
Any mechanism you use to send a value back to the server (excluding web sockets), no matter what the framework, will use one of these mechanisms underneath.
That being said, use whatever best meets the requirements of your application:
Form-based, GET requests:
are simple to understand
don't require much overhead either on the front-end or back-end
are easy to test (just access the url using the appropriate query string)
Form-based, POST requests:
are also simple to understand
also don't require much overhead either on the front-end or back-end
are not as easy to test (you can't just access the url using the appropriate query string)
Ajax-y, JSON body, POST requests:
are the new hotness
require a bit more front-end work (creating the request in JS and sending it)
don't require the browser to make a full-page request/response
Related
Is there a specific scenario where we use a POST instead of GET, to implement the functionality of get operation ?
GET is supposed to get :) and POST is used to mainly add something new or sometimes often used for updates as well (although PUT is recommended in such scenarios). There is no specific scenario where we use a POST instead of a GET, if we require this, that means we are probably doing it wrong, although nothing stops you doing this but this is bad design and you should take a step back and plan your API carefully.
There are 2 important cases for a POST i.e. POST is more secure than a GET and POST can send large amount of data but even with this I won't recommend why one will use POST to simulate a GET behaviour.
Lets understand usage of get and post :
What is GET Method?
It appends form-data to the URL in name/ value pairs. The length of the URL is limited by 2048 characters. This method must not be used if you have a password or some sensitive information to be sent to the server. It is used for submitting the form where the user can bookmark the result. It is better for data that is not secure. It cannot be used for sending binary data like images or word documents. It also provides $_GET associative array to access all the sent information using the GET method.
What is POST Method?
It appends form-data to the body of the HTTP request in such a way that data is not shown in the URL. This method does not have any restrictions on data size to be sent. Submissions by form with POST cannot be bookmarked. This method can be used to send ASCII as well as binary data like image and word documents. Data sent by the POST method goes through HTTP header so security depends on the HTTP protocol. You have to know that your information is secure by using secure HTTP. This method is a little safer than GET because the parameters are not stored in browser history or in web server logs. It also provides $_POST associative array to access all the sent information using the POST method.
Source: https://www.edureka.co/blog/get-and-post-method/
So both the methods have their specific usage.
POST method is used to send data to a server to create or update a resource.
GET method is used to request data from a specified resource.
If you want to fetch some data you can use the GET method. But if you want to update an existing resource or create any new resource you should use POST. GET will not help you to create/update resources. So exposing the api should be specific to your needs.
UPDATE
So your main question is in what scenario we can use POST to implement the functionality of GET.
To answer that, as you understand what GET and POST does, so with GET request you will only fetch the resource. But with POST request you are creating or updating the resource and also can send the response body containing the form data in the same request response scenario. So suppose you are creating a new resource and the same resource you want to see, instead of making a POST call first and making a GET call again to fetch the same resource will cost extra overhead. You can skip the GET call and see your desired response from the POST response itself. This is the scenario you can use POST instead of making an extra GET call.
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.
I have a REST api built for creating orders. The behavior is such that the person who creates an order received an email back saying "You created an order XXX". This email is triggered all the time.
The api appears like this
http://api.mytestevnt.com/ordering/orders - POST with request body as the order entity json.
Now i want to give a feature to the api caller to indicate if the email notification is necessary or not. What's the best way to do this?
I think it depends on whether email notification is data or metadata. If it's part of the order, then definitely add it to the request body. If it's metadata, you have two choices. If you think there will be lots of metadata, you can either edit the order to have a metadata section or you can POST the metadata separately. If there will only be a limited amount of metadata, I would suggest using a query parameter.
You should avoid using a header unless you control the entire path from the client to the server, because proxies or load balancers are allowed to strip non-standard headers.
Include in the POST body a send_email=1 or send_email=0 param. You'll extract that, and see what the user wants to do.
Search "how to get POST variables in JAVA".
Accessing post variables using Java Servlets
You can do like this:
Add a new Java attribute(like boolean emailEnabled) in your Java Request Object for your REST service.
Client side which invokes your REST service need to provide that parameter you added in your server side, you can set a default value for that too.
I am interested in creating a simple web application that will take in user input, convert it to an XML file and send the file to a database.
Coding wise I feel I am okay, it is just the general setup and what implementation to use I am a bit unsure of.
At the moment I have a JSP page containing a form, the user fills out the form and on submit a POST method is sent to a servlet, in the servlet doPost() method the servlet is instantiating a java object and passing it the user inputted data. The java object then writes that data to an XML file and sends it to the database via REST.
All I would be interested to know is if this the standard/optimal way of creating such a web application.
Any and all feedback is appreciated.
Thanks
For a "simple webapplication" this high level approach looks fine in general. However, if you want more critical feedback, you'd need to give more details about the low-level approach. It may for example happen that it isn't memory efficient and thus may break when the webapp is been used by over 10 users concurrently, just to give an example.
I only question the choice for the GET method. You'd normally only use it to retrieve data (SELECT), not to create/alter data (INSERT/UPDATE/DELETE). For that you'd normally use POST, so that no one can execute it "accidently" by just clicking a (bookmarked) link. Changing GET to POST isn't that hard, add method="post" to the <form> element and rename doGet() to doPost().
I have done some research, and majority of the examples I have found use forms (obviously for user input) to collect data which is then passed to another JSP page through the request object.
My question is: Is it possible to pass a parameter between JSP pages if the parameter hasn't been set in HTML <form> tags?
There are a few ways to pass information from one JSP page to another.
1. Hidden values.
Simply write the data to an input field within a form with the type 'hidden', e.g.
<input type="hidden" name="mydata" value="<%=thedata%>">
Data written thus will get posted back when the relevant form is submitted. This can be a useful way to 'carry along' information as the user fills out a series of dialogs as all state is user side and the back and forward buttons will work as expected.
2. URL writing.
Attach parameters to URLs in links on the page, e.g.
<a href="another.jsp?mydata=<%=thedata>>Go!</a>
This also maintains the state with the client while removing the need for a form element to be submitted.
3. Cookies.
Should speak for itself.The state is still user side but is now handled by a cookie. More fragile in some ways since some people disable cookies. Also the back and forward buttons may do unexpected things if you are not careful
4. Server side (session)
Finally you could store the data in a session variable on one JSP and retrieve it on the next, e.g.
session.setAttribute(String key, Object value)
and
session.getAttribute(String key)
Here the state is kept server side which has some benefits (the user can browse away and return without losing his place, but tends to make the back and forward buttons in the browser a bit unreliable unless you are careful. Also the value is available to all pages.
It does however have the advantage that the information is never sent to the client and is thus more secure and more tamper proof.
There's no way a JSP page can tell the difference between a manually constructed GET url, e.g.:
Go to the next JSP page, versus something like:
<form method="get" action="/foo.jsp">
<input name="bar" value="baz">
</form>
Either way it can be accessed through getParameter or getParameterValues
Is that what you're asking?
You usually pass data between servlet/JSP or JSP pages in scoped attributes (in request, session or application). E.g. request.setAttribute("key", data) can set "key" attribute in one JSP, and request.getAttribute("key") gets you this data in other JSP (if multiple JSPs are processing same request).
It is possible to create fake parameters by wrapping your request, and overriding getParameter and similar method, if that is what you really need.
Update: my answer is talking about passing data between several parties which all process same request. This may or may not be what you want, as your question isn't clear.