You are on page 1of 6

Struts 2 simple login example

Posted at: 27 September 2011

MVC architecture
MVC is a software architecture which isolate the application logic from the user interface. This is a good programming technique if: We develop a very big project and we need our code to be readable and maintainable. We have a very big project separated in smaller problems and many developers. With MVC architecture will be more obvious how to join the code pieces. We work in a big company that a web programmer and the web designer is a different person. The following image is from wikipedia

Struts Struts 2 is a web framework for developing Java web applications, which encourages the developer to use the MVC architecture. As we said MVC stands for Model, View and Controller. As the developers we have to create the M (Application logic: calculations, comparisons, reading and writing to the database etc.) and the V (User interface: data presentation, forms, buttons etc.). Struts gives us the C. However we have to write a simple xml configuration for the controller to glue everything together. Since we talk Java, we create some Java classes for the Model and some jsp files for the View. The configuration for the controller is written in XML. Our example In our example we will create a simple login form. First of all you have to create the database. Go to PhpMyAdmin and create a new database (I named it returnsuccessexample). Create a table called users with 3 fields. 1)id: integer, primary key, auto increment, 10 length, 2)username: varchar, unique, 255 length and 3)password: varchar, 32 length.

I have inserted 2 users in the table: 1 - howard - 81dc9bdb52d04dc20036dbd8313ed055 (1234 -> md5 hash) 2 - sheldon - d93591bdf7860e1e4ee2fca799911215 (4321 -> md5 hash)

First we will develop the easy part. The View, or the two jsp's . The first jsp will be the one that includes the login form (index.jsp) ?
<!DOCTYPE HTML> <html> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="s" uri="/struts-tags" %> <head> <title>:: Login ::</title> <link rel="stylesheet" type="text/css" href="style/style.css" /> </head> <body> <s:div id="main" > <s:div id="header"> <h1>Company Logo</h1> </s:div> <s:div id="site_content"> <h2>Sign in</h2> <s:form action="CheckLogin" > <s:textfield name="username" label="Username" /> <s:password name="password" label="Password" /> <s:submit /> </s:form> <s:div id="errormessage"><s:property value="errormessage" /></s:div> </s:div> </s:div> </body> </html>

and we will create the other jsp (the one that will appear after correct login). Name it MainApplicationPage.jsp. ?
<%@page contentType="text/html" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html> <html>

<head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>:: Welcome ::</title> </head> <body> <s:if test="#session.loggedin != 'true'"> <jsp:forward page="/index.jsp" /> </s:if> <h1>Successful login! Welcome to the application</h1> </body> </html>

For the model of our application we need a Java class. A Java class that will get the username and password from the form, change the password to MD5 hashtext, and compare them with the database records. Let's name the source file LoginResult.java (therefore the public class will be LoginResult too). If there is no match it will return "ERROR" and if the user gave correct username and password will put true in session variable loggedin and return "SUCCESS": ?
package MyExample; import import import import import com.opensymphony.xwork2.ActionContext; java.util.Map; java.math.BigInteger; java.security.MessageDigest; java.sql.*;

public class LoginResult { private String errormessage; private String username; private String password; public String execute(){ try{ Map session = ActionContext.getContext().getSession(); session /* Create MD5 from string input */ MessageDigest m = MessageDigest.getInstance("MD5"); m.reset(); m.update(getPassword().getBytes()); byte[] digest = m.digest(); BigInteger bigInt = new BigInteger(1,digest); String hashtext = bigInt.toString(16); while(hashtext.length() < 32 ){ hashtext = "0"+hashtext; } /* Create MD5 from string input */ String url = "jdbc:mysql://localhost:3306/returnsuccessexample"; String user = "root"; String pass = ""; Connection conn; Statement st = null;

// Get

ResultSet rs = null; Class.forName ("com.mysql.jdbc.Driver").newInstance(); conn = DriverManager.getConnection(url, user, pass); st = conn.createStatement(); rs = st.executeQuery("SELECT * FROM `users` WHERE username='"+getUsername()+"'"); if (rs.next()) { if ((rs.getString("password").compareTo(hashtext) ) == 0) { session.put("loggedin","true"); } else{ setErrormessage("Error logging in"); conn.close(); return "ERROR"; } } else { setErrormessage("Error logging in"); conn.close(); return "ERROR"; } conn.close(); } catch (Exception e){ System.out.print(e); setErrormessage("Some database error occurred."); return "ERROR"; } return "SUCCESS"; } /* getters and setters */ public String getErrormessage() { return errormessage; } public void setErrormessage(String errormessage) { this.errormessage = errormessage; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }

Now the configuration. We need to tell our application that we use Struts framework via web.xml:

?
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filterclass> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>

The last thing is to configure the controller, so everything will work harmoniously. That will do in struts.xml. We need to point that when the CheckLogin action will execute (see the form at the first jsp file), we will execute the execute method of the public class LoginResult. When user inserts wrong data, the app will return to the login form. When user inserts correct data, the action should transfer us to the main page of our application. ?
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="default" extends="struts-default"> <action name="CheckLogin" class="MyExample.LoginResult"> <result name="SUCCESS">/MainApplicationPage.jsp</result> <result name="ERROR">/index.jsp</result> </action> </package> </struts>

When I started using Struts I had some difficulties understanding, so I hope that you will find this article useful.

You might also like