Show List
Handling request and response with Controllers
In Spring MVC, Controllers are responsible for handling incoming HTTP requests and returning a response to the client. The process of handling requests and returning a response is referred to as request handling.
There are two main types of controllers in Spring MVC:
- Annotation-based controllers: These are the most commonly used controllers in Spring MVC. They use annotations to define the request mapping and specify which methods should handle which requests.
Example:
@Controllerpublic class MyController { public String handleRequest(Model model) { model.addAttribute("message", "Hello, World!"); return "hello"; } }
- Implementing the Controller interface: You can also create a controller by implementing the
org.springframework.web.servlet.mvc.Controller
interface and defining ahandleRequest
method.
Example:
public class MyController implements Controller {
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView mav = new ModelAndView();
mav.addObject("message", "Hello, World!");
mav.setViewName("hello");
return mav;
}
}
In both of the above examples, the
handleRequest
method is handling an incoming request, adding data to a model, and returning a view name (or a complete view) to be rendered.Leave a Comment