Spring MVC 3.1 without annotations?

2019-02-18 12:12发布

问题:

I'm starting a new project with Spring 3.1, and have been eyeball deep in all the documentation and forum opinions about how to use the @Controller annotation.

I personally dislike using annotations for MVC; I much prefer having all the URLs of a webapp available in one place, using SimpleUrlHandlerMapping.

Also, from much previous work using Spring 2.x, I'm very used to the BaseCommandController heirarchy.

I've always loved Spring because it's empowering without being restricting. Now I find Spring MVC is forcing me to put URLs into the java source, meaning (a) I can't map a controller to several URLs, and (b) to discover what URLs are in use in a webapp, I have to scan through different java source files, which I find impractical.

What is the recommended way of combining @Controller with SimpleUrlHandlerMapping, please ?


Update:

Hi Dave, are you saying you can map multiple URLs like this (altered from petclini.web.ClinicController)?

@RequestMapping({"/vets", "/another"})
public ModelMap vetsHandler() {

If this works then good.

My question still stands though: If I don't want URLs in my java source, how best to map them with @Controller classes?

Regards,

回答1:

Here is a simple set up to support annotation and non-annotated controllers.

Dispatcher servlet configuration xml

<mvc:annotation-driven/>
<bean id="testController" class="com.test.web.TestController"/>
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
  <property name="mappings">
      <value>
      /test=testController
      </value>
  </property>
  <property name="order" value="0"/>
</bean>

A simple URL mapped controller

public class TestController implements Controller {

    @Override
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        PrintWriter responseWriter = response.getWriter();
        responseWriter.write("test");
        responseWriter.flush();
        responseWriter.close();
        return null;
    }
}

The controller for mvc annotation-config

@Controller
@RequestMapping("/home")
public class HomeController {

    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public String dashboard(Model model, HttpServletRequest request) {
        return "home";
    }
}

If you want to use your own handlers for @Controller annotation. you can probably look into ClassPathBeanDefinitionScanner and DefaultAnnotationHandlerMapping.determineUrlsForHandlerMethods.