How to create a login system in struts2 using mysql database

Share:
How to create a login system in struts2 using MySql Database?

Hello readers in this article you are going to learn how to create a login system in struts2 framework using SessionAware interface which is used to put information in the scope on session.
-This example contains view components bloglogin.jsp, invalid_username.jsp, invalid_password.jsp,  blogloginsuccess.jsp .

-When user enter valid username and password then user will be redirected to bloglogingsucces.jsp and displaying welcome username and you are the user count like 1st, 2nd ....3rd etc.

-If user entered invalid username then user will be redirected to invalid_username.jsp which include bloglogin.jsp and similarly for invalid password on invalid_password.jsp .

Here i am using MySql Databse name as mysql@123 and a table name as login with username and password column. I have inserted username as VIRAT and password as KOHLI in my login table.
  
Example of login system using struts2 with MySql Databse?
In this example create the following files
  1.        .bloglogin.jsp to take input from the users.
  2.      Struts.xml in src to define action and result.
  3.      Deployment descriptor i.e., web.xml  .
  4.      DbConnection class to create the connection with MySql database.
  5.      LoginActin.java to authenticate the users credentials.
  6.      blogloginsuccess.jsp
  7.      invalid_username.jsp for invalid userame.
  8.      invalid_password.jsp for invalid_password.
1)Create bloglogin.jsp
This bloglogin.jsp file is responsible to take input from the users. 
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ taglib uri="/struts-tags" prefix="s" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body><br/><br/>
<center>
<h3>
 <font color="red">Please Login...</font>
<s:form action="bloglogin"> 
<s:textfield name="username" label="UserName"></s:textfield> 
<s:password name="password" label="Password"></s:password> 
<s:submit value="login"></s:submit>
</s:form>
</h3> 
</center>
</body>
</html>

2)Create struts.xml in src directory.
This is the center of our application or in a simple way this is our control room of our application.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
    "http://struts.apache.org/dtds/struts-2.5.dtd">
   
<struts>
  <package name="default" extends="struts-default">
    <action name="bloglogin" class="com.Blog.Actions.LoginAction" method="blogexecute">
       <result name="success">/blogloginsuccess.jsp</result>
       <result name="invalid_username">/invalid_username.jsp</result>
       <result name="invalid_password">/invalid_password.jsp</result>
      </action>
  </package>
</struts>

3)web.xml
This file defines mapping between URL path's and handle the requests with those path and provides configuration and deployment information for the web componens. Here in example our welcome file is bloglogin.jsp so whenever we run our application bloglogin.jsp will be displayed first.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <welcome-file-list>
    <welcome-file>bloglogin.jsp</welcome-file>
  </welcome-file-list>
  <filter>
    <filter-name>struts</filter-name>
    <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</weba-pp>

4)Create DbConnection.java
The job DbConnection.java class is to establish the connection with MySql databse and return the instance of connection i.e., conn in this case and this conn will be used in LoginAction.java class where we will validate the users credentials.  
package com.Blog.Actions;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DbConnection {
private Connection conn=null;

public Connection getConnect(){
try {
     Class.forName("com.mysql.jdbc.Driver");
     conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql@123", "root","");
     } catch (ClassNotFoundException e) {
            System.out.println("Connection Refused"+ e.getMessage());
     } catch (SQLException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
     }
return conn;
}//end of getConnect() method
}//end of class

5)Creating LoginAction.java
The job of the LoginAction class is to validate the users credentials and return result that would be used by struts.xml in result type, based on result users will be redirected to view pages.
package com.Blog.Actions;

import java.sql.*;
import java.util.Map;
import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;

public class LoginAction implements SessionAware{
private String username,password,result="invalid_username";
private static int online_user_count=1;
private Connection conn=null;
private DbConnection dbobj=new DbConnection();
private SessionMap<String ,Object> sessionmap;
public void setSession(Map<String, Object> map) {
     sessionmap=(SessionMap<String, Object>) map;
}
//HttpServletRequest request=ServletActionContext.getRequest();
//HttpSession session=request.getSession();
//HttpServletRequest session=(HttpServletRequest) ServletActionContext.getRequest().getSession();

public String getUsername() {
     return username;
}

public void setUsername(String username) {
     this.username = username;
}

public String getPassword() {
     return password;
}

public void setPassword(String password) {
     this.password = password;
}

public String blogexecute() {
     conn=dbobj.getConnect();
     System.out.println("In execute of loginAction"+conn);
     String query="select password from login where username=?";
     try {
           PreparedStatement pst = conn.prepareStatement(query);
           pst.setString(1,getUsername());
           ResultSet rs=pst.executeQuery();
           if(rs.next()) {
                if(rs.getString(1).equalsIgnoreCase(getPassword()))
                {  
                     sessionmap.put("username",getUsername());
                    sessionmap.put("onlineusers_cout",online_user_count++);
                    result="success";
                }
                else {
                     result="invalid_password";
                }
           }
           else {
                result="invalid_username";
           }
     } catch (SQLException e) {
           System.out.println("Connection failure "+e.getMessage());
     } 
    
     return result;
}//end of blogexecute() method
}//end of class

6)creating blogloginsuccess.jsp
If users entered valid username and password then they will be redirected to this page, just welcoming the users and showing count.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ taglib uri="/struts-tags" prefix="s" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<center>
<h3>Login Successful
Welcome :<s:property value="username"/><br/>
You are user number :<%=session.getAttribute("onlineusers_cout")%>
</h3>
</center>
</body>
</html>

7)Create invalid_username.jsp
If users entered invalid username then they will be redirected to this page including bloglogin.jsp .
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<jsp:include page="bloglogin.jsp"></jsp:include>
<center><font color="red">Invalid username...</font></center>
</html>

8)Creating invalid_password.jsp
If users entered invalid password then they will be redirected to this page including bloglogin.jsp .
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ taglib uri="/struts-tags" prefix="s" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<jsp:include page="login.jsp"></jsp:include>
<center><font color="red">Invalid Password...</font></center>
</html>
Output ScreenShots>>

No comments

You May Like Also

Programming Knowledge


Java JDK
Reversing String in Java
Java Generic Concept With Simple Example
Java Generic Objects Behavior In Non-Generic Area
Creating Connection With MySql Databse Using Java Application
Performing Database Operations Java MySql Insert Update Delete Select
Java Inserting Data in MySql Databse Table
Java Basic Login System Using MySql Database Table
JSP Login System Using MySql Databse
Jsp Servlet Login And Logout System Using Mysql Database Table
What is jdk in Java?
Exaplain inheritance in Java with example?
Exaplain polymorphism in Java with example?
Exaplain abstraction in Java with example?
Exaplain encapsulation in Java with example?
What is the use of this keyword in Java?
Explain ArrayList With Example
Explain LinkedList With Example
Explain Vector Class With Example
Explain Vector Class With Example
Generics in java with example
Behavior of generic objects
How can i pass generic class to a method in java
How to create a login system in jsp using mysql database?
How to create a login and logout system in jsp & servlet using mysql database?
How to connection a simple Java application with mysql database?
How to insert values in mysql databse usiong Java applications?
Perform insertion, retrieval, updatation and delete operations?
How to create a simple login system in java using mysql database?

PHP Login System Using MySql Database
PHP Complete Login System With Session And Logout Using MySql Database