Main Tutorials

Spring MVC Tutorial

Spring MVC Tutorials

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 🙂

1. Spring MVC Hello World

Some hello world examples to quick start Spring MVC framework.

New & Updated…

2. Handler Mapping

Define how web request (URL) maps to the Controller handlers.

3. Controller

Controller class to handle the web request.

4. View Resolver

Resolve “view name” that returned from the controller class to a physical view page or JSP page.

5. Form Handling

Form handling in Spring MVC.

6. Spring’s Form Tag Library

Render HTML form’s components via Spring’s form tag.

7. Integrating Spring MVC with other frameworks

Integrate Spring MVC with others.

8. FAQs

Some common use cases.

10. Common Errors

Spring MVC common errors and solution.

Spring Web MVC References

  1. Spring 4.2.x MVC Documentation
  2. Spring 3.2.x MVC Documentation
  3. Spring 2.5.6 MVC Documentation

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
115 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
new2j2e
7 years ago

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

common
8 years ago

thank you!!

sunil
8 years ago

hi..sir..your examples are very helpful..can u share some spring-aws examples..and how to use it…
give me some guidence

Hemant
6 years ago

i don’t understand spring mvc flow and spring secruity please explain in simple ways

Meysam
6 years ago

Hi, Where is 9?

Vishwas Tyagi
7 years ago

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.

mbeddedsoft
7 years ago

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.

tao
7 years ago

Thank you ! Mkyong

Dhyanandra Singh
7 years ago

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.

dhiraj bankar
7 years ago

Hi, Could you please add a Tutorial for Spring MVC with dataTable rendering on JSP.

Mohd Furkan
7 years ago

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

sultanc2
8 years ago

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

jj
8 years ago

test

dectatct panday
8 years ago

Hi can u please tell me how to upload a 2GB Excel or CSV file and read and store in db in spring mvc

Kim
8 years ago

hi you doing great work. Please put more tutorials on spring 4.2

rao hannan
8 years ago

Can you Please Provide Spring MVC example with NetBeans IDE and please also provide some tutorial for IOC theory.

vijay
8 years ago

could not found arctype id

vijay
8 years ago

I am fasing 1 problem with mobven

Santosh Zaveri
8 years ago

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.

Ramachandran
8 years ago

which class is used to connect spring with mvc ?

Manoj Rawat
8 years ago

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.

SRIRAM
8 years ago

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.

Jeetendra
8 years ago

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

sourav
8 years ago

Kindly share me the tutorial how we do the exception handling in Spring 2.5 without annotation.

siva ande
9 years ago

check this configuration in mvc-dispatcher-servlet.xml, which is pointing to correct package path in your project or not. this should help.

yang
9 years ago

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

Katta
9 years ago

Model-View-Contraller (MVC). Sir can you please check the spelling of “contraller”.

javeed
9 years ago

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

Sampath
9 years ago

Great Job…God Bless you !!!

singh1411
10 years ago

can anybody explain about SessionAttribute in xml and @SessionAttrubute ?? whta is use of those two???