Spring MVC 4 : Static resources, Form Post

In the previous post we saw how to make a simple spring mvc 4 project without any xml files. We will continue with the same project. Lets take up serving static resources like css etc for our project. Lets create a resources folder inside out webContent folder. Then create a css folder inside this with a style.css file in it.


h1 {
color:blue;
}

Including this css file in out greetings.jsp


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello</title>
<link rel="stylesheet" href="resources/css/style.css" type="text/css"/>
</head>
<body>
<h1>${greeting}</h1>
</body>
</html>

Lets run and see

springmvc4-addingresouce

Notice that our style.css didnt load hence the css was not applied. To add the ability to add static files from within our application lets open our WebAppConfig.java and extend it with WebMvcConfigurerAdapter class and override addResourceHandlers method.


package com.mynotes.spring.mvc4.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;

@Configuration
@ComponentScan(basePackages = "com.mynotes.spring.mvc4")
@EnableWebMvc
public class WebAppConfig extends WebMvcConfigurerAdapter{

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

return resolver;
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}

}

Restarting and running again:

springmvc4-staticresorce2

Till now we have seen GET calls to our controller. Lets take an example for POST. In this senario we will have a simple registration form that when submitted will call a controller and capture the data. Our model – RegistrationModel.java


package com.mynotes.spring.mvc4.model;

public class RegistrationModel {

private String fname;
private String lname;
private String email;
private String phone;

public String getFname() {
return fname;
}

public void setFname(String fname) {
this.fname = fname;
}

public String getLname() {
return lname;
}

public void setLname(String lname) {
this.lname = lname;
}

public String getEmail() {
return email;
}

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

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

@Override
public String toString() {
return "RegistrationModel [fname=" + fname + ", lname=" + lname + ", email=" + email + ", phone=" + phone + "]";
}

}

Our new controller – RegistrationController.java


package com.mynotes.spring.mvc4.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.mynotes.spring.mvc4.model.RegistrationModel;

@Controller
public class RegistrationController {

@RequestMapping(value="/register", method = RequestMethod.GET)
public String displayAttendeePage(Model model) {

RegistrationModel form = new RegistrationModel();
model.addAttribute("registrationModel", form);
return "registration";
}

@RequestMapping(value="/register", method = RequestMethod.POST)
public String processAttendee(@ModelAttribute("registrationModel") RegistrationModel form) {

System.out.println(form);
return "success";
}

}

So the GET method above will initialize the registrationModel and open registration.jsp from our views. POST will capture the submitted form. The model attribute registrationModel is the same as the command name in jsp. registration.jsp


<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration</title>
</head>
<body>
<form:form method="post" action="register" commandName="registrationModel">
<h2>Registration</h2>
<table>
<tr>
<td><form:label path="fname">First Name</form:label></td>
<td><form:input path="fname" /></td>
</tr>
<tr>
<td><form:label path="lname">Last Name</form:label></td>
<td><form:input path="lname" /></td>
</tr>
<tr>
<td><form:label path="email">Email</form:label></td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td><form:label path="phone">Phone</form:label></td>
<td><form:input path="phone" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Register"/>
</td>
</tr>
</table>

</form:form>
</body>
</html>

Notice the spring tag libraries we included at the top. commandName is the name of the model attribute under which the form object is exposed (done in controller). Defaults value is ‘command’. The exact same thing can be said of ‘modelAttribute’. You got to have one mentioned if you have a name other than the default (command). Also it needs to be setted in controller.The form:input, form:label path attribute should be of same name as that of your form member variables of RegistrationModel class. Also notice the method post.

success.jsp


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello</title>
</head>
<body>
<h1>Registration Success</h1>
</body>
</html>

Restarting server and running:

springmvc4-register1

Submitting this will call our POST controller and print the values.
Above example we have hardcoded label values right now in our jsp. Lets replace them with values from properties file that supports english and spanish for now.

messages_en.properties


label.fname=First Name
label.lname=Last Name
label.email=Email
label.phone=Phone
label.register=Register

messages_es.properties


label.fname=Nombre de pila
label.lname=Apellido
label.email=Email
label.phone=Teléfono
label.register=Registro

Chaging our jsp registration.jsp.


<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration</title>
</head>
<body>
<form:form method="post" action="register" commandName="registrationModel">
<h2>Registration</h2>
<a href="?language=en">
English
</a>
<a href="?language=es">
Spanish
</a>
<table>
<tr>
<td><form:label path="fname"><spring:message code="label.fname"/></form:label></td>
<td><form:input path="fname" /></td>
</tr>
<tr>
<td><form:label path="lname"><spring:message code="label.lname"/></form:label></td>
<td><form:input path="lname" /></td>
</tr>
<tr>
<td><form:label path="email"><spring:message code="label.email"/></form:label></td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td><form:label path="phone"><spring:message code="label.phone"/></form:label></td>
<td><form:input path="phone" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="<spring:message code="label.register"/>"/>
</td>
</tr>
</table>

</form:form>
</body>
</html>

Changing WebAppConfig.java


package com.mynotes.spring.mvc4.config;

import java.util.Locale;

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@ComponentScan(basePackages = "com.mynotes.spring.mvc4")
@EnableWebMvc
public class WebAppConfig extends WebMvcConfigurerAdapter{

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

return resolver;
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}

@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}

@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver resolver = new SessionLocaleResolver();
resolver.setDefaultLocale(Locale.ENGLISH);
return resolver;
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor changeInterceptor = new LocaleChangeInterceptor();
changeInterceptor.setParamName("language");
registry.addInterceptor(changeInterceptor);
}

}

So above we defined 3 beans. First to look for a message source file name – messages. In the default Local resolver we setted English and then we added and interceptor, local change interceptor to be precise that will look for the language parameter to change the locale.

springmvc4-i18n

%d bloggers like this: