14 Essential Spring MVC Controller Tips to Boost Your Java Backend
This article presents fourteen practical techniques for writing Spring MVC controllers, covering annotation‑based definitions, interface implementation, abstract class extension, URL mapping, HTTP method handling, request parameter binding, model‑view returns, redirects, form validation, file uploads, dependency injection, servlet access, and single‑responsibility design, all illustrated with clear Java code examples.
In Spring MVC a controller class handles client requests, delegates business logic, and returns a logical view name that the DispatcherServlet resolves. The following fourteen tips help you write clean, efficient controllers.
1. Use @Controller stereotype
Annotate a class with @Controller to make it a request‑handling component.
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HomeController {
@RequestMapping("/")
public String visitHome() {
return "home";
}
}Enable annotation‑driven scanning in the Spring configuration:
<annotation-driven />
<context:component-scan base-package="net.codejava.spring" />2. Implement the Controller interface
Alternatively, 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");
}
}Configure the bean in spring‑mvc.xml:
<bean name="/main" class="net.codejava.spring.MainController" />3. Extend AbstractController
For easier handling of HTTP methods, sessions, and 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");
}
} <bean name="/big" class="net.codejava.spring.BigController">
<property name="supportedMethods" value="POST" />
</bean>4. Specify URL mapping with @RequestMapping
Use @RequestMapping to map URLs to controller classes or methods.
@RequestMapping("/login")Example of a single‑action controller:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/hello")
public class SingleActionController {
@RequestMapping(method = RequestMethod.GET)
public String sayHello() {
return "hello";
}
}5. Define HTTP methods
Specify the HTTP verb with the method attribute.
@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 with @RequestParam
Retrieve query parameters directly as method arguments.
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String doLogin(@RequestParam String username,
@RequestParam String password) {
// authentication logic
return "Success";
}Optional parameters, default values and map binding are also supported.
7. Return ModelAndView
Return a view name or a ModelAndView object to pass data to the view.
@RequestMapping("/listUsers")
public ModelAndView listUsers() {
List<User> listUser = new ArrayList<>();
ModelAndView mv = new ModelAndView("UserList");
mv.addObject("listUser", listUser);
return mv;
}8. Put objects into the model
Use addObject or a Map to expose data to the view.
modelView.addObject("listUser", listUser);
modelView.addObject("siteName", "CodeJava.net");
modelView.addObject("users", 1200000); @RequestMapping(method = RequestMethod.GET)
public String viewStats(Map<String, Object> model) {
model.put("siteName", "CodeJava.net");
model.put("pageviews", 320000);
return "Stats";
}9. Redirect from a handler
Return a view name prefixed with redirect: to perform a redirect.
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 bindingResult) {
if (bindingResult.hasErrors()) {
// handle errors
} else {
// process registration
}
return "Success";
}
}11. File upload handling
Spring binds uploaded files to CommonsMultipartFile[].
@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 classes
Inject service or DAO beans 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. Access HttpServletRequest and HttpServletResponse
Add the servlet objects 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 by delegating business logic to services and create separate controllers for each domain (e.g., UserController, OrderController, PaymentController).
Controllers should not contain business logic.
One controller per business domain improves maintainability.
These fourteen tips provide a solid foundation for writing effective Spring MVC controllers.
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.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
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.
