Showing posts with label j2-ee. Show all posts
Showing posts with label j2-ee. Show all posts

Friday, January 25, 2013

Displaytags Integration With Spring MVC3

When it comes to displaying database records as a list view(table) in jsp, we need to provide sorting and pagination functionalists. Basically what we do is use ajax  with pure java script  or using JQuery and call controllers to get the job done. This becomes complicated when you need to provide sorting functionality  for multiple columns. I recently found a tag-library "displaytags" which can take care of pagination and sorting stuff in Client side.
Following is the view of functionality we want to come up with using displaytags. 

   
First you need to include tag declaration in your jsp.
 
<%@ taglib uri="http://displaytag.sf.net" prefix="display" %>
And the following will take care of generating table for list view.
 
   
    
    
     
    
The name of the display table attribute(which is name==persons) is binded with a list of Persons and it is assigned in MVC controller class.  
final ModelAndView persons = new ModelAndView(VIEW_ALL_PERSONS);
  persons .addObject("persons", getPersonList(request));
                request.setAttribute("personListSize", personService.getRowCount());
  request.setAttribute("pageSize", pageSize);
And the property attribute of display column which is (property="designationName") is binded with the property of the model in MVC pattern. And also you need to set other request parameters which are used to construct the table by display tag library.
public class PersonDetails {
 
 private String designationName;
 
 public String getDesignationName() {
  return designationName;
 }

 public void setDesignationName(String designationName) {
  this.designationName = designationName;
 }
}
Lets say you want to add an attribute which is not in you model class, then display tags allows you to use a decorator and use that attribute in display columns.I have used personLink and editLink property with a decorator and those properties are not included in my model class(PersonDetails). In the display table you can see a property called decorator and its value.(ecorator="se.nextodo.web.util.LinkDecorator"). Properties which are not included in the model class are retrieved from the decorator class. Advantage of using this is you can add a image links or icons in to the table.
import org.displaytag.decorator.TableDecorator;
import com.mycompany.model.PersonDetails;

public class LinkDecorator extends TableDecorator {

 public String getPersonLink() {
  final PersonDetails personDetails = (PersonDetails) getCurrentRowObject();
  final String link = ""+  "";
  return link;
 }

 public String getEditLink() {
  final PersonDetails personDetails = (PersonDetails) getCurrentRowObject();
  final String link = "" +"";
  return link;
 }
}
You can define button icon in you style sheet (in this case edit-btn) and it will render the images as expected.

       Now we are almost done with the creating table in client side and its time to consider how to implement sorting and pagination functionality in server side. From the server side we need to know the field that the client wanted to sort. It is the sortName property in the table column(sortName="firstName). display tag library set request parameter for this, so that we can retrieve it from the server side as follows.
final String attribute = request.getParameter(new ParamEncoder(tableId)   .encodeParameterName(TableTagParameters.PARAMETER_SORT));
In the same way you can retrieve the sorting order (ascending or descending).
 
final String orderKey = request.getParameter(new ParamEncoder(tableId)
    .encodeParameterName(TableTagParameters.PARAMETER_ORDER));
The remaining fact you want to get from the client is the current page position on the jsp.
  final String page = request.getParameter(new ParamEncoder(tableId)
    .encodeParameterName(TableTagParameters.PARAMETER_PAGE));
So its time to implement our dao functionality.
 @SuppressWarnings("unchecked")
 @Override
 public List getPersons(String orderedBy,
   String order, int startPosition, int maxResult) {

  final String queryString = "select p from Person p ORDER BY "
    + orderedBy + " " + order;

  final Query query = entityManager.createQuery(queryString);
  query.setFirstResult(startPosition);
  query.setMaxResults(maxResult);
  return query.getResultList();
 }
Dao call from the controller looks like bellow.
private Collection getPersonList(
   HttpServletRequest request) {

  final String tableId = "personList"; 
  final int pageSize = 10; 

  return personService.getModels( attribute,orderKey,(page - 1) * pageSize),pageSize);
 }
Reference : diplay tag website

Saturday, August 18, 2012

Spring Web Services with Jaxb

In this post I am going to explain how to implement a web service by using spring-ws. For the demonstration purpose I am going to narrow down this sample project as follows.

Functionality of web service : Authenticate a user(I am not going to use any encryption method or a security mechanism since this post is about spring ws :-))

Development/Deployment environment :
  • java 1.6
  • Spring-ws-core with jaxb 
  • Intelij Idea
  • Apache tomcat 
  • SoapUI 4.5.1
 First we need to start with a schema definition which our service is going to support. So for the simplicity I used following definition which is easy to understand.
 



    

    

    
        
            
            
        
    

    
        
            
            
        
    

Above schema definition consist of a simple login request and the corresponding response.Simple it can parse following sample messages.

Request Message
 

   
   
      
         esu
         password
      
   

Response Message
 

   
   
      
         SUCCESS
         esu
      
   

Then you need to create a web project by using your IDE or a build tool like maven. A web service acts like a web app and the the significant difference is that it can identify incoming xml requests and response them with corresponding xml responses as mentioned in above. If you are familiar with Spring mvc you know that we can configure a Dispatcher Servlet in web.xml which can identify HTTP get and post requests from the client browser.In the similar manner you can configure a MessageDispatcherServlet which can identify web server requests.
    
        customer-ws
        org.springframework.ws.transport.http.MessageDispatcherServlet
    
    
        customer-ws
        /*
     
Then you should have customer-ws-servlet.xml where all the spring web service configurations and jaxb marshaling configurations are located. You can find the Servlet here . The important thing to be noticed is the WSDL configuration and schema configuration.
 
    
        
        
        
    

    
        
    
customer service bean creates a wsdl for you according to the schema bean which is configured to the loginschema.xsd. Once you deploy the web service in to the web container you can access the generated wsdl by http://localhost:8080/customerService/customerService.wsdl.

Then its time to implement end point class which the final destination for incoming soap massages. Following is the implementation of the endpoint.
 
@Endpoint
public class CustomerServiceEndPoint {


    @Autowired
    private LoginService loginService;


    @PayloadRoot(localPart = "LoginRequest", namespace = "http://mycompany.com/customer-ws/schemas")
    @ResponsePayload
    public JAXBElement login(@RequestPayload JAXBElement requestElement) throws IOException {
        ObjectFactory objectFactory = new ObjectFactory();
        LoginResponseDetails details = new LoginResponseDetails();

        details.setUsername(requestElement.getValue().getUserName());
        if (loginService.login(requestElement.getValue().getPassword(), requestElement.getValue().getPassword())) {
            details.setStatus("SUCCESS");

            return objectFactory.createLoginResponse(details);
        }
        details.setStatus("FAIL");
        return objectFactory.createLoginResponse(details);

    }
}
You can see the login method is accepting jaxb element called LoginDetails and it passes that details in to service method and authenticate the user and return the response jaxb element. you might be wondering how this happens. It is because we have configure marshalling and unmarshalling in the servlet xml.And also to enable the jaxb class generation I have used jaxb2-maven-plugin in my pom file which you can find the source code on the Google code repository.

Source Code Link : Code
What you have to do is simply check out the source code and then run mvn package command. Then you can see the generated war file. Then deploy it in to apache tomcat. Now you are done.

Following is the screen shot  taken from the soapui to verify that the web service is working or not.


From my next post i hope to show how to write client app to use this web service.

Saturday, May 19, 2012

Spring MVC + Spring Hibernate for basic CRUD operations

Most of java developers are using Spring framework for flexible designs.Specially for web based projects where we apply MVC design pattern. So in this post I am going to explain how to use spring framework to achieve that requirement.

I will explain it with the web.xml file which is easier to understand.

   
        dispatcher
        org.springframework.web.servlet.DispatcherServlet
        1
      

    
        dispatcher
        *.do
    

    
        org.springframework.web.context.ContextLoaderListener
    
    
        contextConfigLocation
        classpath:/spring/applicationContext.xml
    
Here you can see I it triggers a dispatcher servlet when the request consist of .do extension. Following is the dispatcher file.
  
 
    
    

    
    
 
It defines the package where the spring should search for controllers. And also you can see it consists of the view resolver which uses by the controllers to resolve the views from the returned ModelAndViews.

And if you have a closer look in to the web.xml file you can see it has load the context configuration which acts as an ioc container of spring framework.

 
    
    
    

    
          

    
    

    
        
        
            
                ${hibernate.dialect}
                ${hibernate.show_sql}
            
        
        
    


    
    

    
DataSource properties are loaded from config.properties files in the resources directory. Then what you have to do is implement domain and its dao class. Here I have mentioned only the dao class. You can find domain class in the svn project.

 
import java.util.List;

import com.exilesoft.contactmanager.domain.Contact;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
@Transactional
public class ContactsDAO
{
    @Autowired
    private SessionFactory sessionFactory;

    public Contact getById(int id)
    {
        return (Contact) sessionFactory.getCurrentSession().get(Contact.class, id);
    }

    @SuppressWarnings("unchecked")
    public List searchContacts(String name)
    {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Contact.class);
        criteria.add(Restrictions.ilike("name", name+"%"));
        return criteria.list();
    }

    @SuppressWarnings("unchecked")
    public List getAllContacts()
    {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Contact.class);
        return criteria.list();
    }

    public int save(Contact contact)
    {
        return (Integer) sessionFactory.getCurrentSession().save(contact);
    }

    public void update(Contact contact)
    {
        sessionFactory.getCurrentSession().merge(contact);
    }

    public void delete(int id)
    {
        Contact c = getById(id);
        sessionFactory.getCurrentSession().delete(c);
    }
}
Then what you have to do is call those methods from the controller class. I will left the controller code and the jsp codes since it is easy to understand.
You can find the code in following repository.

http://es-code-snippets.googlecode.com/svn/trunk/contactmanager/