Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
44 views

Spring MVC

The document discusses the workflow of Spring MVC. It describes how Spring MVC handles requests through the DispatcherServlet. The DispatcherServlet sends requests to controllers, which process the request and return a model to the view. The document also discusses core Spring MVC components like controllers and annotations. It provides examples of writing simple controllers using annotations like @RequestMapping and @RequestParam to handle GET requests and accept query parameters.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

Spring MVC

The document discusses the workflow of Spring MVC. It describes how Spring MVC handles requests through the DispatcherServlet. The DispatcherServlet sends requests to controllers, which process the request and return a model to the view. The document also discusses core Spring MVC components like controllers and annotations. It provides examples of writing simple controllers using annotations like @RequestMapping and @RequestParam to handle GET requests and accept query parameters.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 44

Spring-MVC

Spring-MVC
Spring-MVC
Spring-MVC
Spring-MVC
Work Flow in Spring-MVC
Work Flow in Spring-MVC
Work Flow in Spring-MVC
Work Flow in Spring-MVC
Work Flow in Spring-MVC

A request life cycle


Work Flow in Spring-MVC
Work Flow in Spring-MVC
• The DispatcherServlet’s job is to send the request on to a Spring MVC
controller.
• A controller is a Spring component that processes the request.
• Once an appropriate controller has been chosen, DispatcherServlet sends
the request to the chosen controller.
• The logic performed by a controller often results in some information that
needs to be carried back to the user and displayed in the browser. This
information is referred to as the model.
Core Components of Spring-MVC
Core Components of Spring-MVC
First Spring-MVC Application
First Spring-MVC Application
First Spring-MVC Application
First Spring-MVC Application
First Spring-MVC Application
Next set dependencies in the pom.xml
• Open pom.xml file add the following dependecies under <dependencies>
First Spring-MVC Application
Configure DispatcherServlet
First Spring-MVC Application
First Spring-MVC Application
First Spring-MVC Application
First Spring-MVC Application
First Spring-MVC Application
Spring Annotations
Spring Annotations
Spring MVC Annotations
Spring MVC Application-2
Spring MVC Application-2
Spring MVC Application-2
Spring MVC Application-2
Writing a simple controller
• In Spring MVC, controllers are just classes with methods that are annotated
with @RequestMapping to declare the kind of requests they’ll handle.
• Let us take a controller class that handles requests for / and renders the
application’s home page. HomeController, shown in the following listing, is an
example of what might be the simplest possible Spring MVC controller class.
package spittr.web;
import static org.springframework.web.bind.annotation.RequestMethod.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
Declared to be a controller
@Controller
public class HomeController {

@RequestMapping(value="/", method=GET) Handle GET requests for /


public String home() {
return "home"; View name is home
}
}
Writing a simple controller

• Because HomeController is annotated with @Controller, the component


scanner will automatically pick up HomeController and declare it as a bean in
the Spring application context.
• HomeController’s only method, the home() method, is annotated with
@RequestMapping, whenever an HTTP GET request comes in for /, the
home() method will be called. It returns a String value of “home”. This String
will be interpreted by Spring MVC as the name of the view that will be
rendered.
• DispatcherServlet will ask the view resolver to resolve this logical view name
into an actual view.
• The view name “home” will be resolved as a JSP at /WEB-INF/views/home.jsp.
• Keep the Spittr application’s home page
Writing a simple controller
• Spittr home page, defined as a simple JSP: It has welcomes message and two
links: one to view a Spittle list and another to register with the application.

package spittr.web;
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
<title>Spittr</title>
<link rel="stylesheet"
type="text/css"
href="<c:url value="/resources/style.css" />" >
</head>
<body>
<h1>Welcome to Spittr</h1>
<a href="<c:url value="/spittles" />">Spittles</a> |
<a href="<c:url value="/spitter/register" />">Register</a>
</body>
</html>
Writing a simple controller
Testing the controller- HomeControllerTest: tests HomeController
• It calls home() directly and asserts that a String containing the value “home” is
returned. it only tests what happens in the home() method.

import static org.junit.Assert.assertEquals;


