14 Tips for Writing Spring MVC Controllers
This tutorial explains fourteen practical techniques for building Spring MVC controller classes, covering annotation‑based definitions, interface implementation, extending AbstractController, URL mapping, request method handling, parameter binding, model handling, redirects, form validation, file uploads, dependency injection, and best practices such as single‑responsibility and domain‑specific controllers.
Spring MVC is a Java web framework that uses controller classes to process client requests, invoke business logic, and return logical view names. The article provides fourteen concise tips to help developers write clean, maintainable, and functional Spring MVC controllers.
1. Use @Controller annotation
Mark a class with @Controller and map request URLs with @RequestMapping .
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HomeController {
@RequestMapping("/")
public String visitHome() {
return "home";
}
}2. Implement the Controller interface
For a classic approach, let the class implement org.springframework.web.servlet.mvc.Controller and override handleRequest .
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
public class MainController implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
System.out.println("Welcome main");
return new ModelAndView("main");
}
}3. Extend AbstractController
When you need fine‑grained control over HTTP methods, sessions, or caching, extend AbstractController .
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");
}
}4. Specify URL mapping with @RequestMapping
Use @RequestMapping("/login") at class or method level to bind URLs.
5. Define HTTP methods
Set the method attribute to restrict handling to GET, POST, etc.
@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. Bind request parameters
Use @RequestParam to map query or form parameters to method arguments.
@RequestMapping(value="/login", method=RequestMethod.POST)
public String doLogin(@RequestParam String username,
@RequestParam String password) {
// authentication logic
return "Home";
}7. Return ModelAndView or view name
Return a view name directly or a ModelAndView object to pass data to the view.
@RequestMapping("/listUsers")
public ModelAndView listUsers() {
List
listUser = new ArrayList<>();
ModelAndView mv = new ModelAndView("UserList");
mv.addObject("listUser", listUser);
return mv;
}8. Add objects to the model
Use model.addObject(...) or a Map parameter to expose data.
9. Perform redirects
Return "redirect:/login" to send the client to another URL.
10. Handle form submission and validation
Annotate a method with @ModelAttribute and check BindingResult for errors.
@Controller
public class RegistrationController {
@RequestMapping(value="/doRegister", method=RequestMethod.POST)
public String doRegister(@ModelAttribute("userForm") User user,
BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
// handle errors
}
// registration logic
return "Success";
}
}11. File upload
Accept CommonsMultipartFile[] parameters and transfer files.
@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. Autowire business services
Inject service or DAO beans with @Autowired .
@Controller
public class UserController {
@Autowired
private UserDAO userDAO;
// handler methods delegate to userDAO
}13. Access HttpServletRequest/Response
Declare HttpServletRequest and HttpServletResponse as method parameters.
@RequestMapping("/download")
public String doDownloadFile(HttpServletRequest request, HttpServletResponse response) {
// use request/response streams
return "DownloadPage";
}14. Follow the Single Responsibility Principle
Keep controllers thin, delegate business logic to service/DAO layers, and create separate controllers for distinct domains (e.g., UserController, OrderController).
These fourteen tips help developers create Spring MVC controllers that are clear, testable, and aligned with best‑practice architecture.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
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.