Spring MVC, a Java Model-View-Contraller (MVC) web framework, which builds on top of the Spring Inversion of control(IoC) framework.
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
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
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
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
thank you!!
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..sir..your examples are very helpful..can u share some spring-aws examples..and how to use it…
give me some guidence
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???
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
you can add server runtime libraries. it may be work.
javax.servlet
servlet-api
2.5
provided
thanks this is very useful tutorial.bless u
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.
Hi Mkyong,
U are doing brilliant job here, Can u please provide a tutorial on Spring Portlets.
TIA.
Agree
you are the excellent tutorial guide
for me
thank u
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.
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!!
Dear MkYong,
Please tell me how to overcome Browser back button issue in Spring MVC.?
Dear Priyanka,
That can be done by java script’s browser history option.
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.
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
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.
iugnbm.//;pifcsssaasdvb
Hello MKYoung i want to know how to maintain session in spring MVC pls send me replay urgent.
Thanks
Hi MKYONG ur notes was very good for beginners and i have one doubt does spring forms support HTML5 required attribute??
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
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);
}
}
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
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
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 ….
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
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
Hello Sir,
I request you can you provide any example a caching in Springs MVC.
Thanks,
Ankur
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
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
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.
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.
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!
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!
Thanks MkYong, good collection very useful.
MKyong, thank a lot for your SPRING MVC tutorial.
Ivo.
Could you show us how to handle the request for “WelcomePage” in @Controller class with @RequestMapping. For me it’ll be very helpful.
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.
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.
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
this is not clear to get idea about spring + webservices
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)
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
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
I must say the tutorials are amazing; thanks a lot.
Welcome, good to know it help.
i want to need spring 3.0 and 2.5 example:- if i click u.p state than i show all city.
can any one explain how to start spring 2.0 mvc with hibernate?(with example)
Thakz for uploading bro…..
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
Thanks for your kind words. Will publish more similar posts in future.
Can you provide spring mvc session attribute example
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!
Thanks for posting good ‘working’ examples on Spring… God bless you..
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.
G8 tutorial
Hi MKYong,
may i know how to convert below project to Spring 2 ?
http://krams915.blogspot.com/2010/12/jqgrid-and-spring-3-mvc-integration.html
Thanks.
don’t know how to convert @ResponseBody Spring 3 to Spring 2..
Should i learn spring 3 or spring 2 ?
most of Malaysia’s IT companys still using spring 2 right ?
Depends on company, you should learn Spring DI concept, not the version.
Hi MkYong,
May i know how to integrate Spring 2.5.6 MVC (XML based) with Tiles 2.06 ?
<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>Thanks for your sharing.
HI, may i know how to integrate Spring MVC with hibernate ?
Refer to above Spring tutorials, it’s simply a normal Spring + Hibernate integration.
Hello Mkyong .
can u help me to understand beans lifecycle in spring MVC ?
When beans declared for any controller will be created ?
i’m korean..Not English sorry..
Your Spring3MVC SourceCode..Tomcat7 Test Fail…
But Tomcat6 Test Test Success..
fail issue : Tomcat7 and Maven..???……
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.
Thanks for your kind words and help. f words comment is deleted.
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.
tihs is very good,it’s beautiful!
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.
Noted, will post in soon period.
i passed the interview becoz of your site. almost all emerging technologies discuss here. i owe u a lot.
Congratulation 🙂
if you happen to drop by singapore. drop me an email.
want treat me a coffee? 🙂
yes no problem…
Thank you a lot, your tutorials are awsome. So easy to learn from them.
This is very useful for freshers for better and easily understanding
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
Hi Sriyell,
Thanks for your kind words, and glad to know it help you in some ways.
It is really very use ful site . get good basic Info
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.
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.