Creazione di una semplice web application utilizzando maven, jpa2, spring, struts2, mysql (parte 4)

Definito il nostro modello User, vogliamo creare alcuni servizi su di esso. In particolare vogliamo dare la possibilità al sistema di creare nuovi utenti, eliminarli, aggiornarli e prelevarli tutti in una lista.

Per fare questo creeremo un’interfaccia UserService.java.

package it.sample.webapp.service;

import java.util.List;

import org.springframework.transaction.annotation.Transactional;

import it.sample.webapp.model.User;

public interface UserService {
  /**
   * Creates a new user
   * @param user new user to be created
   * @return updated user object that should be used for further updates
   * @throws javax.persistence.PersistenceException when the user can not be 
   *       persisted. This is a <code>RuntimeException</code>
   */
  public User createUser(User user);
  
  /**
   * Deletes the specified user
   * @param user user object to be deleted
   * @throws javax.persistence.PersistenceException when the user can not be 
   *       deleted. This is a <code>RuntimeException</code>
   */
  public void deleteUser(User user);
  
  /**
   * Updates the specified user
   * @param user user object to be updated
   * @return updated user object that should be used for further updates
   * @throws javax.persistence.PersistenceException when the user can not be 
   *       persisted. This is a <code>RuntimeException</code>
   */
  public User updateUser(User user);
  
  /**
   * Gets the user using specified user id
   * @param id unique id assigned to the user
   * @return <code>User</code> object; <code>null</code> if the user does not 
   *       exist in the database
   */
  public User getUser(Long id);
  
  /**
   * Gets all the users
   * @return list of all the users
   */
  public List<User> getAllUsers();
  
  /**
   * Gets the user using specified user name
   * @param name user's name
   * @return <code>User</code> object corresponding to the specified name; 
   *     <code>null</code> if the user does not exist in the database
   */
  public User getUserByUserName(String username);
}

									

L’interfaccia sarà poi implementata dalla classe UserServiceImpl.java

package it.sample.webapp.service.impl;

import java.util.List;

import javax.persistence.NoResultException;

import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Transactional;

import it.sample.webapp.dao.jpa.UserDao;
import it.sample.webapp.model.User;
import it.sample.webapp.service.UserService;

@Transactional
public class UserServiceImpl implements UserService{
  Logger  logger = Logger.getLogger(this.getClass());
  private UserDao userDao;
  
  @Override
  public User createUser(User user) {
    return userDao.save(user);
  }

  @Override
  public void deleteUser(User user) {
    userDao.delete(user.getId());
  }

  @Override
  public List<User> getAllUsers() {
    return userDao.getAll();
  }

  @Override
  public User getUser(Long id) {
    User user = null;
    try {
      user = userDao.getById(id);
    }
    catch (NoResultException nsre) {
      if (logger.isDebugEnabled()) {
        logger.debug("No user found for the specified ID : [" + id + "]");
      }
      user = null;
    }
    return user;
  }

  @Override
  public User updateUser(User user) {
    return userDao.save(user);
  }

  @Override
  public User getUserByUserName(String username) {
    User user = null;
    try {
      user = userDao.getByUserName(username);
    }
    catch (NoResultException nsre) {
      if (logger.isDebugEnabled()) {
        logger.debug("No user found for the specified Name : [" + username + "]");
      }
      user = null;
    }
    return user;
  }
  
  /**
   * Sets the DAO used by this service for persisting <code>User</code> object
   * @param userDao the user DAO to be used for persistence
   */
  public void setUserDao(UserDao userDao) {
    this.userDao = userDao;
  }

  /**
   * Gets the <code>User</code> DAO used for persistence
   * @return the user DAO used for persistence
   */
  public UserDao getUserDao() {
    return userDao;
  }
}

									

Adesso creiamo una classe SampleAction richiamata da struts in modo da scrivere un minimo di logica di business.

Continua a leggere Creazione di una semplice web application utilizzando maven, jpa2, spring, struts2, mysql (parte 4)

