Labels

Java (10) Spring (10) Spring MVC (6) Web Services (5) Rest (4) Javascript (3) Nodejs (3) Spring Batch (3) Angular (2) Angular2 (2) Angular6 (2) Expressjs (2) Passportjs (2) SOAP (2) SOAPUI (2) Spring Boot (2) AJAX (1) H2 (1) JQuery (1) JUnit (1) Npm (1) Puppeteer (1) Python (1) RaspberryPi (1) Raspbian (1) SQL (1) SQLite (1) Scripts (1) html (1)

Tuesday, March 21, 2017

Basic Spring MVC project with fom handling

If you enjoy Spring and its ways, and you are interested in web development, Spring MVC is definitively for you. We will see a simple example of Spring MVC app with Spring Boot.

To develop an easy MVC project (in conjuction with spring Boot) you basically have to care about three things:

1. The configuration files (MvcConfig.java MvcFormsExampleApplication.java and ServletConfig.java.

2. The controller (HomeControler.java which will communicate with the user and will determine the behavior of the app.

3. The views (in our case jsp files).

Setting up the project

We obtained the basic template using the feature Spring Starter Project of STS (the Spring Tool Suite IDE)



 This is how our project will look like:




First, lets start with the pom.xml file


<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>mvc-forms-example</groupId>
 <artifactId>hjbello</artifactId>
 <version>0.1.0</version>
 <packaging>war</packaging>
 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.2.2.RELEASE</version>
 </parent>

 <dependencies>
  <dependency>
   <groupId>org.apache.tomcat.embed</groupId>
   <artifactId>tomcat-embed-jasper</artifactId>
   <scope>provided</scope>
  </dependency>
  <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-catalina</artifactId>
        <version>8.0.28</version>
    </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>jstl</artifactId>
   <exclusions>
    <exclusion>
     <groupId>javax.servlet</groupId>
     <artifactId>servlet-api</artifactId>
    </exclusion>
   </exclusions>
  </dependency> 
 </dependencies>

 <build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
     <executable>true</executable>
    </configuration>
    <executions>
     <execution>
      <goals>
       <goal>repackage</goal>
      </goals>
     </execution>
    </executions>
   </plugin>
  </plugins>
 </build>
</project>

We have added the dependencies org.apache.tomcat.embed and org.apache.tomcat because we will want to use an embedded tomcat server for our spring boot project.



Configuration files


In the class  WebMvcConfigurerAdapter we configure the resources of the app, and we establish that we will use jsp files which will be sotred in the WEB-INF folder of our web content.


package com.example;

   
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter{
 private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

 @Override
 public void addResourceHandlers(ResourceHandlerRegistry registry) {
  if(System.getProperty("os.name").toLowerCase().contains("windows")){
   registry.addResourceHandler("/images/**").addResourceLocations("file:///C:/");
  } else {
   //System.getProperty("user.home")
   registry.addResourceHandler("/images/**").addResourceLocations("file:/");

  }
 }

 @Bean
 public InternalResourceViewResolver viewResolver() {
  InternalResourceViewResolver resolver = new InternalResourceViewResolver();
  resolver.setPrefix("/WEB-INF/jsp/");
  resolver.setSuffix(".jsp");
  return resolver;
 }   

}


 In ServletConfig we choose configure the port of our tomcat Server.


package com.example;

import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;

@Controller
public class ServletConfig {
    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {
        return (container -> {
            container.setPort(8080);
        });
    }
}

And our classic public static void main method, which will be used by Spring Boot to start the embedded tomcat server.


package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MvcFormsExampleApplication {

 public static void main(String[] args) {
  SpringApplication.run(MvcFormsExampleApplication.class, args);
 }
}




The views

We will choose a very simple jsp file with a form that we will use to pass a parameter to the controller:


<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Home</title>
<link href="<spring:url value="css/app.css" />" rel="stylesheet" type="text/css">
</head>
<body>
 <h1>Hello world!</h1>
 <form action="send">
  <input type="text" name="id" /> <input type="submit" />
 </form>
</body>
</html>

The parameter will be called id, and will be passed to the controller every time we click the button..



The Controller

This here is an easy example of a controller


package com.example;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
  
/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {

 private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

 /**
  * Simply selects the home view to render by returning its name.
  */
 @RequestMapping(value = "/", method = RequestMethod.GET)
 public String home(Model model) {  
  logger.info(".....");
  return "home";
 }
 
 @RequestMapping(value = "/send", method=RequestMethod.GET)
 @ResponseBody
 public ModelAndView form(@RequestParam("id") String id) {
     System.out.println(id);
     ModelAndView mv = new ModelAndView();
     mv.setViewName("home2");
     mv.addObject("id", id);
  return mv;
     }

}


The annotation @Controller is what spring needs to know that this is going to be behind the views.
In HomeController we have two requestMappings  that will act as listeners.

The method home is for the value "/" the other method form is for "/send" . The first method will be triggered when we access the url
localhost:8080/ . The second one when we access localhost:8080/send which will also happen when we click the button defined in the previous view.

We use @RequestParam("id") to indicate that the requestMapping should obtain the parameter id from a form in the view that went before we access to /send.

form returns the object mv which is a ModelAndView, that has added an object "id". In this case id is the same one that we introduce in home.jsp.

This is the jsp that form will return:





<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
 <title>Home</title>
 <link href="<spring:url value="css/app.css" />" rel="stylesheet" type="text/css">
</head>
<body>
<h1>
 you passed ${id}  
</h1>

 </body>
</html>


Running the Spring Boot application


We start the app running the main method of MvcFormsExampleApplication with STS



This is the fist view:
 This is the response:



Download the code here:

https://github.com/HugoJBello/java-projects-tutorials/tree/master/spring-mvc-forms-example



No comments:

Post a Comment