Struts 2 - Accesso al database

Questo capitolo ti insegnerà come accedere a un database utilizzando Struts 2 in semplici passaggi. Struts è un framework MVC e non un framework di database, ma fornisce un eccellente supporto per l'integrazione JPA / Hibernate. Guarderemo l'integrazione di ibernazione in un capitolo successivo, ma in questo capitolo useremo il vecchio JDBC per accedere al database.

Il primo passo in questo capitolo è configurare e caricare il nostro database. Sto usando MySQL come database per questo esempio. Ho MySQL installato sulla mia macchina e ho creato un nuovo database chiamato "struts_tutorial". Ho creato una tabella chiamatalogine l'ha popolato con alcuni valori. Di seguito è riportato lo script che ho utilizzato per creare e popolare la tabella.

Il mio database MYSQL ha il nome utente predefinito "root" e la password "root123"

CREATE TABLE `struts_tutorial`.`login` (
   `user` VARCHAR( 10 ) NOT NULL ,
   `password` VARCHAR( 10 ) NOT NULL ,
   `name` VARCHAR( 20 ) NOT NULL ,
   PRIMARY KEY ( `user` )
) ENGINE = InnoDB;

INSERT INTO `struts_tutorial`.`login` (`user`, `password`, `name`)
VALUES ('scott', 'navy', 'Scott Burgemott');

Il prossimo passo è scaricare il file jar di MySQL Connector e posizionare questo file nella cartella WEB-INF \ lib del progetto. Dopo averlo fatto, siamo ora pronti per creare la classe di azione.

Crea azione

La classe di azione ha le proprietà corrispondenti alle colonne nella tabella del database. abbiamouser, password e namecome attributi String. Nel metodo di azione, utilizziamo i parametri utente e password per verificare se l'utente esiste, in tal caso, visualizziamo il nome utente nella schermata successiva.

Se l'utente ha inserito informazioni errate, lo inviamo nuovamente alla schermata di accesso.

Di seguito è riportato il contenuto di LoginAction.java file -

package com.tutorialspoint.struts2;

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

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {

   private String user;
   private String password;
   private String name;

   public String execute() {
      String ret = ERROR;
      Connection conn = null;

      try {
         String URL = "jdbc:mysql://localhost/struts_tutorial";
         Class.forName("com.mysql.jdbc.Driver");
         conn = DriverManager.getConnection(URL, "root", "root123");
         String sql = "SELECT name FROM login WHERE";
         sql+=" user = ? AND password = ?";
         PreparedStatement ps = conn.prepareStatement(sql);
         ps.setString(1, user);
         ps.setString(2, password);
         ResultSet rs = ps.executeQuery();

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

   public String getUser() {
      return user;
   }

   public void setUser(String user) {
      this.user = user;
   }

   public String getPassword() {
      return password;
   }

   public void setPassword(String password) {
      this.password = password;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }
}

Crea pagina principale

Ora creiamo un file JSP index.jspper raccogliere il nome utente e la password. Questo nome utente e password verranno verificati nel database.

<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1"
   pageEncoding = "ISO-8859-1"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
   <head>
      <title>Login</title>
   </head>
   
   <body>
      <form action = "loginaction" method = "post">
         User:<br/><input type = "text" name = "user"/><br/>
         Password:<br/><input type = "password" name = "password"/><br/>
         <input type = "submit" value = "Login"/>		
      </form>
   </body>
</html>

Crea viste

Ora creiamo success.jsp file che verrà richiamato nel caso in cui l'azione restituisca SUCCESS, ma avremo un altro file di visualizzazione nel caso in cui venga restituito un ERRORE dall'azione.

<%@ page contentType = "text/html; charset = UTF-8" %>
<%@ taglib prefix = "s" uri = "/struts-tags" %>

<html>
   <head>
      <title>Successful Login</title>
   </head>
   
   <body>
      Hello World, <s:property value = "name"/>
   </body>
</html>

Di seguito sarà il file di visualizzazione error.jsp in caso di ERRORE viene restituito dall'azione.

<%@ page contentType = "text/html; charset = UTF-8" %>
<%@ taglib prefix = "s" uri = "/struts-tags" %>

<html>
   <head>
      <title>Invalid User Name or Password</title>
   </head>
   
   <body>
      Wrong user name or password provided.
   </body>
</html>

File di configurazione

Infine, mettiamo insieme tutto usando il file di configurazione struts.xml come segue:

<?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>
   <constant name = "struts.devMode" value = "true" />
   <package name = "helloworld" extends = "struts-default">
   
      <action name = "loginaction" 
         class = "com.tutorialspoint.struts2.LoginAction"
         method = "execute">
         <result name = "success">/success.jsp</result>
         <result name = "error">/error.jsp</result>
      </action>
   
   </package>
</struts>

Di seguito è riportato il contenuto di web.xml file -

<?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_3_0.xsd"
   id = "WebApp_ID" version = "3.0">
   
   <display-name>Struts 2</display-name>
   
   <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>
   
   <filter>
      <filter-name>struts2</filter-name>
      <filter-class>
         org.apache.struts2.dispatcher.FilterDispatcher
      </filter-class>
   </filter>

   <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
   </filter-mapping>
</web-app>

Ora, fai clic con il pulsante destro del mouse sul nome del progetto e fai clic Export > WAR Fileper creare un file War. Quindi distribuire questo WAR nella directory webapps di Tomcat. Infine, avvia il server Tomcat e prova ad accedere all'URLhttp://localhost:8080/HelloWorldStruts2/index.jsp. Questo produrrà la seguente schermata:

Immettere un nome utente e una password errati. Dovresti vedere la pagina successiva.

Adesso entra scott come nome utente e navycome password. Dovresti vedere la pagina successiva.