There are lots of ways of creating a Login form by using Servlets or PHP or JSP, etc. Another such way is using Struts 2.0 framework. The main purpose of creating this tutorial was to demonstrate a clear way of using Struts 2 as many websites have still not updated their blogs and show demonstration using Struts 1.3.x only, which is a bit different from Struts 2.
NOTE: This tutorial is for creating a simple login form using Struts 2 in NetBeans only. Disclaimer: I do not own any content. The following procedure is an amalgamation of different procedures and codes available on the Internet such as: StackOverflow, JavaTPoint, Java4s, videos on YouTube, etc. Let's begin. Prerequisite:
Installations:
If you've never installed Struts 2, don't worry. Just follow the below procedure:
Procedure: To create a login form using Struts 2, we will be creating the following 4 files:
<html> <head> <title>Login using Struts 2</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <form action="login" method="post"> Username: <input type="text" id="username" name="username"><br><br> Password: <input type="password" id="password" name="password"><br><br> <input type="submit" value="Submit"> </form> </body> </html> Your index.html file should look something like this:
<h1> Wrong Username or Password!</h1> Your error.jsp page should look like this:
String username, password;
public String execute(){ if(username.equals("universe") && password.equals("galaxy")){ return "SUCCESS"; }else{ return "ERROR"; } }
<action name="login" class="login.LoginAction"> <result name="SUCCESS">/success.jsp</result> <result name="ERROR">/error.jsp</result> </action> So if the execute() function returns value "SUCCESS" then struts.xml will redirect to success.jsp else it'll redirect to error.jsp. Your struts.xml file will look like this.
<%@taglib uri="/struts-tags" prefix="s" %> in the top just after the <%@ page contentType="..... %>.
<h1>Hello <s:property value="username"/>!</h1> <s:property value="username"/> will fetch the name the user had entered in the username text-field during login.
You're all ready now. Compile and run index.html using Shift + F6. The following page will open:
When I enter the correct details, I am greeted with success.jsp.
Whereas, when I enter the wrong details, I get the error.jsp page.
This was a basic login page. You can add CSS, JavaScript, jQuery, etc. to add more functionalities and features to your page.
That's it. An easy way to implement a login page using Struts 2 in NetBeans. NOTE: You can access the entire code here. Try it out yourself and let me know about any errors or doubts you may have in the comments section below.
1 Comment
|
Archives
December 2018
Categories
|