14 Tips for Writing Spring MVC Controllers

This article presents fourteen practical techniques for creating Spring MVC controller classes, covering annotation-based definitions, interface implementation, extending abstract controllers, URL mapping, HTTP method specification, request parameter binding, model and view handling, redirects, form validation, file uploads, dependency injection, request/response access, and adherence to the single‑responsibility principle.

IT Xianyu
IT Xianyu
IT Xianyu
14 Tips for Writing Spring MVC Controllers

1. Use @Controller Annotation

Declare a controller class with @Controller and map request URLs using @RequestMapping. The handler method returns a view name, e.g., "home".

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HomeController {
    @RequestMapping("/")
    public String visitHome() {
        return "home";
    }
}

2. Implement Controller Interface

Implement org.springframework.web.servlet.mvc.Controller and override handleRequest. This approach handles a single URL pattern defined in the Spring context.

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

Extend AbstractController to gain support for HTTP methods, session handling, and caching. Override handleRequestInternal and configure bean properties such as supportedMethods.

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. Multiple URLs can be mapped with an array syntax.

@RequestMapping({"/hello", "/hi", "/greetings"})
public String sayHello() { ... }

5. Define HTTP Methods

Set the method attribute of @RequestMapping to restrict handlers to GET, POST, etc.

@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 bind query or form parameters to method arguments, with optional required and defaultValue attributes.

@RequestMapping(value="/login", method=RequestMethod.POST)
public String doLogin(@RequestParam String username, @RequestParam String password) { ... }

7. Return ModelAndView

Handlers can return a view name as a String 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. Add Objects to the Model

Use model.addObject(...) or a Map<String,Object> parameter to place data into the model.

modelView.addObject("listUser", listUser);
model.put("siteName", "CodeJava.net");

9. Perform Redirects

Return a view name prefixed with redirect:/ to send the client to another URL.

return new ModelAndView("redirect:/login");

10. Handle Form Submission and Validation

Annotate a method with @ModelAttribute to bind form fields to an object and use BindingResult for validation errors.

@Controller
public class RegistrationController {
    @RequestMapping(value="/doRegister", method=RequestMethod.POST)
    public String doRegister(@ModelAttribute("userForm") User user, BindingResult result) {
        if (result.hasErrors()) { /* handle errors */ }
        return "Success";
    }
}

11. File Uploads

Spring binds uploaded files to CommonsMultipartFile[]. Iterate over the array and store each file.

@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 into controllers with @Autowired and delegate business logic.

@Controller
public class UserController {
    @Autowired
    private UserDAO userDAO;
    public String listUser() { userDAO.list(); }
    public String saveUser(User user) { userDAO.save(user); }
}

13. Access HttpServletRequest/Response

Add HttpServletRequest and HttpServletResponse parameters to a handler to work with low‑level servlet APIs.

@RequestMapping("/download")
public String doDownloadFile(HttpServletRequest request, HttpServletResponse response) {
    // use request/response streams
    return "DownloadPage";
}

14. Follow Single‑Responsibility Principle

Keep controllers thin by delegating business work to services, and create separate controllers for distinct domains (e.g., UserController, OrderController).

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaWeb Developmentannotationsdependency-injectionControllerrestSpring MVC
IT Xianyu
Written by

IT Xianyu

We share common IT technologies (Java, Web, SQL, etc.) and practical applications of emerging software development techniques. New articles are posted daily. Follow IT Xianyu to stay ahead in tech. The IT Xianyu series is being regularly updated.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.