Struts Login Form Example Eclipse MySql Apache Tomcat

Struts Login Example

Struts 1.3 Java Eclipse MySql Apache Tomcat

Project Screenshot:



Project Explorer:



Source code:

struts-config.xml 
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
          "http://struts.apache.org/dtds/struts-config_1_3.dtd">

<struts-config>

    <!-- Form Beans -->
    <form-beans>
        
        <form-bean name="loginForm" type="com.loginexample.forms.LoginForm"/>

    </form-beans>

    <!-- Action Mappings -->
    <action-mappings>

     <action name="loginForm" path="/Login" type="com.loginexample.actions.LoginAction" scope="request" input="/Login.jsp">
         <forward name="failure" path="/Failure.jsp" redirect="true"/>
         <forward name="success" path="/Success.jsp" redirect="true"/>
     </action>

    </action-mappings>
    
    <!-- Message Source -->
     <message-resources parameter="com.loginexample.resources.Application"/>

</struts-config>

web.xml
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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">
  <display-name>StrutsLoginFormExample</display-name>
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
      <param-name>config</param-name>
      <param-value>
          /WEB-INF/struts-config.xml
       </param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
Login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib prefix="html" uri="http://struts.apache.org/tags-html"%>
<%@taglib prefix="logic" uri="http://struts.apache.org/tags-logic"%>
<%@taglib prefix="bean" uri="http://struts.apache.org/tags-bean"%>
<!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><bean:message key="loginform.label.title"/></title>
</head>
<body>
<center>
<h1><bean:message key="loginform.label.title"/></h1>
<html:form action="/Login" focus="username">
<table>
<tr><td>
 <bean:message key="loginform.label.usernane"/>
 </td>
 <td>
   <html:text property="username"/>
  </td>
  <td>
  <logic:messagesPresent property="username">
   <html:messages id="error" property="username">
    <font color="red"><bean:write name="error"/></font>
   </html:messages>
  </logic:messagesPresent>
 </td></tr>
<tr><td>
  <bean:message key="loginform.label.password"/>
 </td>
 <td>
  <html:password property="paswd"/>
 </td>
 <td> 
 <logic:messagesPresent property="paswd">
  <html:messages id="error" property="paswd">
   <font color="red"><bean:write name="error"/></font>
  </html:messages>
 </logic:messagesPresent>
 </td></tr>
<tr><td></td>
  <td align="left">
 <html:submit value="Login"/>
 <html:reset value="Cancel"/>
 </td>
  <td>
 </td></tr>
</table>
</html:form>
</center>
</body>
</html>

Success.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>Login Successful</title>
</head>
<body>
 <h1>Login Successful</h1>
</body>
</html>

Failure.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>Login Failure</title>
</head>
<body>
 <h1 style="color: red;">Login Failure</h1>
</body>
</html>

LoginForm.java
package com.loginexample.forms;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

public class LoginForm extends ActionForm {


 /**
  * nn
  */
 private static final long serialVersionUID = 1L;
 private String username = null;
 private String paswd = null;
 
 public String getUsername() {
  return username;
 }
 
 public void setUsername(String username) {
  this.username = username;
 }
 
 public String getpaswd() {
  return paswd;
 }
 
 public void setpaswd(String paswd) {
  this.paswd = paswd;
 }
 
 @Override
 public void reset(ActionMapping mapping, HttpServletRequest request) {
  this.paswd = null;
 }
 public ActionErrors validate(ActionMapping mapping,
   HttpServletRequest request) {
  ActionErrors errors = new ActionErrors();
  if(username==null || username.length()==0 || username.trim().equals(""))
  {
   ActionMessage message = new ActionMessage("loginform.username.empty");
   errors.add("username", message);
  }
  else if(!username.matches("^[a-zA-Z0-9 ]+$"))
  {
   errors.add("username", new ActionMessage("loginform.username.alphabets"));
  }
  else if(username.length()<3)
  {
   errors.add("username", new ActionMessage("loginform.username.length"));
   
  }
  if(paswd==null||paswd.length()==0||paswd.trim().equals(""))
  {
   errors.add("paswd", new ActionMessage("loginform.paswd"));
  }
  
 
 return errors;
 }
 

}


LoginAction,java
package com.loginexample.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.loginexample.forms.LoginForm;
import com.loginexample.services.LoginService;

