Random Posts




banner



How to Do the Login Page Validation in Servlet Updated FREE

How to Do the Login Page Validation in Servlet

In this Coffee servlet tutorial, I will guide y'all how to read values of mutual input fields from HTML form on the server side with Coffee Servlet.

You know, handling form data represented in HTML page is a very common task in web development. A typical scenario is the user fills in fields of a class and submits information technology. The server volition process the request based on the submitted data, and send response back to the client. The post-obit motion-picture show depicts that workflow with Coffee servlet on the server side:

form submit workflow

To create a form in HTML we demand to apply the post-obit tags:

    • <class>: to create a form to add fields in its body.
    • <input>, <select>, <textarea>…: to create form fields like text boxes, dropdown listing, text expanse, bank check boxes, radio buttons,… and submit button.

To make the class works with Coffee servlet, we need to specify the following attributes for the <grade> tag:

    • method="post": to ship the form data every bit an HTTP POST request to the server. By and large, form submission should be done in HTTP Mail method.
    • action="URL of the servlet": specifies relative URL of the servlet which is responsible for handling data posted from this form.

For example, post-obit is HTML code of a login form:

<grade proper name="loginForm" method="post" action="loginServlet"> 	Username: <input type="text" name="username"/> <br/> 	Password: <input type="password" name="countersign"/> <br/> 	<input type="submit" value="Login" /> </grade>

This course would wait similar this in browser:

Login Form example

On the server side, we need to create a Coffee servlet which is mapped to the URL: loginServlet, every bit specified in the course's action attribute. Following is code of the servlet:

@WebServlet("/loginServlet") public class LoginServlet extends HttpServlet {  	protected void doPost(HttpServletRequest request, 			HttpServletResponse response) throws ServletException, IOException {  		// code to process the form...  	}  }

Notice that the servlet'due south URL is specified by the @WebServlet annotation before the servlet course. When the user submits the login form higher up, the servlet'south doPost() method will be invoked by the servlet container. Typically we will practice the following tasks within doPost() method:

    • Read values of the fields posted from the form via the request object (implementation of javax.servlet.http.HttpServletRequest interface).
    • Practise some processing, due east.g. connecting to database to validate the username and password.
    • Return response dorsum to the user via the respone object (implementation of javax.servlet.http.HttpServletResponse interface).

To read values of form's fields, the HttpServletRequest interface provides the following methods:

