Master Spring MVC Controllers: From @Controller Basics to Advanced Techniques
This guide walks through creating Spring MVC controllers using @Controller, implementing the Controller interface, extending AbstractController, mapping URLs and HTTP methods, handling request parameters, returning ModelAndView, performing redirects, processing forms, uploading files, autowiring services, and adhering to the single‑responsibility principle.
1. Using @Controller construction
The simplest way to create a controller that can handle one or more requests is to annotate a class with @Controller. Example:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HomeController {
@RequestMapping("/")
public String visitHome() {
return "home";
}
}The visitHome() method redirects to the view named home. Note that @Controller works only when annotation‑driven configuration is enabled ( <annotation-driven />) and the component‑scan base package is set.
2. Implementing the Controller interface
Another classic approach is to let a class implement the Controller interface and override handleRequest(). The request URL pattern is defined in the Spring XML configuration:
<bean name="/main" class="net.codejava.spring.MainController" />This method can handle only a single URL.
3. Extending AbstractController
Extending AbstractController simplifies handling supported HTTP methods, sessions, and caching. Example:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class BigController extends AbstractController {
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println("You're big!");
return new ModelAndView("big");
}
}Bean configuration can specify supported methods, e.g., POST.
4. Specifying URL mapping for handler methods
Use @RequestMapping to map URLs to controller methods or classes, e.g.:
@RequestMapping("/login")
public String viewLogin() { return "LoginForm"; }Multiple URLs can be mapped with an array syntax.
5. Specifying HTTP request methods
Set the method attribute of @RequestMapping to restrict handling to GET, POST, etc. Example:
@Controller
public class LoginController {
@RequestMapping(value="/login", method=RequestMethod.GET)
public String viewLogin() { return "LoginForm"; }
@RequestMapping(value="/login", method=RequestMethod.POST)
public String doLogin() { return "Home"; }
}6. Mapping request parameters to handler methods
Use @RequestParam to bind request parameters to method arguments, with optional required and defaultValue attributes. Example:
@RequestMapping(value="/login", method=RequestMethod.POST)
public String doLogin(@RequestParam String username, @RequestParam String password) { ... }Parameters can also be collected into a Map<String,String>.
7. Returning model and view
Handler methods can return a view name as a String or a ModelAndView object. Example returning a ModelAndView with data:
@RequestMapping("/listUsers")
public ModelAndView listUsers() {
List<User> listUser = new ArrayList<>(); // fetch from DAO
ModelAndView mv = new ModelAndView("UserList");
mv.addObject("listUser", listUser);
return mv;
}The same can be achieved by declaring ModelAndView as a method parameter.
8. Adding objects to the model
Use addObject() on ModelAndView or put entries into a Map<String,Object> to pass data to the view.
modelView.addObject("siteName", "CodeJava.net");
model.put("pageviews", 320000);9. Redirecting from handler methods
Return a view name prefixed with redirect:/ to perform a redirect, e.g.:
if (!isLogin) {
return new ModelAndView("redirect:/login");
}10. Form submission and validation
Bind form fields with @ModelAttribute and validate using BindingResult:
@Controller
public class RegistrationController {
@RequestMapping(value="/doRegister", method=RequestMethod.POST)
public String doRegister(@ModelAttribute("userForm") User user, BindingResult result) {
if (result.hasErrors()) {
// handle errors
} else {
// process registration
}
return "Success";
}
}11. Handling file uploads
Accept uploaded files as CommonsMultipartFile[] and transfer them to the server:
@RequestMapping(value="/uploadFiles", method=RequestMethod.POST)
public String handleFileUpload(@RequestParam CommonsMultipartFile[] fileUpload) throws Exception {
for (CommonsMultipartFile aFile : fileUpload) {
aFile.transferTo(new File(aFile.getOriginalFilename()));
}
return "Success";
}12. Autowiring business classes
Inject service or DAO beans into controllers with @Autowired:
@Controller
public class UserController {
@Autowired
private UserDAO userDAO;
public String listUser() { userDAO.list(); }
public String saveUser(User user) { userDAO.save(user); }
public String deleteUser(User user) { userDAO.delete(user); }
public String getUser(int userId) { userDAO.get(userId); }
}13. Accessing HttpServletRequest and HttpServletResponse
Simply add the request or response objects as method parameters; Spring will inject them automatically.
@RequestMapping("/download")
public String doDownloadFile(HttpServletRequest request, HttpServletResponse response) {
// use request/response
return "DownloadPage";
}14. Following the Single Responsibility Principle
Controllers should delegate business logic to service/DAO layers, keeping the controller focused on request handling and workflow orchestration.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