public class LoginAction extends Action {
 @Override
 public ActionForward execute(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response)
   throws Exception {
  LoginForm loginForm = (LoginForm)form;
  LoginService loginService= new LoginService();
  
  try
  {
   loginService.checkLogin(loginForm);
   return mapping.findForward("success");
  }
  catch (Exception e)
  {
   return mapping.findForward("failure");
  }
 
 }

}


LoginService.java
package com.loginexample.services;

import java.sql.SQLException;

import com.loginexample.dao.impl.LoginDaoImplementation;
import com.loginexample.exceptions.InvalidUserException;
import com.loginexample.forms.LoginForm;

public class LoginService {
 public boolean checkLogin(LoginForm loginForm) throws SQLException, InvalidUserException
 {
  LoginDaoImplementation loginDao= new LoginDaoImplementation();
  if(!loginDao.checkLogin(loginForm))
    throw new InvalidUserException("Incorrect Username/Password.");
  else
   return true;
 }

}


LoginDao.java
package com.loginexample.dao;

import java.sql.SQLException;

import com.loginexample.forms.LoginForm;

public interface LoginDao 
{
public boolean checkLogin(LoginForm loginForm) throws SQLException;
}


LoginDaoImplementation.java
package com.loginexample.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.loginexample.dao.LoginDao;
import com.loginexample.forms.LoginForm;
import com.loginexample.utilities.DBUtilities;

public class LoginDaoImplementation implements LoginDao
{
 public boolean checkLogin(LoginForm loginForm) throws SQLException
 {
  Connection con=null;
  boolean access=false;
  
  try
  {
   con=DBUtilities.getConnection();
   
   String query= "select * from login where username=? and password=?";
   PreparedStatement stmt= con.prepareStatement(query);
   stmt.setString(1, loginForm.getUsername());
   stmt.setString(2, loginForm.getpaswd());
   ResultSet rs= stmt.executeQuery();
   
   if(rs.next())
   {
    access=true;
   }
  
   
  }
  finally
  {
   DBUtilities.closeConnection(con);
  }
  return access;
 }
}



DBUtilities.java
package com.loginexample.utilities;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DBUtilities {
 
    public static Connection getConnection()
    {
     Connection con = null;
     
     try 
     {
    Class.forName("com.mysql.jdbc.Driver");
    con  =DriverManager.getConnection("jdbc:mysql://localhost:3306/nn","root","");
     } 
     catch (ClassNotFoundException e) 
     {
   // TODO Auto-generated catch block
      e.printStackTrace();
     } 
     catch (SQLException e) 
     {
   // TODO Auto-generated catch block
      e.printStackTrace();
     }
     
     return con; 
     
    }
 
     public static void closeConnection(Connection con){      
      if(con!=null){
       try{
       con.close();
       }catch(SQLException e){}
      }      
     }   
       public static void closePreparedStatement(PreparedStatement ps){      
      if(ps!=null){
       try{
       ps.close();
       }catch(SQLException e){}
      }
      
     }

}



InvalidUserException.java
package com.loginexample.exceptions;

public class InvalidUserException extends Exception
{

 /**
  * 
  */
 private static final long serialVersionUID = 1L;

 public InvalidUserException(String arg0) 
 {
  super(arg0);
 }
 

 
}


Application.properties
loginform.label.title=Login Form
loginform.label.usernane=Username : 
loginform.label.password=Password : 
loginform.username.empty=Please enter username
loginform.username.alphabets=Please enter alphabets only
loginform.username.length=Please enter username of length of at least 3 characters
loginform.paswd=Please enter password



Download:
StrutsLoginFormExample

