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.
-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.
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
- .bloglogin.jsp to take input from the users.
- Struts.xml in src to define action and result.
- Deployment descriptor i.e., web.xml .
- DbConnection class to create the connection with MySql database.
- LoginActin.java to authenticate the users credentials.
- blogloginsuccess.jsp
- invalid_username.jsp for invalid userame.
- invalid_password.jsp for invalid_password.
1)Create bloglogin.jsp
This bloglogin.jsp file is responsible to take input from the users.
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>
No comments