Creazione di una semplice web application utilizzando maven, jpa2, spring, struts2, mysql

medium economic 1 day

In questo tutorial verrà spiegato come sviluppare una semplice web application utilizzando tecnologie come maven, jpa2, struts2, spring e mysql.

Ambiente di lavoro:

  • MySQL Server
  • Eclipse + da “Eclipse Market Place”  “Maven Integration for Eclipse”
  • JDK 1.7

Creazione tabella mysql:

Prima di iniziare tutto il lavoro creiamo una tabella che chiameremo user

CREATE  TABLE IF NOT EXISTS `user` (
  `id` BIGINT NOT NULL AUTO_INCREMENT,
  `username` VARCHAR(255) NOT NULL ,
  `password` VARCHAR(255) ,
  PRIMARY KEY (`id`) )
ENGINE = InnoDB;
									

 

Creazione di un nuovo progetto Maven su Eclipse:

– creiamo un nuovo progetto “maven” su eclipse

– impostiamo  maven-archetypes-webapp

– impostiamo grupId e artifactId come in figura



Struttura progetto e configurazione pom.xml

Una volta generato il progetto maven, Eclipse ci propone tutto il progetto come in figura

 Il prossimo passo sarà quello di configurare il file pom.xml in modo da personalizzare il building e includere le tecnologie che ci interessano.

In particolare includiamo le dipendenze per: struts2, spring, mysql connector, servlet e jsp, hibernate, log4j e junit.

Dopo di che impostiamo anche il <build> in modo da utilizzare alcuni plugin tra cui il web server jetty.

POM.XML

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>it.sample</groupId>
  <artifactId>webapp</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>webapp Maven Webapp</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <struts2.version>2.1.8</struts2.version>
    <hibernate.em.version>3.4.0.GA</hibernate.em.version>
    <spring.version>2.5.6</spring.version>
        <spring.jpa.version>2.0.8</spring.jpa.version>
        <mysql.connector.version>5.1.13</mysql.connector.version>
    <junit.version>4.4</junit.version>
        <log4j.version>1.2.16</log4j.version>
  </properties>


  <dependencies>
        <!--  Struts 2 -->
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
            <version>${struts2.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-spring-plugin</artifactId>
            <version>${struts2.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-junit-plugin</artifactId>
            <version>${struts2.version}</version>
        </dependency>

        <!-- Spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${spring.version}</version>
    </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jpa</artifactId>
            <version>${spring.jpa.version}</version>
        </dependency>
        
        <!-- MySQL JDBC Connector -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysql.connector.version}</version>
    </dependency>
        
        <!-- Servlet & Jsp -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.4</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>
        
        <!-- Hibernate dependencies -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.em.version}</version>
        </dependency>
 
        <!-- Other dependencies -->

        <!-- slf4j required for hibernate-annotations 3.4.0 -->    
      <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
          <version>1.5.6</version>
      </dependency>
      <!-- concrete Log4J Implementation for SLF4J API-->
      <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j12</artifactId>
          <version>1.5.6</version>
      </dependency>
        
      <dependency>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
          <version>${log4j.version}</version>
          <scope>runtime</scope>
     </dependency>
  
      <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>${junit.version}</version>
          <scope>test</scope>
      </dependency>
  </dependencies>
  

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.0.2</version>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.1-beta-1</version>
        <configuration>
          <failOnMissingWebXml>false</failOnMissingWebXml>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>maven-jetty-plugin</artifactId>
        <version>6.0.0</version>
        <configuration>
          <contextPath>/</contextPath>
          <scanIntervalSeconds>3</scanIntervalSeconds>
          <scanTargets>
            <scanTarget>
              src/main/webapp/WEB-INF/web.xml
                  </scanTarget>
          </scanTargets>
        </configuration>
      </plugin>
        </plugins>
    <finalName>webapp</finalName>
  </build>

</project>