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.

Nel nostro caso vorremo aggiungere un utente e, dopo di che, visualizzare l’elenco di tutti gli utenti a video.

SampleAction.java

package it.sample.webapp.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
import it.sample.webapp.model.User;
import it.sample.webapp.service.UserService;

/**
 * 
 */
public class SampleAction extends ActionSupport implements ModelDriven<Object>, 
  Preparable, ServletRequestAware {
  private static final long serialVersionUID = -3670063011948002290L;

  private User user;
  private List<User> users;
  
  private HttpServletRequest request;
  private UserService userService;

  //During prepare call, this field is set to true for the existing user.
  //Execute method uses this to call appropriate service method.
  //Remember, in struts2 new Action is instantiated for every request.
  private boolean isExistingUser = false;
  
  public Object getModel() {
    return user;
  }

  public void prepare() throws Exception {
    //If the user name was specified, check if it already exists in the database
    String username = request.getParameter("name");
    
    if ((username == null) || (username.trim().equals(""))) {
      user = new User();
      isExistingUser = false;
    } else {
      user = userService.getUserByUserName(username);
      if (user == null) {
        isExistingUser = false;
        user = new User();
      } else {
        isExistingUser = true;
      }
    }
    
  }

  @Override
  public String execute () {
    //Let's override this method to add our application logic.
    //Create new user or modify existing user using specified user details
    //see http://rajandesai.com/blog/2010/07/14/jpa-entitymanager-persist-vs-merge/
    //if you are wondering why we use the User object returned by the update
    //or create method of the service.
    if (isExistingUser) {
      user = userService.updateUser(user);
    } else {
      //If username is null, get the list of users from the db.
      if (user.getUsername() != null) {
        user = userService.createUser(user);
      } else {
        users = userService.getAllUsers();
      }
      
    }
    return SUCCESS;
  }
  
  public void setServletRequest(HttpServletRequest httpServletRequest) {
    request = httpServletRequest;
  }

  /**
   * @return the user
   */
  public final User getUser() {
    return user;
  }

  /**
   * @param user the user to set
   */
  public final void setUser(User user) {
    this.user = user;
  }

  /**
   * @param users the users to set
   */
  public void setUsers(List<User> users) {
    this.users = users;
  }

  /**
   * @return the users
   */
  public List<User> getUsers() {
    return users;
  }

  /**
   * @param userService the userService to set
   */
  public void setUserService(UserService userService) {
    this.userService = userService;
  }

  /**
   * @return the userService
   */
  public UserService getUserService() {
    return userService;
  }
}

									

Infine, possiamo costruire la nostra pagina jsp di presentazione.

la chiameremo sample.jsp e la inseriremo all’interno del folder /WEB-INF/sample/sample.jsp

sample.jsp

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

<body>

<h1>Welcome!<s:if test="%{user.username != null}"> <s:property value="user.username" />
<hr/>
<h2>Dettagli</h2>
<h4>Your Name   : <s:property value="user.username" /></h4>
<h4>Your Password    : <s:property value="user.password" /></h4>
<hr/>
</s:if>
<s:else> </h1>
<p>Lista Utenti</p>
<hr/>
<s:if test="users.size > 0">
    <table>
        <s:iterator value="users">
            <tr id="row_<s:property value="id"/>">
                <td width="200">
                    <a href="/sample/sample.action?username=<s:property value='username'/>"><s:property value="username" /></a>
                </td>
                <td width="50">
                    <s:property value="password" />
                </td>
             </tr>
        </s:iterator>
    </table>
</s:if>
</s:else>
<h2>
--Inserisci Utente--</br>
</h2>
<form method="get" action="/sample/sample.action">
Username: <input name="username"><br />
Password: <input name="password" type="password"><br />
<input type="submit"><br />
</form>
<h3><a href="/sample/sample"> Guarda lista</a></h3>
</body>
</html>

									

A questo punto possiamo far partire l’applicazione attraverso il comando mvn jetty:run

Si accede all’applicazione attraverso http://localhost:8080/sample/sample

Buon lavoro,

 

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *