By kswaughs | Thursday, February 4, 2016

Spring MVC Web application with annotations and maven

Step 1 : Create a Configuration class that extends WebMvcConfigurerAdapter which is equivalent to spring dispatcher context xml.

SpringWebConfig
package com.kswaughs.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@EnableWebMvc 
@Configuration
@ComponentScan({ "com.kswaughs.web" })
public class SpringWebConfig extends WebMvcConfigurerAdapter {
 
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }
 
    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/jsps/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
}


Step 2 : Create a Spring Web Initializer class that extends AbstractAnnotationConfigDispatcherServletInitializer which is equivalent to web.xml.

SpringWebInitializer
package com.kswaughs.servlet;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import com.kswaughs.config.SpringWebConfig;

public class SpringWebInitializer extends
    AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class[] getServletConfigClasses() {
        return new Class[] { SpringWebConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }

    @Override
    protected Class[] getRootConfigClasses() {
        return new Class[] {};
    }
}

Step 3 : Create below model object to pass the data between spring controller and JSPs.

Model Object - Phone
package com.kswaughs.web.beans;

public class Phone {
 
    private String id;
 
    private String name;
 
    private String price;
 
    public Phone() { }
 
    public Phone(String id, String name) {
        this.id = id;
        this.name = name;
    }
 
    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public void setId(String id) {
        this.id = id;
    }

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

Step 4 : Create Controller class to serve the web requests

PhoneController
package com.kswaughs.web.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.kswaughs.web.beans.Phone;
import com.kswaughs.web.service.PhoneService;

@Controller
@RequestMapping(value = "/phones")
public class PhoneController {
 
    @Autowired
    PhoneService phoneSvc;
 
    @RequestMapping(value = "", method = RequestMethod.GET)
    public ModelAndView index(@ModelAttribute("phone") Phone phone) {
  
        List phonesList = phoneSvc.getPhoneslist();
   
        return new ModelAndView("index", "phones",  phonesList);
    }
 
    @RequestMapping(value = "/details", method = RequestMethod.POST)
    public ModelAndView showPrice(@ModelAttribute("phone") Phone phone ) {
    
        phone = phoneSvc.getPhoneDetails(phone);
    
        return new ModelAndView("details", "phone", phone);
    }
}

Step 5 : Create Service class to process the business logic

PhoneService
package com.kswaughs.web.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.kswaughs.web.beans.Phone;

@Service
public class PhoneService {
 
    public List getPhoneslist() {
  
        List phonesList = new ArrayList();
  
        phonesList.add(buildPhone("1", "Samsung Galaxy Y"));
        phonesList.add(buildPhone("2", "Nokia Lumia"));
        phonesList.add(buildPhone("3", "Moto G"));
  
        return phonesList;
    }
 
    public Phone getPhoneDetails(Phone phone) {
    
        final String id = phone.getId();
        String price = null;
        if("1".equals(id)) {
            phone = buildPhone("1", "Samsung Galaxy Y");
            price = "10,000";
   
        } else if("2".equals(id)) {
            phone = buildPhone("2", "Nokia Lumia");
            price = "12,000";
  
        } else if("3".equals(id)) {
            phone = buildPhone("3", "Moto G");
            price = "14,000";
        }
  
        phone.setPrice(price);
        return phone;
     }
 
    private Phone buildPhone(String id, String name) {
  
        Phone phone = new Phone(id, name);
        return phone;
    }
}

Step 6 : Welcome page to show list of available phones

index.jsp
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<spring:url value="/resources/css/style.css" var="style" />
<link href="${style}" rel="stylesheet" />
</head>
<body>
<div>
<p>Welcome to Phones Store</p>
<p>Choose your Phone below</p>
<div>
<form:form method="post" action="${pageContext.request.contextPath}/phones/details" 
modelAttribute="phone">
<c:forEach var="ph" items="${phones}">
<div><form:radiobutton path="id" value="${ph.id}"/>${ph.name}</div>
</c:forEach>
<input type="submit"  value="submit"/>
</form:form>
</div>
</div>
</body>
</html>

Step 7 : Phone details page to display user selected phone name and price.

details.jsp
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<spring:url value="/resources/css/style.css" var="style" />
<link href="${style}" rel="stylesheet" />
</head>
<body>
<div>
<p>Welcome to Phones Store</p>
<p>Your phone details</p>
<div>Phone : ${phone.name}</div>
<div>Price : ${phone.price} Rs/<sub>-</sub></div>
</div>
</body>
</html>

Step 8 : Testing the application. Run the maven build and generated the war with name 'spring_app' and deployed in Tomcat 7 server.

Welcome page

http://localhost:8080/spring_app/phones

Welcome to Phones Store
Choose your Phone below
Samsung Galaxy Y
Nokia Lumia
Moto G

Details page

http://localhost:8080/spring_app/phones/details

Welcome to Phones Store
Your phone details
Phone : Moto G
Price : 14,000 Rs/-

Use Below maven dependencies in your pom.xml.

pom.xml
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${spring.version}</version>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
    <scope>provided</scope>
</dependency>

Recommend this on


No comments:

Post a Comment