Java Printwrite Print Html Template?
- Details
- Written past
- Final Updated on 11 March 2020 | Print Electronic mail
In this Java servlet tutorial, I will guide you how to read values of common input fields from HTML form on the server side with Java 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 form and submits it. The server volition process the request based on the submitted data, and transport response back to the client. The following picture depicts that workflow with Coffee servlet on the server side:
To create a course in HTML we need to use the following tags:
-
- <form>: to create a form to add fields in its body.
- <input>, <select>, <textarea>…: to create form fields similar text boxes, dropdown list, text expanse, check boxes, radio buttons,… and submit button.
To make the form works with Java servlet, we demand to specify the following attributes for the <form> tag:
-
- method="post": to ship the class data as an HTTP POST request to the server. Generally, course submission should exist done in HTTP Postal service method.
- action="URL of the servlet": specifies relative URL of the servlet which is responsible for handling information posted from this class.
For instance, following is HTML lawmaking of a login form:
<form proper noun="loginForm" method="postal service" action="loginServlet"> Username: <input type="text" proper noun="username"/> <br/> Password: <input type="password" name="password"/> <br/> <input type="submit" value="Login" /> </form>
This grade would look like this in browser:
On the server side, nosotros demand to create a Coffee servlet which is mapped to the URL: loginServlet, as specified in the form'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... } } Discover that the servlet'south URL is specified by the @WebServlet annotation before the servlet grade. When the user submits the login form above, the servlet's doPost() method volition be invoked past the servlet container. Typically we will practice the following tasks inside doPost() method:
-
- Read values of the fields posted from the course 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 back to the user via the respone object (implementation of javax.servlet.http.HttpServletResponse interface).
To read values of form'due south fields, the HttpServletRequest interface provides the following methods:
-
- Cord getParameter(String proper name) : gets value of a field which is specified by the given name, as a String. The method returns null if there is no form field exists with the given proper name.
- String[] getParameterValues(Cord proper name) : gets values of a grouping of fields which accept same name, in an array of String objects. The method returns naught if there is no field exists with the given name.
Notation that the above methods can also deal with parameters in URL'due south query string, hence the name getParameter.
For case, we tin can write the post-obit code in the doPost() method to read values of course'southward fields:
String username = request.getParameter("username"); String password = request.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 writer = response.getWriter();
Then use the print() or println() method to deliver 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'south complete code of the servlet class to process the login course:
packet cyberspace.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 request, HttpServletResponse response) throws ServletException, IOException { // read form fields String username = asking.getParameter("username"); String password = asking.getParameter("password"); System.out.println("username: " + username); System.out.println("password: " + password); // do some processing here... // get response writer PrintWriter writer = response.getWriter(); // build HTML lawmaking String htmlRespone = "<html>"; htmlRespone += "<h2>Your username is: " + username + "<br/>"; htmlRespone += "Your password is: " + password + "</h2>"; htmlRespone += "</html>"; // render response writer.println(htmlRespone); } } Hither's an example output when submitting the above login form in browser:
So far yous have got the ins and outs when treatment HTML form information with Java servlet. For your reference, nosotros provide a list of examples for handling common HTML form fields as below. Note that we use the System.out.println() argument in servlet to demo the output.
ane. Read values of text field and password field
- HTML code:
Username: <input type="text" proper noun="username"/> Password: <input type="password" name="password"/>
- Field prototype:
- Coffee code in servlet:
String username = request.getParameter("username"); Cord countersign = asking.getParameter("password"); System.out.println("username is: " + username); System.out.println("password is: " + countersign); - Output:
username is: admin password is: nimda
ii. Read value of checkbox field
- HTML lawmaking:
Speaking linguistic communication: <input type="checkbox" proper noun="language" value="english" />English language <input type="checkbox" proper noun="language" value="french" />French
- Field prototype:
- Coffee code in servlet:
Cord languages[] = asking.getParameterValues("linguistic communication"); if (languages != zilch) { System.out.println("Languages are: "); for (String lang : languages) { Organisation.out.println("\t" + lang); } } - Output:
Languages are: english french
3. Read value of radio push field
- HTML code:
Gender: <input type="radio" proper name="gender" value="male person" />Male person <input type="radio" name="gender" value="female" />Female
- Field image:
- Java code in servlet:
String gender = request.getParameter("gender"); System.out.println("Gender is: " + gender); - Output:
Gender is: male person
iv. Read value of text area field
- HTML code:
Feedback:<br/> <textarea rows="5" cols="30" name="feedback"></textarea>
- Field image:
- Java code in servlet:
String feedback = asking.getParameter("feedback"); Arrangement.out.println("Feed back is: " + feedback); - Output:
Feed back is: This tutorial is very helpful. Thanks a lot!
5. Read value of dropdown list (combobox) field
- HTML code:
Job Category: <select name="jobCat"> <option value="tech">Technology</selection> <option value="admin">Assistants</selection> <option value="biology">Biology</choice> <option value="science">Scientific discipline</selection> </select>
- Field paradigm:
- Coffee code in servlet:
Cord jobCategory = request.getParameter("jobCat"); System.out.println("Job category is: " + jobCategory); - Output:
Job category is: science
6. Read data of file upload field
To create a form to upload file, we need to specify the enctype aspect for the <form> tag as follow:
<grade method="mail" activity="uploadServlet" enctype="multipart/class-data"> Select file to upload: <input blazon="file" name="uploadFile" /> <input type="submit" value="Upload" /> </form>
For treatment file upload on the server side with Coffee servlet, we recommend these tutorials:
-
- File upload servlet with Apache Mutual File Upload.
- How to write upload file servlet with Servlet iii.0 API.
For the examples in this tutorial, you can download Eclipse-based project as well as deployable WAR file under the attachments section.
Other Java Servlet Tutorials:
- Java Servlet Quick Start for beginners (XML)
- How to Create and Run Java Servlet for Beginners (Annotation)
- Java Servlet and JSP Hello World Tutorial with Eclipse, Maven and Apache Tomcat
- Java File Download Servlet Case
- Upload file to servlet without using HTML form
- How to use Cookies in Java web application
- How to use Session in Coffee 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 Coffee i.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.
Add comment
Java Printwrite Print Html Template?,
Source: https://www.codejava.net/java-ee/servlet/handling-html-form-data-with-java-servlet
Posted by: morristhadell.blogspot.com

0 Response to "Java Printwrite Print Html Template?"
Post a Comment