Spring MVC Tutorial
Spring MVC, a Java Model-View-Contraller (MVC) web framework, which builds on top of the Spring Inversion of control(IoC) framework.
Rewrite and Spring 4 (12/Jun/2015)
I’m rewriting the outdated articles and upgrade it to Spring 4, give me some time 🙂
I’m rewriting the outdated articles and upgrade it to Spring 4, give me some time 🙂
1. Spring MVC Hello World
Some hello world examples to quick start Spring MVC framework.
- Gradle – Spring 4 MVC Hello World Example (XML Configuration)
- Gradle – Spring 4 MVC Hello World Example (@JavaConfig + Servlet 3)
- Maven – Spring 3 MVC Hello World Example (XML Configuration)
- Maven – Spring 3 MVC Hello World Example (@JavaConfig + Servlet 3)
- Spring 3 REST Example (Working)
- Spring 4 REST Example (Working)
@Deprecated
– Maven + Spring 2.5.6 MVC hello world example@Deprecated
– Maven + Spring 2.5.6 MVC hello world annotation example
New & Updated…
2. Handler Mapping
Define how web request (URL) maps to the Controller handlers.
- BeanNameUrlHandlerMapping example
Maps the requested URL to the name of the cocntroller. - ControllerClassNameHandlerMapping example
Uses convention to map the requested URL to Controller. - SimpleUrlHandlerMapping example
Allow developer to specify the mapping of URL patterns and handler mappings explicitly. - Configure the handler mapping priority
If multiple view handler mappings are applied, you have to declare priority to avoid conflict issue.
3. Controller
Controller class to handle the web request.
- MultiActionController example
Group related actions into a single controller class. - MultiActionController annotation example
Multi-actions controller by using annotation, @RequestMapping, he best and easy solution. - PropertiesMethodNameResolver example
A flexible method name resolver for the MultiActionController controller class, it allow to define the mapping between requested URL and method name explicitly. - ParameterMethodNameResolver example
Another method name resolver for the MultiActionController controller class, it allow to map URL to method name via requested parameter name. - ParameterizableViewController example
With ParameterizableViewController, you don’t need to hard code the view name in the controller class anymore, instead, you specify the view name through the ParameterizableViewController’s “viewName” property.
4. View Resolver
Resolve “view name” that returned from the controller class to a physical view page or JSP page.
- InternalResourceViewResolver example
Adding a predefined prefix and suffix to the view name (prefix + view name + suffix), and generate the final view page URL. - XmlViewResolver example
Puts view beans in XML file. - ResourceBundleViewResolver example
Puts view beans in “.properties” file. - Configure multiple view resolvers priority
If multiple view resolver strategies are applied, you have to declare priority to avoid conflict issue.
5. Form Handling
Form handling in Spring MVC.
- Form handling example
Form handling in Spring MVC, XML based version. - Form handling annotation example
Form handling in Spring MVC, annotation version. - Handling duplicate form submission
“Post/Redirect/Get” Design Pattern is the common solution for this duplicated form submission problem. - RedirectView example
A view which redirect to another absolute, context relative, or current request relative URL. - Handling multipage / wizard forms
How to handle multipage forms or wizard form.
6. Spring’s Form Tag Library
Render HTML form’s components via Spring’s form tag.
- Textbox example
<form:input /> tag, render a HTML textbox field. - Password example
<form:password /> tag, render a HTML password field. - Textarea example
<form:textarea /> tag, render a HTML textarea field. - Checkbox and Checkboxes example
<form:checkbox />, <form:checkboxes /> tags, render a single or multiple HTML check boxes. - Radiobutton and Radiobuttons example
<form:radiobutton />, <form:radiobuttons /> tags, render a single or multiple HTML radio buttons. - Dropdown and list box example
<form:select />, <form:option /> and <form:options /> tags, render a HTML dropdown box, multiple select box and listbox. - Hidden value example
<form:hidden /> tags, render a HTML hidden value field. - Form errors tag example
<form:errors /> tag , render those form components error messages. - File upload example
File upload handling via Spring MultipartResolver.
7. Integrating Spring MVC with other frameworks
Integrate Spring MVC with others.
- Spring 3 MVC and JSR303 @Valid example
Using Hibernate validator (JSR303 implementation) to validate bean in Spring MVC. - Spring 3 MVC and RSS feed example
Using ROME to generate RSS feed from Spring MVC. - Spring 3 MVC and XML example
Using JAXB to generate XML output from Spring MVC. - Spring 3 MVC and JSON example
Using Jackson to generate JSON output from Spring MVC. - Spring MVC and Excel file via AbstractExcelView
Using AbstractExcelView to export data to Excel file via Apache POI library. - Spring MVC and Excel file via AbstractJExcelView
Using AbstractJExcelView to export data to Excel file via JExcelAPI library. - Spring MVC and PDF file via AbstractPdfView
Using AbstractPdfView to export data to Pdf file via Bruno Lowagie’s iText library. - Spring MVC and Log4j integration example
Example to integrate Log4j into the Spring MVC application.
8. FAQs
Some common use cases.
- Spring 3 MVC ContentNegotiatingViewResolver example
This view resolver let you determine which view resolver will be returned, base on reuqested file extension. - Exception handling example
Exception handling in Spring MVC. - Handler interceptors example
Intercept web request through handler interceptors. - Internationalization example
Multiple languages supported in Spring MVC.
10. Common Errors
Spring MVC common errors and solution.
- ModelAndView’s model value is not displayed in JSP via EL
- 404 error code is not working in Spring MVC
- Cannot change HTTP accept header – use a different locale resolution strategy
- Spring MVC failed to convert property value in file upload form
- Neither BindingResult nor plain target object for bean name ‘xxx’ available as request attribute
- ClassNotFoundException : com.sun.syndication.feed.WireFeed
- ClassNotFoundException : com.thoughtworks.xstream.io.HierarchicalStreamReader
Hi,
Thanks for your tutos that are very helpful. I want to know if it is possible to include a php file into the resources folder with Spring.
Thanks in advance for your response
thank you!!
hi..sir..your examples are very helpful..can u share some spring-aws examples..and how to use it…
give me some guidence
i don’t understand spring mvc flow and spring secruity please explain in simple ways
Hi, Where is 9?
Can you provide application event example. I wrote one :
@Component
public class AppStartListener implements ApplicationListener {
public void onApplicationEvent(ContextRefreshedEvent arg0) {
System.out.println(“Inside onApplication Listener”);
}
}
But this class is not running on application booting.
I want something like ServletContextListener in Spring 3.
How can I set context path for my Spring MVC web app?
Here’s what I’m wondering how to do, we have some existing Spring Web apps. There’s a request to have all the web apps map off the same base URL.
For example, let say the base URL needs to be ‘mtools’ and we have 2 web applications a dashboard and tracking.
The goal is to have the routes map like so ‘/mtools/dashboard’ and ‘/mtools/tracking’.
By default, the project POM specifies the ‘name’ and that name is the base context used by Servlet for Mapping/routing.
So I’m not sure how to override the context-base URL for the 2 web applications.
do you have any ideas?
thank you.
Thank you ! Mkyong
I have implemented maven based multimodule project. and each project is based on [spring mvc + hibernate + Jax-rs] and having an annotation based configuration. after combining them i need to configure them in such a way that it can execute mail module as well as sub module.
Hi, Could you please add a Tutorial for Spring MVC with dataTable rendering on JSP.
I have some action like
1. fitness/add
2. fitness/delete
3. dinning/add
4. dinning/delete
I want to show only (do ex – http://localhost:8080/projectName/do ) in URL for every action in spring.
Can you help me, how to do
Hello Mkyong,
hope you doing well, i really learnt a lot from you and now i’m stuck in Bootstrap!
i want a simplest way and detailed explanation of how to add Bootstrap framework to spring 3 using maven.
Thanks in advance
Regards
Sultan
test
Hi can u please tell me how to upload a 2GB Excel or CSV file and read and store in db in spring mvc
hi you doing great work. Please put more tutorials on spring 4.2
Can you Please Provide Spring MVC example with NetBeans IDE and please also provide some tutorial for IOC theory.
could not found arctype id
I am fasing 1 problem with mobven
org.springframework.beans.NullValueInNestedPathException: Invalid property ‘address’ of bean class [gov.school.payroll.shared.model.bean.BeanSchoolDetail]: Could not instantiate property type [gov.school.payroll.shared.model.Address] to auto-grow nested property path: java.lang.InstantiationException: gov.school.payroll.shared.model.Address
at org.springframework.beans.BeanWrapperImpl.newValue(BeanWrapperImpl.java:657)
at org.springframework.beans.BeanWrapperImpl.createDefaultPropertyValue(BeanWrapperImpl.java:623)
at org.springframework.beans.BeanWrapperImpl.setDefaultValue(BeanWrapperImpl.java:611)
at org.springframework.beans.BeanWrapperImpl.getNestedBeanWrapper(BeanWrapperImpl.java:575)
at org.springframework.beans.BeanWrapperImpl.getBeanWrapperForPropertyPath(BeanWrapperImpl.java:549)
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:917)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:95)
at org.springframework.validation.DataBinder.applyPropertyValues(DataBinder.java:749)
at org.springframework.validation.DataBinder.doBind(DataBinder.java:645)
at org.springframework.web.bind.WebDataBinder.doBind(WebDataBinder.java:189)
at org.springframework.web.bind.ServletRequestDataBinder.bind(ServletRequestDataBinder.java:106)
at org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.bindRequestParameters(ServletModelAttributeMethodProcessor.java:150)
I am getting above error.
Address is one of the field in SchoolDetail class.
My SchoolDetail is an interface :
import java.util.Date;
public interface SchoolDetail {
public School getSchool();
public void setSchool(School School) ;
public String getDISENO() ;
public Address getAddress();
public void setAddress(Address addresses);
public long getId();
public void setId(long id);
public void setIsNew(boolean isNew);
public boolean isNew();
}
It has got 2 implementations. BeanSchoolDetail and JpaSchoolDetail.
Address is again interface and has got 2 implementation similar to above
package gov.school.payroll.shared.model;
public interface Address{
public String getHouseNo();
public void setHouseNo(String houseNo);
public String getLine1();
public void setLine1(String line1);
public String getVillage();
public void setVillage(String village);
public String getTaluka();
public void setTaluka(String taluka);
public String getDistrict();
public void setDistrict(String district);
public String getState();
public void setState(String state);
public String getPin();
public void setPin(String pin);
}
I am using spring mvc. Given below is my jsp page
window.onload = function() {
new JsDatePick({
useMode : 2,
target : “sod”,
dateFormat : “%d-%M-%Y”
});
new JsDatePick({
useMode : 2,
target : “doacc”,
dateFormat : “%d-%M-%Y”
});
new JsDatePick({
useMode : 2,
target : “doj”,
dateFormat : “%d-%M-%Y”
});
};
${school.schoolName}(${school.schoolCode})
Add School Details
Update School Details
?????? ????????? ????
Message : ${errorMessage.errorMessage}
DISENO
Medium
<%–
Contact Numbers:
Work
Home
Mobile
–%>
School Opening Date
Address:
House No
House Number
Village
Taluka
District
State
Pin Code
Email Id
Website URL
* indicates a required field
Add
Update
and the controller is
package gov.school.payroll.mvc.web.controller;
import gov.school.payroll.mvc.web.exception.DatabaseException;
import gov.school.payroll.mvc.web.validator.SchoolDetailFormValidator;
import gov.school.payroll.service.service.SchoolDetailService;
import gov.school.payroll.service.service.SchoolService;
import gov.school.payroll.service.service.TeacherService;
import gov.school.payroll.shared.model.School;
import gov.school.payroll.shared.model.SchoolDetail;
import gov.school.payroll.shared.model.Teacher;
import gov.school.payroll.shared.model.bean.BeanSchoolDetail;
import gov.school.payroll.shared.util.testDataCreator.EntityInstanceCreator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import javax.persistence.NoResultException;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.ConversionService;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
@SessionAttributes(types = SchoolDetail.class)
public class SchoolDetailController {
public static final String SCHOOL_ATTRIBUTE = “schoolDetail”;
private static final Logger logger = LoggerFactory
.getLogger(SchoolController.class);
@Autowired
SchoolService schoolService;
//@Autowired
SchoolDetailService schoolDetailService;
@Autowired
TeacherService employeeService;
// @Autowired
SchoolDetailFormValidator schoolDetailFormValidator;
@Autowired
public SchoolDetailController(SchoolDetailService schoolDetailService, SchoolDetailFormValidator validator){
this.schoolDetailService = schoolDetailService;
this.schoolDetailFormValidator = validator;
}
/* @Autowired
private ConversionService conversionService;
@InitBinder
protected void initBinder(ServletRequestDataBinder binder) {
binder.setConversionService(conversionService);
}*/
/*@InitBinder(“contactNos”)
protected void initContactNosBinder(WebDataBinder binder) {
binder.setValidator(new ContactNosValidator());
}
*/
/*@InitBinder(“schoolDetail”)
public void initSchoolDetailBinder(WebDataBinder binder) {
// binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(“dd/MM/yyyy”), true, 10));
SchoolDetailFormValidator schoolDetailFormValidator = new SchoolDetailFormValidator();
schoolDetailFormValidator.setAddressValidator(new AddressValidator());
binder.setValidator(schoolDetailFormValidator);
}*/
@ModelAttribute(value = “BRCCordinatorList”)
public List BRCCordinatorList() {
return employeeService.findAll();
}
@ModelAttribute(value = “CRCCordinatorList”)
public List CRCCordinatorList() {
return employeeService.findAll();
}
// save or update SchoolDetail
@RequestMapping(value = “/schoolDetail/save”, method = RequestMethod.POST)
public String saveOrUpdateSchoolDetail(
@ModelAttribute(“schoolDetailForm”) @Validated BeanSchoolDetail schoolDetail,
final SessionStatus status,
BindingResult result, Model model,
final RedirectAttributes redirectAttributes) {
schoolDetailFormValidator.validate(schoolDetail, result);
logger.debug(“saveOrUpdateSchoolDetail() : {}”, schoolDetail);
if (result.hasErrors()) {
return “schools/schooldetailform”;
}
redirectAttributes.addFlashAttribute(“css”, “success”);
if (schoolDetail.getId() < 1 ) {
redirectAttributes.addFlashAttribute("msg",
"School Details added successfully!");
} else {
redirectAttributes.addFlashAttribute("msg",
"School Details updated successfully!");
}
schoolDetailService.saveOrUpdate(schoolDetail);
status.setComplete();
// POST/REDIRECT/GET
return "redirect:/schoolDetail/" + schoolDetail.getSchool().getSchoolCode();
// POST/FORWARD/GET
//return "school/list";
}
// show add user form
@RequestMapping(value = "/schoolDetail/{schoolCode}/add", method = RequestMethod.GET)
public String showAddSchoolDetailForm(
@PathVariable("schoolCode") String schoolCode, Model model) {
logger.debug("showAddSchoolForm()");
SchoolDetail schoolDetail = EntityInstanceCreator.getSchoolDetailEntity();
schoolDetail.setIsNew(true);
School school = schoolService.findSchoolOnlyBySchoolCode(schoolCode);
schoolDetail.setSchool(school);
model.addAttribute("school", school);
model.addAttribute("schoolDetailForm", schoolDetail);
return "schools/schooldetailform";
}
@RequestMapping(value = "/schoolDetail/{schoolCode}/update", method = RequestMethod.GET)
public String showUpdateSchoolDetailForm(
@PathVariable("schoolCode") String schoolCode, Model model) {
logger.debug("showUpdateSchoolDetailForm() : {}", schoolCode);
model.addAttribute("schoolDetailForm", schoolDetailService
.findBySchoolCode(schoolCode).get());
return "schools/schooldetailform";
}
@RequestMapping(value = "/schoolDetail/{schoolCode}", method = RequestMethod.GET)
public String showSchoolDetail(@PathVariable("schoolCode") String schoolCode,
Model model) {
logger.debug("showSchoolDetail() schoolCode: {}", schoolCode);
Optional schoolDetail = schoolDetailService
.findBySchoolCode(schoolCode);
if (!schoolDetail.isPresent()) {
model.addAttribute(“css”, “danger”);
model.addAttribute(“msg”, “School Details not found for School Code “+schoolCode);
} else {
model.addAttribute(“school”, schoolDetail.get());
}
return “schools/showschooldetail”;
}
@ExceptionHandler(NoSuchElementException.class)
public ModelAndView handleNoSuchElementException(
HttpServletRequest request, DatabaseException ex) {
logger.error(“Requested URL=” + request.getRequestURL());
logger.error(“Exception Raised=” + ex);
return setExceptionDetails(request, ex);
}
@ExceptionHandler(NoResultException.class)
public ModelAndView handleNoResult(HttpServletRequest req, Exception ex) {
logger.debug(“handleEmptyData()”);
logger.error(“Request: {}, error “, req.getRequestURL(), ex);
return setExceptionDetails(req, ex);
}
@ExceptionHandler(DataIntegrityViolationException.class)
public ModelAndView handleDataIntegrityViolation(HttpServletRequest req,
Exception ex) {
logger.debug(“handleDataIntegrityViolation()”);
logger.error(“Request: {}, error “, req.getRequestURL(), ex);
return setExceptionDetails(req, ex);
}
private ModelAndView setExceptionDetails(HttpServletRequest req,
Exception ex) {
ModelAndView model = new ModelAndView();
model.addObject(“ex”, ex);
model.addObject(“url”, req.getRequestURL());
model.setViewName(“schools/show”);
model.addObject(“msg”, “school not found”);
return model;
}
}
Please tell me how to remove this error.
which class is used to connect spring with mvc ?
Nice blog written on “Spring MVC” which described information on its flow, controllers, handlers, etc. The information contained in the blog is very helpful for Java developers. Here is an another informative blog published on Spring MVC & MongoDB http://findnerd.com/list/view/Spring-MVC-and-MongoDB/2240/ , hope this will help developers too to understand the Spring MVC in a detailed way. While learning from this blog developers can also post & view java questions and answers to enhance the tech knowledge among the developers community.
can any body please let me know how to read a ldap file which is in resourece file through code.
I tried using classpah:users.ldif with context parametes but it didnt work.
Hi Mkyong,
I want create a web application using Spring Web MVC + Maven + Spring Boot using STS.
Could you please guide me with steps to create the same ?
Thanks
Kindly share me the tutorial how we do the exception handling in Spring 2.5 without annotation.
check this configuration in mvc-dispatcher-servlet.xml, which is pointing to correct package path in your project or not. this should help.
Hello MKYong,
I have a question to ask —— when using Converter to convert data, if there are type conversion errors, how to send the detailed errors to the web page in order to be saw
Model-View-Contraller (MVC). Sir can you please check the spelling of “contraller”.
hi
while executing simple spring mvc program am facing the the bello issue from STS.. could you please help me out in this issue.
java.lang.NoClassDefFoundError: org/springframework/context/ApplicationContextException
Great Job…God Bless you !!!
can anybody explain about SessionAttribute in xml and @SessionAttrubute ?? whta is use of those two???