{"id":32,"date":"2013-02-18T03:58:34","date_gmt":"2013-02-18T03:58:34","guid":{"rendered":"http:\/\/localhost\/tfcom_wp\/2013\/02\/18\/simple-registration-application\/"},"modified":"2025-06-30T02:39:41","modified_gmt":"2025-06-30T02:39:41","slug":"simple-registration-application","status":"publish","type":"post","link":"https:\/\/www.tech-freaks.com\/java\/jsp-servlets\/simple-registration-application.html","title":{"rendered":"Simple Registration Application using JSP, Servlets and JDBC connectivity to MySQL"},"content":{"rendered":"<p style=\"text-align: left;\"><strong>Requirement<\/strong><\/p>\n<ul style=\"text-align: left;\">\n<li><span style=\"line-height: 1.3em;\">Create a Registration Form to enter user name, password, first name, last name, email address, secret question, answer and register a new user to system.<\/span><\/li>\n<li><span style=\"line-height: 1.3em;\">Validate if the user name and password is not blank. Display error message to user, if either of them is blank.<\/span><\/li>\n<li><span style=\"line-height: 1.3em;\">Validate if the user name already exists and display an error message to the user<\/span><\/li>\n<li><span style=\"line-height: 1.3em;\">In the event of an error, ensure that registration form is displayed again with all prefilled information<\/span><\/li>\n<li><span style=\"line-height: 1.3em;\">On successful registration, set the user name in session and forward to home page.<\/span><\/li>\n<\/ul>\n<p style=\"text-align: left;\"><strong style=\"line-height: 1.3em;\">Pre-requisites<\/strong><\/p>\n<ul style=\"text-align: left;\">\n<li><span style=\"line-height: 1.3em;\">MySQL and Tomcat is already installed<\/span><\/li>\n<li><span style=\"line-height: 1.3em;\">You have basic knowledge of MySQL to create tables and insert \/ update records<\/span><\/li>\n<li><span style=\"line-height: 1.3em;\">You have basic knowledge of Java and J2EE web applications<\/span><\/li>\n<li><span style=\"line-height: 1.3em;\">Have your favorite IDE for developing \/ reviewing code<\/span><\/li>\n<li><span style=\"line-height: 1.3em;\">This workshop adds the registration functionality to the previous article\u00a0<a title=\"Simple Login Application\" href=\"java\/jsp-servlets\/simple-login-application.html\" target=\"_blank\" rel=\"noopener noreferrer\">Simple Login Application<\/a>. Reviewing that article prior to this article would help.<\/span><\/li>\n<\/ul>\n<p style=\"text-align: left;\"><strong style=\"line-height: 1.3em;\">Concepts Covered<\/strong><\/p>\n<ul style=\"text-align: left;\">\n<li><span style=\"line-height: 1.3em;\">JDBC connectivity to MySQL from Servlet<\/span><\/li>\n<li><span style=\"line-height: 1.3em;\">Simple application of JSTL tag<\/span><\/li>\n<li><span style=\"line-height: 1.3em;\">Using request attribute and request parameters<\/span><\/li>\n<li><span style=\"line-height: 1.3em;\">Basic error handling concepts<\/span><\/li>\n<\/ul>\n<p style=\"text-align: left;\"><strong>NOTE<\/strong>: Don&#8217;t even think of using the code as is for a production environment<br \/>\nThis is just for education purpose but you can take inspiration from this code.<\/p>\n<p><!--more--><\/p>\n<p style=\"text-align: left;\"><strong>Analysis and Design<\/strong><\/p>\n<p style=\"text-align: left;\"><span style=\"line-height: 1.3em;\">We start with the\u00a0<a title=\"Simple Login Application\" href=\"jsp-servlets\/simple-login-application.html\" target=\"_blank\" rel=\"noopener noreferrer\">Simple Login application<\/a>\u00a0article as a baseline. First, we need to update the database to add more fields and constraints. We will make the user_name field as the primary key for the USERS table.<\/span><\/p>\n<p style=\"text-align: left;\"><span style=\"line-height: 1.3em;\">We create a new class for database connectivity code unlike in the simple login application and refactor the connectivity code out of the Servlet code. This is a good design practice to keep the servlet layer uncoupled to the database code layer. We would still following the MVC design model.<\/span><\/p>\n<p style=\"text-align: left;\"><span style=\"line-height: 1.3em;\">Below is a list of elements identified as part of the design:<\/span><\/p>\n<ul style=\"text-align: left;\">\n<li><span style=\"line-height: 1.3em;\"><em>com.techfreaks.db.util.ConnectionUtil<\/em>\u00a0&#8211; Utility class for getting connection, closing connection and executing insert \/ update query<\/span><\/li>\n<li><span style=\"line-height: 1.3em;\"><em>com.techfreaks.registration.servlet.RegistrationServlet<\/em>\u00a0&#8211; This servlet is the controller. It calls the ConnectionUtil and forwards to the home page or Registration page<\/span><\/li>\n<li><span style=\"line-height: 1.3em;\"><em>RegistrationForm.jsp<\/em>\u00a0&#8211; UI page with fields for registration form<\/span><\/li>\n<li><span style=\"line-height: 1.3em;\"><em>Home.jsp<\/em>\u00a0&#8211; UI page picked up after successful registration. It is the same page taken from Login Application<\/span><\/li>\n<li><span style=\"line-height: 1.3em;\"><em>web.xml<\/em> &#8211; Deployment Descriptor in which the servlet is registered.<\/span><\/li>\n<\/ul>\n<p style=\"text-align: left;\"><strong style=\"line-height: 1.3em;\">Development<\/strong><\/p>\n<p style=\"text-align: left;\"><em>Setup the database:<\/em><\/p>\n<p style=\"text-align: left;\">We alter the USERS table to add the new fields. However, for quick reference we provide the create USERS table DDL. You will have to drop and recreate the table using the below DML, if you already have an USER table. You could very well manually edit the existing table based on the below DDL.<\/p>\n<pre class=\"brush:sql\" style=\"text-align: left;\">CREATE TABLE `users` (\n\t`first_name` VARCHAR(100) NOT NULL,\n\t`last_name` VARCHAR(100) NOT NULL,\n\t`email_address` VARCHAR(50) NOT NULL,\n\t`secret_question` VARCHAR(200) NULL DEFAULT NULL,\n\t`secret_answer` VARCHAR(200) NULL DEFAULT NULL,\n\t`user_name` VARCHAR(100) NOT NULL,\n\t`password` VARCHAR(100) NOT NULL,\n\tPRIMARY KEY (`user_name`)\n)\nCOLLATE='latin1_swedish_ci'\nENGINE=InnoDB;\n<\/pre>\n<p style=\"text-align: left;\">A screenshot of the development environment is provided below. Make sure the mysql drivers, jstl libraries and tlds are all available. For making your life easy, we have included a hot deployable WAR file at the end of the workshop.<\/p>\n<p style=\"text-align: left;\"><img fetchpriority=\"high\" decoding=\"async\" title=\"Simple Registration App Environment Folder structure\" src=\"https:\/\/www.tech-freaks.com\/wp-content\/uploads\/2013\/02\/registrationapp_env_setup.png\" alt=\"Simple Registration App Environment Folder structure\" width=\"316\" height=\"371\" border=\"0\" \/><\/p>\n<hr class=\"system-pagebreak\" title=\"Coding and Unit Testing\" \/>\n<p style=\"text-align: left;\"><strong>Coding and Unit testing:<\/strong><\/p>\n<p style=\"text-align: left;\"><span style=\"line-height: 1.3em;\">First, we would look at the ConnectionUtil. Below are the methods we would need for the ConnectionUtil. Note that we create this class as a static class (A class with static methods).\u00c3\u201a\u00a0<\/span><\/p>\n<p style=\"text-align: left;\">&#8211;\u00a0<em>getConnection()<\/em><br \/>\n<em>&#8211; closeConnection()<\/em><br \/>\n<em>&#8211; executeQuery(String strQuery)<\/em><\/p>\n<p style=\"text-align: left;\">If you have read the article about simple login application, you would have already noticed thatt we just refactored the first two methods out of the LoginServlet. We prevent the code to be spread across multiple servlets this way. It is used to get a SQL Connection object and to close an open connection respectively.<\/p>\n<p style=\"text-align: left;\">In this example, we would use\u00a0<em>java.sql.Statement<\/em>\u00a0instead of\u00a0<em>java.sql.PrepareStatement<\/em>\u00a0which we used in LoginServlet, to spice things up. We need to pass the complete query to the Statement object to execute a query. The executeQuery can take an insert \/ update query and execute it. It would internally call getConnection() and closeConnection() to fetch and close a connection.<\/p>\n<p style=\"text-align: left;\">Below is the method executeQuery:<\/p>\n<pre class=\"language-java\"><code>public static void executeQuery(String strQuery) throws Exception {\n\t\tConnection conn = null;\n\t\t\n\t\ttry {\n\t\t\tconn = getConnection();\n\t\t\tStatement stmt  = conn.createStatement();\n\t\t\tstmt.executeUpdate(strQuery);\n\t\t\t\n\t\t} catch (SQLException sqle) {\n\t\t\tSystem.out.println(\"SQLException: Unable to execute query : \"+strQuery);\n\t\t\tthrow sqle;\n\t\t} catch (Exception e) {\n\t\t\tSystem.out.println(\"Exception: Unable to execute query: \"+strQuery);\n\t\t\tthrow e;\n\t\t} finally {\n\t\t\tcloseConnection(conn);\n\t\t}\n\t}<\/code><\/pre>\n<pre class=\"brush:java\" style=\"text-align: left;\"><\/pre>\n<p style=\"text-align: left;\">We also moved the static variables like database name, db user name and db password from the servlet to the ConnectionUtil.<\/p>\n<pre class=\"language-java\"><code>        private static final String DBNAME = \"tf_loginappdb\";\n\tprivate static final String DB_USERNAME = \"root\";\n\tprivate static final String DB_PASSWORD = \"admin*\";<\/code><\/pre>\n<pre style=\"text-align: left;\"><\/pre>\n<p style=\"text-align: left;\">If your database has different dbname, username or password, you will need to update this and recompile you java file for the application to be able to connect to MySQL database.<\/p>\n<p>Next, we would look at the code in the RegistrationServlet. It gets all the fields from the RegistrationForm in the request parameters. Below are the methods which we would add to this servlet.<\/p>\n<p style=\"text-align: left;\"><em>&#8211; doPost()<\/em><br \/>\n<em>&#8211; validateData()<\/em><br \/>\n<em>&#8211; setRequestAttributes()<\/em><br \/>\n<em>&#8211; generateInsertQuery()<\/em><\/p>\n<p style=\"text-align: left;\">The doPost is the entry point to the servlet for html form POST. We have all the controller logic in here. The other methods are in a way, do not do the controller work. We use them for simple tasks which do not warranty creating other classes in our case. However, in a real life application, if the task is complex we might want to create new classes to delegate the task.<\/p>\n<p style=\"text-align: left;\">validateData() is used to implement the requirement that the userName and password cannot be empty. It validates and returns a boolean indicating success or failure of the validation.<\/p>\n<p style=\"text-align: left;\">generateInsertQuery() fetches the request parameters and generates the insert query which will be passed on to the executeQuery method of the ConnectionUtil. Below is the code for the method:<\/p>\n<pre class=\"brush:java\" style=\"text-align: left;\"><\/pre>\n<pre class=\"language-java\"><code> private String generateInsertQuery(HttpServletRequest request) {\n\t\tString strUserName = request.getParameter(\"userName\");\n\t\tString strPassword = request.getParameter(\"password\");\n\t\tString strFirstName = request.getParameter(\"firstName\");\n\t\tString strLastName = request.getParameter(\"lastName\");\n\t\tString strEmail = request.getParameter(\"email\");\n\t\tString strSecretQuestion = request.getParameter(\"secretQuestion\");\n\t\tString strSecretAnswer = request.getParameter(\"secretAnswer\");\n\n\t\tStringBuffer strQuery = new StringBuffer(INSERT_QUERY_START);\n\t\tstrQuery.append(strFirstName);\n\t\tstrQuery.append(\"', '\");\n\t\tstrQuery.append(strLastName);\n\t\tstrQuery.append(\"', '\");\n\t\tstrQuery.append(strEmail);\n\t\tstrQuery.append(\"', '\");\n\t\tstrQuery.append(strSecretQuestion);\n\t\tstrQuery.append(\"', '\");\n\t\tstrQuery.append(strSecretAnswer);\n\t\tstrQuery.append(\"', '\");\n\t\tstrQuery.append(strUserName);\n\t\tstrQuery.append(\"', '\");\n\t\tstrQuery.append(strPassword);\n\t\tstrQuery.append(\"')\");\n\t\t\n\t\tSystem.out.println(\"Insert query : \"+strQuery.toString());\n\t\t\n\t\treturn strQuery.toString();\n\n\t}\n <\/code><\/pre>\n<pre class=\"brush:java\" style=\"text-align: left;\">\nsetRequestAttributes() is used to implement the requirement about maintaining the data entered in the registration form in the even of an error. Do you remember banging your head against the keyboard after filling up a long registration form and clicking submit, only to find the form reloading with an error message and all the data you entered spending hours, boom! gone!<img decoding=\"async\" title=\"Yell\" data-src=\"media\/editors\/tinymce\/jscripts\/tiny_mce\/plugins\/emotions\/img\/smiley-yell.gif\" alt=\"Yell\" border=\"0\" src=\"data:image\/svg+xml;base64,PHN2ZyB3aWR0aD0iMSIgaGVpZ2h0PSIxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjwvc3ZnPg==\" class=\"lazyload\" \/><\/pre>\n<p style=\"text-align: left;\">Instead of the classic get each parameter and set to attribute, we would just do a generic loop through. This would keep the code small. Imagine your registration form is 100 fields instead, the below code will not require any modification. Below is the code:<\/p>\n<pre class=\"language-java\"><code>\tprivate void setRequestAttributes(HttpServletRequest request) {\n\t\tEnumeration  enumKeys =  request.getParameterNames();\n\t\twhile(enumKeys.hasMoreElements()) {\n\t\t\tString key  = enumKeys.nextElement();\n\t\t\trequest.setAttribute(key, request.getParameter(key))  ;\n\t\t}\n\t} <\/code><\/pre>\n<pre class=\"brush:java\" style=\"text-align: left;\"><\/pre>\n<p style=\"text-align: left;\">The doPost() method is provided below. It has inline comment to explain key control logic. Once the insert in the database is successful, we set the userName is session and redirect to Home.jsp.<\/p>\n<p style=\"text-align: left;\">The error messages are managed by putting a request attribute on error situation and forwarding back to RegistrationForm. You will see the difference between the redirect and forward. You will see that the request attributes are available and also the URL of the servlet remains the same after the request is forwarded to the JSP. Also, note how we utilize the primary key duplicate error message and set the error message. We use the same pattern to set error message, set the request attributes and forward to registration page on all the error conditions.<\/p>\n<pre class=\"language-java\"><code>protected void doPost(HttpServletRequest request, HttpServletResponse \n\t\t\tresponse) throws ServletException, IOException {\n\t\t\n\t\tString strUserMsg = null;\n\t\tHttpSession session = request.getSession();\n\t\tRequestDispatcher reqDisp =  request.getRequestDispatcher(REGISTRATION_PAGE);\n\t\t\n\t\ttry {\n\t\t\t\/\/Check if data is valid\n\t\t\tif(validateData(request)) {\n\t\t\t\tConnectionUtil.executeQuery(generateInsertQuery(request));\n\t\t\t\tSystem.out.println(\"Insert into database successful\");\n\t\t\t\tsession.setAttribute(\"userName\", request.getParameter(\"userName\"));\n\t\t\t\tresponse.sendRedirect(getServletContext().getContextPath()+HOME_PAGE);\n\t\t\t} else {\/\/If data is invalid\n\t\t\t\tstrUserMsg = \"User Name and Password cannot be empty\";\n\t\t\t\tsetRequestAttributes(request);\n\t\t\t\trequest.setAttribute(\"userMsg\", strUserMsg);\n\t\t\t\treqDisp.forward(request, response);\n\t\t\t}\n\t\t\t\n\t\t} catch(SQLException sqle ) {\n\t\t\tSystem.out.println(\"Unable to register user: \"+sqle.getMessage());\n\t\t\t\/\/Check if we are getting duplicate key exception on userName\n\t\t\tif(sqle.getMessage().indexOf(\"Duplicate entry\")!=-1) {\n\t\t\t\tSystem.out.println(\"User already exists\");\n\t\t\t\tstrUserMsg = \"User name \"+request.getParameter(\"userName\")+\" already \" +\n\t\t\t\t\t\t\"exists. Please try another user name.\";\n\t\t\t} else { \/\/If other SQLException than dup key exception\n\t\t\t\tstrUserMsg = \"Unable to register user \"+request.getParameter(\"userName\")+\n\t\t\t\t\". Please try again later.\";\n\t\t\t}\n\t\t\tsetRequestAttributes(request);\n\t\t\trequest.setAttribute(\"userMsg\", strUserMsg);\n\t\t\treqDisp.forward(request, response);\n\n\t\t} catch(Exception e) {\/\/If it goes into Exception other than SQLException\n\t\t\tSystem.out.println(\"Unable to register user: \"+e.getMessage());\n\t\t\tstrUserMsg = \"Unable to register user \"+request.getParameter(\"userName\")\n\t\t\t+\". Please try again later.\";\n\t\t\tsetRequestAttributes(request);\n\t\t\trequest.setAttribute(\"userMsg\", strUserMsg);\n\t\t\treqDisp.forward(request, response);\n\n\t\t}\n\t\t\n\t\t\n\n\t}<\/code><\/pre>\n<pre class=\"brush:java\" style=\"text-align: left;\"><\/pre>\n<p style=\"text-align: left;\">Next, let us look at our RegistrationForm.jsp. We highlight small snippet of code here<\/p>\n<pre class=\"language-markup\"><code>&lt;p&gt;&lt;font color=\"#ff0000\"&gt;&lt;c:out value=\"${userMsg}\"\/&gt;&lt;\/font&gt;&lt;\/p&gt;\n&lt;form name=\"frmRegistration\" method=\"post\" action=\"&lt;c:out value=\"${pageContext.servletContext.contextPath}\" \/&gt;\/servlet\/RegistrationServlet\"&gt;\n&lt;table border=\"1\"&gt;\n&lt;tbody&gt;\n&lt;tr&gt;\n&lt;td&gt;First Name&lt;\/td&gt;\n&lt;td&gt;&lt;input type=\"text\" name=\"firstName\" value =\"&lt;c:out value=\"${firstName}\"\/&gt;\" size=\"20\"&gt;&lt;\/td&gt;<\/code><\/pre>\n<ul style=\"text-align: left;\">\n<li><span style=\"line-height: 1.3em;\">JSTL is used display the userMsg which we set in the request attribute in our servlet.<\/span><\/li>\n<li><span style=\"line-height: 1.3em;\">JSTL is used to pick the contextPath from servletContext<\/span><\/li>\n<li><span style=\"line-height: 1.3em;\">JSTL is used to display user entered data in the event of an error<\/span><\/li>\n<\/ul>\n<p style=\"text-align: left;\">We picked up the Home.jsp from the simple login application. You can get the complete WAR file to the simple registration application by clicking\u00a0<a title=\"SimpleRegistrationApp\" href=\"sourcecode\/SimpleRegistrationApp\/SimpleRegistrationApp.war\" target=\"_blank\" rel=\"noopener noreferrer\">SimpleRegistrationApp.war<\/a>.<\/p>\n<p style=\"text-align: left;\">You just need to hot deploy SimpleRegistrationApp.war to webapps folder in the Tomcat program file and it would explode. Verify the application by accessing http:\/\/localhost:8080\/SimpleRegistrationApp\/RegistrationForm.jsp and run some tests to figure out how it works for you.<\/p>\n<p style=\"text-align: left;\">Feel free to leave a comment below, if you run into any issues. Enjoy!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Requirement Create a Registration Form to enter user name, password, first name, last name, email address, secret question, answer and [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":31,"comment_status":"open","ping_status":"open","sticky":true,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[10],"tags":[],"class_list":["post-32","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-jsp-servlets"],"_links":{"self":[{"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/posts\/32","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/comments?post=32"}],"version-history":[{"count":1,"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/posts\/32\/revisions"}],"predecessor-version":[{"id":144,"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/posts\/32\/revisions\/144"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/media\/31"}],"wp:attachment":[{"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/media?parent=32"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/categories?post=32"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/tags?post=32"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}