25 comments:

  1. Your Blog post has exceptionally supportive data.

    Much obliged concerning share.... .

    Continue offering
    Correspondence Courses

    ReplyDelete
  2. Thank you for that information you article
    i like play games make up games 2 girls online free and play game friv games and games 2 girls ! have fun!

    ReplyDelete
  3. Thanks for sharing. I hope it will be helpful for too many people that are searching for this topic.
    Signature:
    Jugar juegos de frozen en línea gratis, los nuevos de princesa de Disney juegos frozen - la princesa encantadora y linda. Divertirse frozen!

    ReplyDelete
  4. The article you have shared here very awesome. I really like and appreciated your work. I read deeply your article, the points you have mentioned in this article are useful
    Signature:
    download descargar facebook gratis para Android celular and download free descargar facebook apk en español, descargar facebook plus , descarga facebook

    ReplyDelete
  5. I understand what you bring it very meaningful and useful, thanks.
    Signature:
    facebook entrar iniciar sesion gratis - Sitio Oficial iniciado sesión en Facebook lengua española. facebook entrar rápido, facebook iniciar sesion en tu cuenta de entrar facebook

    ReplyDelete

  6. Your design of the blog is really eye-catching. More over the content is also very productive. Information you have provided is really very beneficial.

    PHP Services in Gravesend
    Website Design Company in Gravesend
    Web Design Services in Gravesend

    ReplyDelete
  7. I would like to thank you for your nicely written post
    Signature:
    Versión en facebook en español descargar a los países hablan Español: facebook entrar direto agora , facebook en español para and facebook entrar direto

    ReplyDelete
  8. I would like more information about this, because it is very nice., Thanks for sharing.
    Signature:
    download baixar facebook movel, Facebook movel, baixar facebook movel. Facebook chat, baixar whatsapp gratis, fazer o download baixar whatsapp para Android, iPhone. Últimas Facebook

    ReplyDelete
  9. Thank you for your post, I look for such article along time, today i find it finally. this post give me lots of advise it is very useful for me
    Signature:
    The place to play all unblocked games 77 online. Here you can find every blocked games such as: unblockedgames , unblocked games happy , unblocked games 77 , gmod

    ReplyDelete
  10. Very helpful advice in this particular post! It’s the little changes that make the largest changes. Thanks for sharing!
    kids games online , friv 2 , jogos do friv , juegosjuegos.com , juegos de matar zombbies
    , juegos de un show mas

    ReplyDelete
  11. You have a real ability for writing unique content. I like how you think and the way you represent your views in this article. I agree with your way of thinking. Thank you for sharing.
    happy wheels ,
    super mario bros
    pacman
    agario

    ReplyDelete
  12. I hope today can better yet, share permissions
    agario game is a multiplayer browser game in which players have to eat competitors or be eaten while striving to dominate the world of colorful cells. In agario, you start off with a small circle and eat smaller static circles and other smaller players. Once you get big enough you will get addicted. With agar.io, you have an option to split your circle in two and throw one half at the other players with larger speed, in order to gain more mass. You have the option to play agar io in a Free For All mode, where you play against everyone, or you can play in teams. Play agar io skins online game for free with your friends now!

    ReplyDelete
  13. The blog or and best that is extremely useful to keep I can share the ideas. Age Of War 2
    Big Farm | Slitherio | Tank Trouble
    Of the future as this is really what I was looking for, I am very comfortable and pleased to come here. Thank you very much.
    Happy Wheels | Goodgeme Empire | Slither.io

    ReplyDelete
  14. Life becomes more interesting and wonderful when you share your memorable moments with friends and family through unique photographs. You can create your own unique style impressed with image editing software. And after hours of work stress you can also

    tank trouble, tank trouble 2, tank trouble games, tank trouble

    ReplyDelete
  15. Life becomes more interesting and wonderful when you share your memorable moments with friends and family through unique photographs. You can create your own unique style impressed with image editing software. And after hours of work stress you can also
    dr driving, dr driving baixar ,download dr driving, dr driving

    ReplyDelete
  16. You need to have time to take care of the active. It in fact was a amusement account it. Look advanced to far added agreeable from you.
    banana kong ,
    banana kong baixar ,
    baixar banana kong ,
    download banana kong ,
    banana kong

    ReplyDelete
  17. You need to have time to take care of the active. It in fact was a amusement account it. Look advanced to far added agreeable from you.

    entrar hotmail agora , hotmail entrar, entrar hotmail , entrar no hotmail

    ReplyDelete
  18. Thanks I have read your article, it is very interesting and exciting
    download go launcher, go launcher apk, go launcher , go launcher androi,

    ReplyDelete
  19. Mostly people have all the same things when they are writing academic task or any other writing, especially light music most people like during the writing.

    subway surf , baixar subway surf, subway surf download , download subway surf

    ReplyDelete
  20. Mostly people have all the same things when they are writing academic task or any other writing, especially light music most people like during the writing.
    dream league soccer download , dream league soccer apk , download dream league soccer , dream league soccer

    ReplyDelete
  21. You’ve written nice post, I am gonna bookmark this page, thanks for info. I actually appreciate your own position and I will be sure to come back here.
    Facebook Lite

    ReplyDelete
  22. Thanks for your post! Through your pen I found the problem up interesting! I believe there are many other people who are interested in them just like me! Thank you for sharing them with everyone!
    abcya

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...