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

115 comments on “Spring MVC Tutorial

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

    Reply
  2. 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.

    Reply
  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.

    Reply
  4. 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

    Reply
  5. 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.

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

    Reply
  7. 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

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

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

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

    Reply
  11. 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.

    Reply
  12. which class is used to connect spring with mvc ?

    Reply
  13. 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.

    Reply
  14. 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.

    Reply
  15. 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

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

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

    Reply
  18. 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

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

    Reply
  20. 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

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

    Reply
  22. can you tell me this problem solution

    I make program in spring mvc and run program then (java.lang.NoClassDefFoundError: javax/servlet/http/HttpServlet,HTTP Status 500 – javax/servlet/http/HttpServlet) is show error I set servlet-api.jar file but show error .

    please tell me how can solve this problem

    Reply
  23. Hello Mkyong,

    I really appreciate the way you describe the stuff.

    I am very new to spring framework, I want to develop frames in spring and the frame in left side will interact with the frame at right side like “http://www.wicket-library.com/wicket-examples-6.0.x/frames/”, Could you please provide me some hint to achieve this. this may be pretty easy for you but as a newbie I am struggling to implement this. Hope you will help on this.

    Reply
  24. Hi Mkyong,

    U are doing brilliant job here, Can u please provide a tutorial on Spring Portlets.

    TIA.

    Reply
  25. Spring MVC is expected to host N number of users at any ponit. What is the maximum N? What is the approach followed to attain such a number.

    Reply
  26. An interesting discussion is worth comment. I do believe that you ought to write more on this topic, it may not be a taboo matter but typically folks don’t discuss these issues. To the next! Cheers!!

    Reply
  27. Dear MkYong,
    Please tell me how to overcome Browser back button issue in Spring MVC.?

    Reply
    1. Dear Priyanka,
      That can be done by java script’s browser history option.

      Reply
  28. Hi Mkyong,

    In your JSF 2 + Spring integration example, you didn’t use Spring MVC controller.
    Is integrating Spring MVC with JSF 2 into a same web application not a good idea?
    Will you please explain the reason?

    Many Thanks.

    Reply
  29. Love the blog!

    I was wondering if you’d have any sample code for extending abstract form class of spring, more specifically AbstractDataBoundFormElementTag.

    I’d really like to learn how to write custom Spring Tags.

    Anychance you have anything similar?

    Cheers and keep up the good work!
    Francis

    Reply
  30. Hi everyone, it’s my first pay a visit at this web site, and piece of writing is really fruitful designed for me, keep up posting these content.

    Reply
  31. Hello MKYoung i want to know how to maintain session in spring MVC pls send me replay urgent.

    Thanks

    Reply
  32. hi…your site very helpful for us….
    plz give an example how to read data from excel/csv file in spring web mvc
    plz reply soon

    Reply
    1. public class WidgetListExcelView extends AbstractExcelView
      {
      protected void buildExcelDocument(Map model,
      HSSFWorkbook workbook,
      HttpServletRequest request,
      HttpServletResponse response)
      {

      }
      }
      AbstractExcelView implements the View’s render(Map model, HttpServletRequest request, HttpServletResponse response) for you, makes a new POI HSSFWorkbook, and makes you implement protected void buildExcelDocument(Map model, HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response). From there, you can simply work on the workbook as you would in POI. Spring will handle the messy work of setting the response content type, streaming the workbook to the browser, etc. For more information on working with Excel documents via POI see Busy Developers’ Guide to HSSF Features at the official POI website.

      Here is a full example to generate an Excel document of a list of Widgets:

      /**
      * View to generate an Excel document of a list of Widgets
      * @author rlambert
      */

      public class WidgetListExcelView extends AbstractExcelView
      {
      public static final String WIDGET_LIST_KEY = “widgetList”;
      protected static final short WIDGET_NAME_COLUMN = 0;
      protected static final short WIDGET_SIZE_COLUMN = 1;

      protected void buildExcelDocument(Map model,
      HSSFWorkbook workbook,
      HttpServletRequest request,
      HttpServletResponse response)
      {
      //CREATE THE SHEET
      HSSFSheet sheet = workbook.createSheet(“Widget List”);
      sheet.setDefaultColumnWidth((short) 12);

      //GETCELL: getCell(SHEET, ROW, COLUMN);
      short currentRow = 0;

      //WRITE ROW FOR HEADER
      HSSFCell header0 = getCell(sheet,
      currentRow,
      WIDGET_NAME_COLUMN);
      setText(header0, “NAME”);

      HSSFCell header1 = getCell(sheet,
      currentRow,
      WIDGET_SIZE_COLUMN);
      setText(header1, “SIZE”);

      List widgetList = (List) model.get(WIDGET_LIST_KEY);
      Iterator widgetListIterator = widgetList.iterator();

      while (widgetListIterator.hasNext())
      {
      currentRow++;
      Widget widget = (Widget) widgetListIterator.next();
      HSSFRow row = sheet.createRow(currentRow);
      row.createCell(WIDGET_NAME_COLUMN)
      .setCellValue(widget.getName());
      row.createCell(WIDGET_SIZE_COLUMN)
      .setCellValue(widget.getSize());
      }
      }
      }
      Here’s a simple Controller that uses the above WidgetListExcelView as the View:

      package com.zabada.springbook.excel;

      import java.util.HashMap;
      import java.util.List;
      import java.util.Map;

      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;

      import org.springframework.web.servlet.ModelAndView;
      import org.springframework.web.servlet.mvc.Controller;

      import com.zabada.springbook.dao.WidgetDAO;

      /**
      * Controller to show a Widget List in an Excel document
      *
      * @author rlambert
      */
      public class WidgetListExcelController implements Controller
      {
      private WidgetDAO dao;

      public void setWidgetDAO(WidgetDAO dao)
      {
      this.dao = dao;
      }

      /* (non-Javadoc)
      * @see org.springframework.web.servlet.mvc.Controller
      * #handleRequest(javax.servlet.http.HttpServletRequest,
      * javax.servlet.http.HttpServletResponse)
      */
      public ModelAndView handleRequest(HttpServletRequest arg0,
      HttpServletResponse arg1)
      throws Exception
      {
      Map model = new HashMap();
      List list = dao.getWidgets();
      model.put(WidgetListExcelView.WIDGET_LIST_KEY, list);
      return new ModelAndView(new WidgetListExcelView(), model);
      }
      }

      Reply
  33. i m getting following exception in sprin mvc,can any one resolve it

    1)
    java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered?

    2)

    Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:524)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:417)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:320)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:803)

    root cause

    javax.servlet.ServletException: javax.servlet.jsp.JspException: Can’t get definitions factory from context.
    org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:850)
    org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:779)
    org.apache.jsp.index_jsp._jspService(index_jsp.java:82)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:393)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:320)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:803)

    root cause

    javax.servlet.jsp.JspException: Can’t get definitions factory from context.
    org.apache.struts.taglib.tiles.InsertTag.processDefinitionName(InsertTag.java:583)
    org.apache.struts.taglib.tiles.InsertTag.createTagHandler(InsertTag.java:487)
    org.apache.struts.taglib.tiles.InsertTag.doStartTag(InsertTag.java:451)
    org.apache.jsp.index_jsp._jspx_meth_tiles_005finsert_005f0(index_jsp.java:99)
    org.apache.jsp.index_jsp._jspService(index_jsp.java:71)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:393)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:320)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:803)

    note

    Reply
    1. You need to configure DispatcherServerlet and xml file in contextLoaderListener.
      May be u missed out those things in web.xml.
      Check it once and let us know

      Reply
    2. there is problem with form:from tag and u need to place it in web-inf or else chane the paht in congi file try to update the dependecy using pom ….

      Reply
  34. i m getting following exception in sprin mvc,can any one resolve it

    1)
    java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered?

    2)
    7:
    8:
    9:
    10:
    11:
    12:

    Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:524)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:417)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:320)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:803)

    root cause

    javax.servlet.ServletException: javax.servlet.jsp.JspException: Can’t get definitions factory from context.
    org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:850)
    org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:779)
    org.apache.jsp.index_jsp._jspService(index_jsp.java:82)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:393)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:320)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:803)

    root cause

    javax.servlet.jsp.JspException: Can’t get definitions factory from context.
    org.apache.struts.taglib.tiles.InsertTag.processDefinitionName(InsertTag.java:583)
    org.apache.struts.taglib.tiles.InsertTag.createTagHandler(InsertTag.java:487)
    org.apache.struts.taglib.tiles.InsertTag.doStartTag(InsertTag.java:451)
    org.apache.jsp.index_jsp._jspx_meth_tiles_005finsert_005f0(index_jsp.java:99)
    org.apache.jsp.index_jsp._jspService(index_jsp.java:71)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:393)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:320)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:803)

    note

    Reply
    1. pls check the web.xml file and write properly and register listener class lik bellow

      org.springframework.web.context.ContextLoaderListener

      contextConfigLocation
      /WEB-INF/contacts.xml, /WEB-INF/resources.xml

      Reply
  35. Hello Sir,

    I request you can you provide any example a caching in Springs MVC.

    Thanks,
    Ankur

    Reply
  36. hi sir,
    spring-mvc::
    i want to go from
    index.jsp(href) to hello.jsp
    can u give me answer request comes from where and go to where.
    is this 1 to 2 to 3 to 4
    or 3 to 1 to 2 to 4

    1.my web.xml have
    *.html

    2.my dispatcher-servelet.xml have

    3. my index.jsp have
    Hello World

    4. my jsp name is hello.jsp

    Reply
  37. hi sir,
    i want to go from
    index.jsp(href) to hello.jsp
    can u give me answer request comes from where and go to where.
    is this 1 to 2 to 3 to 4
    or 3 to 1 to 2 to 4

    1.my web.xml have
    *.html

    2.my dispatcher-servelet.xml have

    3. my index.jsp have
    Hello World

    4. my jsp name is hello.jsp

    Reply
  38. Thanks for all your helpful post.
    Do you have anything on spring mvc (CRUD) where there is a link to edit data on table using jquery dialog? am having problems passing the data to the dialog. Please help. Thanks in advance.

    Reply
  39. I love all your tutorials and I can’t wait until I get to read your MVC spring tutorial. Thanks a lot, your my teacher.

    Reply
  40. Thanks Mykong. It’s a very good site to understand emerging technologies. Will be very helpful if you can put some info on Spring’s Transaction Management and Spring Webflow. That will be great. Thanks a lot!

    Reply
  41. Great tutorial! Spring MVC is my favorite Java web framework. It’s easy to learn, very flexible, and it works! I strongly believe that the request/response paradigm is the way to go!

    Reply
  42. MKyong, thank a lot for your SPRING MVC tutorial.
    Ivo.

    Reply
  43. Could you show us how to handle the request for “WelcomePage” in @Controller class with @RequestMapping. For me it’ll be very helpful.

    Reply
  44. Hi mkyong,

    Good to share knowledge related to java and frameworks. Really like it very much. 🙂 I hope you can post some tutorials about spring-mvc without using maven.

    Reply
    1. Thanks for your kind words. Maven is just a build tool, no dependencies AT ALL, you can just unplug it and still continue using Spring MVC.

      Reply
  45. hey ,Mk Yong i was just luking for the Spring 3.0 and hibernate integeration please guide with the demo how it is done…. i am trying it out but it is throwing certain exceptions

    Reply
  46. this is not clear to get idea about spring + webservices

    Reply
  47. I need an help regarding implementing EJB with the spring framework
    Can you provide the tutor or the link to combine the functionality of spring with ejb(Business layer)

    Reply
  48. I have gone through most of the page(Tutors), it is really marvelous and helps me in getting good knowledge on the technologies.

    By
    DineshT

    Reply
  49. Hello MKYong,

    your website here was the need of the hour help for me in my project implementation.
    I had to complete a project in 10 days in Spring MVC + Restful webservice.

    Guess what, i been simply hitting your site day in and day out and we were able to finish our project within the deadline..

    your certainly deserve a kodos mate..

    thank you for your wonderful help thru your website here..

    Best Regards,
    -Mohan Kumar

    Reply
  50. I must say the tutorials are amazing; thanks a lot.

    Reply
      1. i want to need spring 3.0 and 2.5 example:- if i click u.p state than i show all city.

        Reply
  51. can any one explain how to start spring 2.0 mvc with hibernate?(with example)

    Reply
  52. I was looking for this only. It helped me alot. This is best tutorial on the web . 🙂 🙂 thank you for publishing such a wonderful blog

    Reply
  53. Hi,

    No Doubt, this is really a good tutorial. . but Unfortunately My problem wasn’t solved. . .

    Can I please know how to convert a jsp project which has only two jsp pages(index & data) to Spring MVC Project?

    I would be really gratefull If any oe could assist me. . .

    Thanks in Advance!

    Reply
  54. Thanks for posting good ‘working’ examples on Spring… God bless you..

    Reply
  55. Congratulations for your site.
    I’m from Spain and my work is developer with Java.
    My english language level is very poor, but your site is very good.

    Thanks.

    Reply
    1. don’t know how to convert @ResponseBody Spring 3 to Spring 2..

      Reply
  56. Should i learn spring 3 or spring 2 ?
    most of Malaysia’s IT companys still using spring 2 right ?

    Reply
  57. Hi MkYong,

    May i know how to integrate Spring 2.5.6 MVC (XML based) with Tiles 2.06 ?

    Reply
    1. <bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
              <property name="definitions">
                  <list>
                      <value>/WEB-INF/tiles/defs/tiles-defs.xml</value>
                  </list>
              </property>
          </bean> 
          
          <bean id="tilesViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
              <property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
              <property name="order" value="1"/>
          </bean> 
      
      Reply
  58. Hello Mkyong .

    can u help me to understand beans lifecycle in spring MVC ?
    When beans declared for any controller will be created ?

    Reply
  59. i’m korean..Not English sorry..
    Your Spring3MVC SourceCode..Tomcat7 Test Fail…
    But Tomcat6 Test Test Success..

    fail issue : Tomcat7 and Maven..???……

    Reply
    1. Sir i can understand you have the problem with the Tomcat 7 version,but please be reasonable as this is an open community where young and old of all ages read the good examples given by Mr Mkyong.So if you can refrain yourself from using F word or any other uncalled for statement, all the readers will be grateful to you.
      Thank you.

      Reply
  60. I don’t know how to thank you, you are number one tutorial in the internet, the way you teach things is simple.
    I have some questions please :

    1)Can you please teach us how did you generate a maven project that has pom.xml ?

    2)Any example for spring MVC and Jquery and Json ?

    3)Any example for spring MVC getting/inserting data to a database .

    Thanks Lot.

    Reply
  61. Hei MkYong,

    Nice detailed tutorials. Can you please also add Spring security 3 tutorial. I think this is important part of any application.

    Best Regards.

    Reply
  62. i passed the interview becoz of your site. almost all emerging technologies discuss here. i owe u a lot.

    Reply
  63. Thank you a lot, your tutorials are awsome. So easy to learn from them.

    Reply
  64. This is very useful for freshers for better and easily understanding

    Reply
  65. MKYong,

    You have an excellent ability to breakdown a complicated and overwhelming subject into a simple and easy-to-understand sections. For past year, I have been going through number of Spring Framework books where most authors talk and talk like politicians and never come down to a level of beginner developer and explain with some simple examples. I was never able to get a good grasp of how all the moving pieces work together until I luckily hit your website. Thankyou so much for your simple and clear examples. I was also impressed with your reply to one of the reader that you are also in the process of learning. That also speaks a lot about your good attitude that is often missing in today’s professional world ! Thanks again.

    SY

    Reply
    1. Hi Sriyell,

      Thanks for your kind words, and glad to know it help you in some ways.

      Reply
  66. Clean and neat explanation to the point. Keep it up your good work. This is one of the best sites to start understanding topics related to Java.

    Reply
  67. It is cool that you blogged about this. I found you on yahoo and I had been searching for information about this. Nice site, thanks for the info.

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *