Copy and Import Template:
spring_mvc_hibernate
template project.Configure Spring’s Front Controller (DispatcherServlet):
Purpose: Ensures all client requests are intercepted by a centralized dispatcher.
Class: org.springframework.web.servlet.DispatcherServlet
(D.S) – the entry point.
Lifecycle Management: Handled by the Web Container (WC).
Configuration in web.xml
:
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Web Application Startup:
init()
method of D.S:
WebApplicationContext
.servletName-servlet.xml
(e.g., spring-servlet.xml
).WEB-INF
.prefix
: /WEB-INF/views/
suffix
: .jsp
viewClass
: JSTLView
(to enable JSTL actions in JSP).Create Request-Handling Controller (Handler):
@Controller
: Class-level annotation.
@RequestMapping
: Method-level annotation (mandatory) to map HTTP requests (GET, POST, PUT, DELETE, PATCH, etc.).
Method-Level Annotations:
@RequestMapping
// OR
@GetMapping // Equivalent to doGet
// OR
@PostMapping // Equivalent to doPost
Create JSP-Based View Layer:
index.jsp
.WEB-INF/views
.Test the Flow:
Client Request:
<http://host>:port/ctx_path/
index.jsp
).After Clicking a Link in index.jsp
:
<h5>
<a href="test/test1">Test ModelAndView</a>
</h5>
http://host:port/ctx_path/test/test1
TestController.testModelAndView
→ D.S invokes the method.Using ModelAndView
Class:
Purpose: Holds the Logical View Name (LVN) and model attributes.
Constructor:
public ModelAndView(String LVN, String modelAttributeName, Object modelValue)
Flow:
Handler creates and returns a ModelAndView
object to D.S.
D.S extracts LVN → V.R resolves to AVN.
D.S checks for model attributes (if present) → SC adds them to request scope.
Forwards to JSP.
Access in JSP:
${requestScope.attrName}
Using org.springframework.ui.Model
Interface:
Purpose: Acts as a holder for model attributes.
Setup: Add Model
as a method argument in the request-handling method.
Model
map via Dependency Injection (IoC).Programmer’s Task: Add model attributes using:
public Model addAttribute(String attrName, Object attrValue);
Flow:
Objective: List all available restaurants.