Get and post in servlet in java

Parameters, GET and POST methods in Servlets.

The parameters are the way in which a client or user can send information to the Http Server. For example, in a login screen, we need to send to the server, the user and the password so that it validates them.

How does the client or the Browser send these parameters using the methods GET or POST, is explained in the tutorial Web Server or HTTP Server. What we are going to see in this tutorial is how to recover this information in the server, using the API Servlet.

The first thing we are going to do is to create in our site a page «login.html» with the following content:

Then, we create a Servlet which receives the request in /login , which is the indicated direction in the action attribute of the tag of login.html

package com.edu4java.servlets; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginServlet extends HttpServlet < @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException < String user = req.getParameter("user"); String pass = req.getParameter("password"); if ("edu4java".equals(user) && "eli4java".equals(pass)) < response(resp, "login ok"); >else < response(resp, "invalid login"); >> private void response(HttpServletResponse resp, String msg) throws IOException < PrintWriter out = resp.getWriter(); out.println(""); out.println(""); out.println("" + msg + ""); out.println(""); out.println(""); > >

We compilate this Servlet and we include LoginServlet.class in the folder /WEB-INF/classes. We modify web.xml to link /login with this Servlet.

 

timeservlet
com.edu4java.servlets.FirstServlet


login-servlet
com.edu4java.servlets.LoginServlet


timeservlet
/what-time-is-it


login-servlet
/login

We restart the server, open the page login.html, write an «x» in user, write an «x» in password and click on the submit button.

indicating that the login has failed. If we repeate the operation with «edu4java» as user and «eli4java» as password we obtain

The problem here is that the secret password is visible in the URL …/login?user=edu4java&password=eli4java, it will be kept in the history of the Browser and anybody who access the Browser after us can obtain it easily. This can be solved changing the way of sending the form and using the method POST in login.html.

Читайте также:  Php object type test

Reusing login.html, we will use the following error.

What is happening here is that we haven´t implemented the doPost method (we have only implemented doGet), so our Servlet is not able to receive POST requests. In the following code we can see the necessary modifications to make it work.

package com.edu4java.servlets; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginServlet extends HttpServlet < @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException < String user = req.getParameter("user"); String pass = req.getParameter("password"); if ("edu4java".equals(user) && "eli4java".equals(pass)) < response(resp, "login ok"); >else < response(resp, "invalid login"); >> private void response(HttpServletResponse resp, String msg) throws IOException < PrintWriter out = resp.getWriter(); out.println(""); out.println(""); out.println("" + msg + ""); out.println(""); out.println(""); > >

The only change is the replacement of doGet for doPost. After the recompilation, the deployment of the Servlet, the restart of the server and the reuse of login.html we obtain

We can see that the parameters of the URL have dissapeared.

Источник

Servlets — Form Data

You must have come across many situations when you need to pass some information from your browser to web server and ultimately to your backend program. The browser uses two methods to pass this information to web server. These methods are GET Method and POST Method.

GET Method

The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? (question mark) symbol as follows −

http://www.test.com/hello?key1 = value1&key2 = value2

The GET method is the default method to pass information from browser to web server and it produces a long string that appears in your browser’s Location:box. Never use the GET method if you have password or other sensitive information to pass to the server. The GET method has size limitation: only 1024 characters can be used in a request string.

This information is passed using QUERY_STRING header and will be accessible through QUERY_STRING environment variable and Servlet handles this type of requests using doGet() method.

Читайте также:  Python numpy array copy

POST Method

A generally more reliable method of passing information to a backend program is the POST method. This packages the information in exactly the same way as GET method, but instead of sending it as a text string after a ? (question mark) in the URL it sends it as a separate message. This message comes to the backend program in the form of the standard input which you can parse and use for your processing. Servlet handles this type of requests using doPost() method.

Reading Form Data using Servlet

Servlets handles form data parsing automatically using the following methods depending on the situation −

  • getParameter() − You call request.getParameter() method to get the value of a form parameter.
  • getParameterValues() − Call this method if the parameter appears more than once and returns multiple values, for example checkbox.
  • getParameterNames() − Call this method if you want a complete list of all parameters in the current request.

GET Method Example using URL

Here is a simple URL which will pass two values to HelloForm program using GET method.

http://localhost:8080/HelloForm?first_name = ZARA&last_name = ALI

Given below is the HelloForm.java servlet program to handle input given by web browser. We are going to use getParameter() method which makes it very easy to access passed information −

Assuming your environment is set up properly, compile HelloForm.java as follows −

If everything goes fine, above compilation would produce HelloForm.class file. Next you would have to copy this class file in /webapps/ROOT/WEB-INF/classes and create following entries in web.xml file located in /webapps/ROOT/WEB-INF/

 HelloForm HelloForm  HelloForm /HelloForm  

Now type http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI in your browser’s Location:box and make sure you already started tomcat server, before firing above command in the browser. This would generate following result −

GET Method Example Using Form

Here is a simple example which passes two values using HTML FORM and submit button. We are going to use same Servlet HelloForm to handle this input.

Keep this HTML in a file Hello.htm and put it in /webapps/ROOT directory. When you would access http://localhost:8080/Hello.htm, here is the actual output of the above form.

Try to enter First Name and Last Name and then click submit button to see the result on your local machine where tomcat is running. Based on the input provided, it will generate similar result as mentioned in the above example.

Читайте также:  Java class reference list

POST Method Example Using Form

Let us do little modification in the above servlet, so that it can handle GET as well as POST methods. Below is HelloForm.java servlet program to handle input given by web browser using GET or POST methods.

Now compile and deploy the above Servlet and test it using Hello.htm with the POST method as follows −

Here is the actual output of the above form, Try to enter First and Last Name and then click submit button to see the result on your local machine where tomcat is running.

Based on the input provided, it would generate similar result as mentioned in the above examples.

Passing Checkbox Data to Servlet Program

Checkboxes are used when more than one option is required to be selected.

Here is example HTML code, CheckBox.htm, for a form with two checkboxes

The result of this code is the following form

Given below is the CheckBox.java servlet program to handle input given by web browser for checkbox button.

    \n» + «
  • Maths Flag : : » + request.getParameter(«maths») + «\n» + «
  • Physics Flag: : » + request.getParameter(«physics») + «\n» + «
  • Chemistry Flag: : » + request.getParameter(«chemistry») + «\n» + «

For the above example, it would display following result −

Reading All Form Parameters

Following is the generic example which uses getParameterNames() method of HttpServletRequest to read all the available form parameters. This method returns an Enumeration that contains the parameter names in an unspecified order

Once we have an Enumeration, we can loop down the Enumeration in standard way by, using hasMoreElements() method to determine when to stop and using nextElement() method to get each parameter name.

Now, try the above servlet with the following form −

Now calling servlet using the above form would generate the following result −

Reading All Form Parameters

Param Name Param Value(s)
maths on
chemistry on

You can try the above servlet to read any other form’s data having other objects like text box, radio button or drop down box etc.

Источник

Оцените статью