Struts 2 simple Login example


Lets try this example to load success or error page based on username and password


Code

<%@ taglib prefix="s" uri="/struts-tags"%> 
<html>
<body> 
	<h4>
		<u>Struts2 Login Example</u>
	</h4>
	
	<s:form action="login" >
		<s:textfield name="uname"  label="Enter Username"/>
		<br>
		<s:password name="pass" label="Enter Password" />
		<br>
		<s:submit value="Login" align="center" />
	</s:form>  
	<br>

	
</body>
</html>
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>Struts2Example8</display-name>
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>
			org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
		</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>
struts.xml
<?xml version="1.0" encoding="UTF-8"?>

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

<struts>
   
    <package name="com" extends="struts-default">
             
        <action name="login" class="com.candidjava.controller.LoginController">       
        	<result name="success">/success.jsp</result>
            <result name="error">/error.jsp</result>      
        </action>
              
    </package>
</struts>

LoginController.java

package com.candidjava.controller;
import com.opensymphony.xwork2.ActionSupport;
public class LoginController extends ActionSupport{	
	
	private static final long serialVersionUID = 1L;
	
	private String uname;
	private String pass;
	private String msg;
	
	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public String getUname() { 
		return uname;  
	}

	public void setUname(String uname) {
		this.uname = uname;
	}
	  
	public String getPass() {
		return pass;
	}

	public void setPass(String pass) {
		this.pass = pass;
	}

	public String execute()
	{		
		if(uname.equals("candidjava") && pass.equals("1234"))
		{
			setMsg("welcome Candidjava");
			return "success";
			
		}else 
			return "error";
	}
	
	
}
Success.jsp
<%@ taglib prefix="a" uri="/struts-tags" %>




Welcome <b><a:property value="msg"/>,</b><br/>

You have been successfully Logged in.... 
error.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>

Login failed....

Screenshot

        

        

Download

        Struts 2 login example war

        Struts 2 login example maven zip





Related Post

Comments


©candidjava.com