import org.junit.Test;
import spittr.web.HomeController;
public class HomeControllerTest {
@Test
public void testHomePage() throws Exception {
HomeController controller = new HomeController();
assertEquals("home", controller.home());
}
}
Writing a simple controller
Testing the controller- HomeControllerTest: tests HomeController
• To demonstrate proper testing of a Spring MVC controller, rewrite Home-
ControllerTest to take advantage of the new Spring MVC testing features. The following
listing shows the new HomeControllerTest.

package spittr.web;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;
import org.junit.Test;
import org.springframework.test.web.servlet.MockMvc;
import spittr.web.HomeController;

public class HomeControllerTest {


@Test
public void testHomePage() throws Exception {
HomeController controller = new HomeController(); Set up MockMvc
MockMvc mockMvc = standaloneSetup(controller).build();
Perform GET /
mockMvc.perform(get("/"))
.andExpect(view().name("home"));
Expect home view
}
Accepting request input
• Spring MVC provides several ways that a client can pass data into a controller’s
handler method. These include
• Query parameters(Request Parameters)
• Form parameters
• Path variables
Query Parameter in Spring MVC

Query Parameter
http://internet.org/process-homepage?number1=23&number2=12
• So in the above URL, the query string is whatever follows the question
mark sign (“?”) i.e (“number1=23&number2=12”) this part. And
“number1=23”, “number2=12” are Query Parameters which are joined by
a connector “&”.
http://internet.org?title=Query_string&action=edit
• In the above URL, the query string is “title=Query_string&action=edit” this
part. And “title=Query_string”, “action=edit” are Query Parameters which
are joined
Query Parameter in Spring MVC
Query Parameter
• Using @RequestParam to get Query parameters
• In a Spring MVC application, you can use the @RequestParam annotation
to accept query parameters in Controller's handler methods.

For examples, suppose you have a web application that returns details of
orders and trades, and you have the following URLs:
• http://localhost:8080/eportal/orders?id=1001
• To accept the query parameters in the above URLs, you can use the
following code in the Spring MVC controller:

@RequestMapping("/orders")
public String showOrderDetails(@RequestParam("id") String orderId, Model model)
{ model.addAttribute("orderId", orderId); return "orderDetails“;
Query Parameter in Spring MVC
Query Parameter
• Using @RequestParam to get Query parameters
• If the name of the query parameter is the same as the name of the variable in the
handler's @RequestParam annotated argument then you can simply
use @RequestParam without specifying the name of a query parameter, Spring will
automatically derive the value

URL: http://localhost:8080/eportal/trades? tradeId=2001

@RequestMapping("/trades")
public String showTradeDetails(@RequestParam String tradeId, Model model)
{ model.addAttribute("tradeId", tradeId); return "tradeDetails"; }

we have just annotated the method parameter tradeId with @RequestParam without
specifying the name of the query parameter because the name of both request
parameter and argument name is the same, i.e., "tradeId“ .
Path parameters in Spring MVC
2. Using @PathVariable annotation to extract values from URI

You can use Spring MVC's @PathVaraible annotation to extract any value
which is embedded in the URL itself. Spring calls it a URI template,
where @PathVariable is used to obtain some placeholders from the URI itself.

URL: http://localhost:8080/book/9783827319333
Now, to extract the value of ISBN number from the URI in your Spring MVC
Controller's handler method, you can use @PathVariable annotation as
shown in the following code:

@RequestMapping(value="/book/{ISBN}", method= RequestMethod.GET)


public String showBookDetails(@PathVariable("ISBN") String id, Model model)
{ model.addAttribute("ISBN", id);
return "bookDetails"; }
Path parameters in Spring MVC
2. Using @PathVariable annotation to extract values from URI

Similar to @RequestParameter annotation, you also can also omit the value
attribute in @PathVariable annotation, if the name of the path variable's
placeholder in the @RequestMapping annotation is the same as the variable
name in the handler method's @PathVariable annotated parameter

URL: http://localhost:8080/book/9783827319333

@RequestMapping(value="/book/{ISBN}", method= RequestMethod.GET)


public String showBookDetails(@PathVariable String ISBN, Model model)
{ model.addAttribute("ISBN", ISBN);
return "bookDetails"; }
Processing forms
3. Using Form parameters :

• Spring MVC controllers are well-suited for form processing as well as


serving content.

You might also like