Struts 2 Database Access

In this chapter we will teach you how to access a database using Struts 2 in simple steps. Struts is a MVC framework and not a database framework but it provides excellent support for JPA/Hibernate integration. We shall look at the hibernate integration in a later chapter, but in this chapter we shall use plain old JDBC to access the database.

The first step in this chapter is to setup and prime our database. I am using MySQL as my database for this example. I have MySQL installed on my machine and I have created a new database called "DOJDB". I have created a table called "USER"and populated it with some values. Below is the script I used to create and populate the table.

  UserName VARCHAR(10) NOT NULL,


Create Action:
The action class has the properties corresponding to the columns in the database table. We have user, password and name as String attributes. In the action method, we use the user and password parameters to check if the user exists, if so , we display the user name in the next screen. If the user has entered wrong information, we send them to the login screen again.
Following is the content of file:
package com.dineshonjava.struts2.login;

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

import com.opensymphony.xwork2.ActionSupport;

 * @author Dinesh Rajput
public class LoginAction  extends ActionSupport{
 private String username;
    private String password;
    private String userid;
 public String execute() {
  String ret = ERROR;
       Connection conn = null;

       try {
          String URL = "jdbc:mysql://localhost:3306/DOJDB";
          conn = DriverManager.getConnection(URL, "root", "root");
          String sql = "SELECT name FROM user WHERE";
          sql+=" userName = ? AND password = ?";
          PreparedStatement ps = conn.prepareStatement(sql);
          ps.setString(1, username);
          ps.setString(2, password);
          ResultSet rs = ps.executeQuery();

          while ( {
           username = rs.getString(1);
           ret = SUCCESS;
       } catch (Exception e) {
          ret = ERROR;
       } finally {
          if (conn != null) {
             try {
             } catch (Exception e) {
       return ret;

 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 getUserid() {
  return userid;

 public void setUserid(String userid) {
  this.userid = userid;

Create main page:
Now, let us create a JSP file Login.jsp to collect the username and password. This username and password will be checked against the database.
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Struts 2 - Login Application |</title>
<h2>Struts 2 - Login Application</h2>
<font color="red"><s:actionerror /></font>
<s:form action="login/welcome.action" method="post">
    <s:textfield name="username" key="label.username" size="20" />
    <s:password name="password" key="label.password" size="20" />
    <s:submit method="execute" key="label.login" align="center" />
Create Views:
Now let us create success.jsp file which will be invoked in case action returns SUCCESS, but we will have another view file in case of an ERROR is returned from the action.
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <h2>Hello Welcome , <s:property value="username" />...!</h2>
Configuration Files:
Finally, let us put everything together using the struts.xml configuration file as follows:
<?xml version="1.0" encoding="UTF-8" ?>
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="false" />
    <constant name="struts.custom.i18n.resources" value="myapp" />
      <package name="login" extends="struts-default" namespace="/login">
        <action name="welcome" class="com.dineshonjava.struts2.login.LoginAction">
            <result name="success">/Welcome.jsp</result>
            <result name="error">/Login.jsp</result>
label.username= Username
label.password= Password
label.login= Login
error.login= Invalid Username/Password. Please try again.

Following is the content of web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="" xmlns="" xmlns:web="" xsi:schemaLocation="" id="WebApp_ID" version="3.0">
Now, right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access

URL http://localhost:8080/doj/Login.jsp.

This will give you following screen:

Enter a wrong user name and password. You should see the next page-

Now enter "Dinesh" as user name and "Sweety" as password. You should see the next page-

Download Source Code+Libs

<<Previous <<   || Index ||   >>Next >>

No comments:

Post a Comment