Spring4 Mvc Form Annotation Example

Click here to download eclipse supported ZIP file



This is index.jsp JSP file and it is used display the output for the application.



<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="register">Please click here to get Registration page !!!</a>
</body>
</html>


This is registration.jsp JSP file and it is used display the output for the application.



<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Registration</title>
</head>
<body>
<div align="center">
<form:form action="register" method="post" commandName="userForm">
<table border="0">
<tr>
<td colspan="2" align="center"><h2>Spring MVC Form Demo - Registration</h2></td>
</tr>
<tr>
<td>User Name:</td>
<td><form:input path="username" /></td>
</tr>
<tr>
<td>Password:</td>
<td><form:password path="password" /></td>
</tr>
<tr>
<td>E-mail:</td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td>Birthday <font color="RED">(mm/dd/yyyy)</font>:</td>
<td><form:input path="birthDate" /></td>
</tr>
<tr>
<td>Profession:</td>
<td><form:select path="profession" items="${professionList}" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Register" /></td>
</tr>
</table>
</form:form>
</div>
</body>
</html>


This is registrationSuccess.jsp JSP file and it is used display the output for the application.



<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Registration Success</title>
</head>
<body>
<div align="center">
<table border="0">
<tr>
<td colspan="2" align="center"><h2>Registration Succeeded!</h2></td>
</tr>
<tr>
<td colspan="2" align="center">
<h3>Thank you for registering! Here's the review of your details:</h3>
</td>
</tr>
<tr>
<td>User Name:</td>
<td>${userForm.username}</td>
</tr>
<tr>
<td>E-mail:</td>
<td>${userForm.email}</td>
</tr>
<tr>
<td>Birthday:</td>
<td>${userForm.birthDate}</td>
</tr>
<tr>
<td>Profession:</td>
<td>${userForm.profession}</td>
</tr>
</table>
</div>
</body>
</html>



This is MvcConfiguration.java file having the source code to execute business logic.


 

    
package com.cv.spring.mvc.form.config;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
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;

/**
 @author Chandra Vardhan
 */

@Configuration
@ComponentScan(basePackages = "com.cv.spring.mvc.form")
@EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter {
  private static final Logger LOGGER = Logger.getLogger(MvcConfiguration.class);

  @Bean
  public ViewResolver getViewResolver() {
    LOGGER.info("Control entered into getViewResolver() method...");
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/views/");
    resolver.setSuffix(".jsp");
    LOGGER.info("Control exited from getViewResolver() method...");
    return resolver;
  }

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    LOGGER.info("Control entered into addResourceHandlers(-) method...");
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    LOGGER.info("Control exited from addResourceHandlers(-) method...");
  }

}


This is RegisterController.java file having the controller logic and it will have the services defined in it.


 

    
package com.cv.spring.mvc.form.controller;

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

import org.apache.log4j.Logger;
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 com.cv.spring.mvc.form.model.User;

/**
 @author Chandra Vardhan
 */

@Controller
@RequestMapping(value = "/register")
public class RegisterController {
  private static final Logger LOGGER = Logger.getLogger(RegisterController.class);  
  @RequestMapping(method = RequestMethod.GET)
  public String viewRegistration(Map<String, Object> model) {
    LOGGER.info("Control entered into viewRegistration(- -)  method...");
    User userForm = new User();    
    model.put("userForm", userForm);
    
    List<String> professionList = new ArrayList<>();
    professionList.add("Developer");
    professionList.add("Designer");
    professionList.add("IT Manager");
    model.put("professionList", professionList);
    LOGGER.info("Control exited from viewRegistration(- -) method...");
    return "registration";
  }
  
  @RequestMapping(method = RequestMethod.POST)
  public String processRegistration(@ModelAttribute("userForm"User user, 
      Map<String, Object> model) {
    LOGGER.info("Control entered into processRegistration(- -) method...");
    // implement your own registration logic here...
    
    // for testing purpose:
    LOGGER.info("username : " + user.getUsername());
    LOGGER.info("password : " + user.getPassword());
    LOGGER.info("email : " + user.getEmail());
    LOGGER.info("birth date : " + user.getBirthDate());
    LOGGER.info("profession : " + user.getProfession());
    LOGGER.info("Control exited from processRegistration(- -) method...");
    return "registrationSuccess";
  }
}


This is User.java file having the source code to execute business logic.


 

    
package com.cv.spring.mvc.form.model;

import java.util.Date;

/**
 @author Chandra Vardhan
 */

public class User {
  private String username;
  private String password;
  private String email;
  private Date birthDate;
  private String profession;

  public String getUsername() {
    return username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public String getEmail() {
    return email;
  }

  public void setEmail(String email) {
    this.email = email;
  }

  public Date getBirthDate() {
    return birthDate;
  }

  public void setBirthDate(Date birthDate) {
    this.birthDate = birthDate;
  }

  public String getProfession() {
    return profession;
  }

  public void setProfession(String profession) {
    this.profession = profession;
  }

}

This is pom.xml file having the entries of dependency jars and information to build the application .


	
<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">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>com.cv.spring.mvc.form</groupId> <packaging>war</packaging> <version>1.0</version> <name>Spring4MvcFormAnnotationExample Maven Webapp</name> http://maven.apache.org <properties> <spring.version>4.2.0.RELEASE</spring.version> <hibernate.version>4.3.5.Final</hibernate.version> <log4j-version>1.2.17</log4j-version> 1.8 Spring4MvcFormAnnotationExample </properties> <build> <finalName>${pom.artifactId}</finalName> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>${jdk.version}</source> <target>${jdk.version}</target> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</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-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> provided </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20090211</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> </dependency> </dependencies> <artifactId>Spring4MvcFormAnnotationExample</artifactId> </project>

This is web.xml deployment descriptor file and it describes how the web application should be deployed.


	
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>Spring4MvcFormAnnotationExample</display-name>
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>SpringDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.cv.spring.mvc.form</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringDispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

This is log4j.properties file having the entries for logging the information into the console/file.



#By default enabling Console appender
# Root logger option
log4j.rootLogger=INFO, stdout

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p [%c]:%L -->> %m%n

# Redirect log messages to a log file
#log4j.appender.file=org.apache.log4j.RollingFileAppender
#log4j.appender.file.File=C:\servlet-application.log
#log4j.appender.file.MaxFileSize=5MB
#log4j.appender.file.MaxBackupIndex=10
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

No comments:

Post a Comment