    • Cord getParameter(Cord name) : gets value of a field which is specified by the given name, as a String. The method returns null if there is no class field exists with the given name.
    • String[] getParameterValues(Cord name) : gets values of a group of fields which have same name, in an array of Cord objects. The method returns null if there is no field exists with the given name.

Note that the above methods can also deal with parameters in URL's query cord, hence the name getParameter.

For example, we can write the following code in the doPost() method to read values of course's fields:

String username = request.getParameter("username"); String password = asking.getParameter("password");

To send response back to the client, we need to obtain a writer from the response object by calling the method getWriter() of the HttpServletResponse interface:

PrintWriter author = response.getWriter();

Then utilize the impress() or println() method to evangelize the response (in form of HTML code). For instance:

String htmlRespone = "<html>"; htmlRespone += "<h2>Your username is: " + username + "</h2>"; htmlRespone += "</html>";  writer.println(htmlRespone);

Here's complete code of the servlet form to process the login form:

package net.codejava.servlet;  import java.io.IOException; import java.io.PrintWriter;  import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;  @WebServlet("/loginServlet") public class LoginServlet extends HttpServlet {  	protected void doPost(HttpServletRequest asking, 			HttpServletResponse response) throws ServletException, IOException { 		 		// read form fields 		String username = request.getParameter("username"); 		String password = request.getParameter("password"); 		 		System.out.println("username: " + username); 		System.out.println("countersign: " + password);  		// do some processing here... 		 		// get response author 		PrintWriter writer = response.getWriter(); 		 		// build HTML code 		String htmlRespone = "<html>"; 		htmlRespone += "<h2>Your username is: " + username + "<br/>";		 		htmlRespone += "Your countersign is: " + password + "</h2>";		 		htmlRespone += "</html>"; 		 		// return response 		author.println(htmlRespone); 		 	}  }

Here'southward an case output when submitting the higher up login course in browser:

servlet response

And then far you take got the ins and outs when handling HTML form data with Coffee servlet. For your reference, we provide a listing of examples for treatment mutual HTML course fields as below. Notation that nosotros use the Arrangement.out.println() argument in servlet to demo the output.

ane. Read values of text field and password field

  • HTML code:
    Username: <input type="text" name="username"/> Password: <input type="password" name="password"/>            
  • Field image:text field and password field
  • Java code in servlet:
    String username = request.getParameter("username"); String countersign = request.getParameter("password");  System.out.println("username is: " + username); System.out.println("password is: " + password);            
  • Output:
username is: admin password is: nimda

ii. Read value of checkbox field

  • HTML code:
    Speaking language: <input type="checkbox" name="language" value="english language" />English <input type="checkbox" proper noun="language" value="french" />French            
  • Field paradigm:check box field
  • Java code in servlet:
    Cord languages[] = request.getParameterValues("language");  if (languages != zilch) { 	System.out.println("Languages are: "); 	for (String lang : languages) { 		System.out.println("\t" + lang); 	} }            
  • Output:
    Languages are: 	english 	french

3. Read value of radio button field

  • HTML code:
    Gender: <input blazon="radio" name="gender" value="male person" />Male <input type="radio" proper name="gender" value="female" />Female            
  • Field image:radio button field
  • Java code in servlet:
    String gender = request.getParameter("gender"); Arrangement.out.println("Gender is: " + gender);            
  • Output:
Gender is: male

4. Read value of text expanse field

  • HTML code:
    Feedback:<br/> <textarea rows="5" cols="30" name="feedback"></textarea>            
  • Field image:textarea field
  • Java code in servlet:
    String feedback = asking.getParameter("feedback"); System.out.println("Feed back is: " + feedback);            
  • Output:
Feed back is: This tutorial is very helpful. Thanks a lot!


v. Read value of dropdown listing (combobox) field

  • HTML lawmaking:
    Task Category: <select name="jobCat"> 	<option value="tech">Engineering science</pick> 	<selection value="admin">Administration</option> 	<pick value="biology">Biology</option> 	<selection value="scientific discipline">Science</option> </select>            
  • Field image:dropdown list field
  • Java code in servlet:
    Cord jobCategory = request.getParameter("jobCat"); Arrangement.out.println("Task category is: " + jobCategory);            
  • Output:
Job category is: science        

half dozen. Read information of file upload field

To create a form to upload file, we need to specify the enctype attribute for the <form> tag equally follow:

<course method="mail service" action="uploadServlet" enctype="multipart/form-data">  		Select file to upload: <input type="file" name="uploadFile" />  		<input type="submit" value="Upload" /> </form>

For handling file upload on the server side with Java servlet, we recommend these tutorials:

    • File upload servlet with Apache Common File Upload.
    • How to write upload file servlet with Servlet 3.0 API.

For the examples in this tutorial, you lot can download Eclipse-based projection too as deployable WAR file nether the attachments section.

 

Other Java Servlet Tutorials:

  • Java Servlet Quick Get-go for beginners (XML)
  • How to Create and Run Java Servlet for Beginners (Annotation)
  • Java Servlet and JSP How-do-you-do World Tutorial with Eclipse, Maven and Apache Tomcat
  • Coffee File Download Servlet Example
  • Upload file to servlet without using HTML form
  • How to apply Cookies in Java web application
  • How to utilize Session in Java spider web application

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in beloved with Java since so. Brand friend with him on Facebook and watch his Java videos you lot YouTube.

Add comment

How to Do the Login Page Validation in Servlet

DOWNLOAD HERE

Source: https://www.codejava.net/java-ee/servlet/handling-html-form-data-with-java-servlet

Posted by: walkerhemple.blogspot.com

0 Response to "How to Do the Login Page Validation in Servlet Updated FREE"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel