简体   繁体   中英

How to Add a Controller in Spring MVC 3?

I have created a new Spring MVC 3 project using NetBean. But there is no option of adding a new controller in the IDE.

Well adding a Controller is as simple as adding a class annotated with

@Controller

And specifying the package to be scanned from applicationContext.xml which in turn is specified in the web.xml. Something like this:

    <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/spring/appServlet/applicationContext.xml
    </param-value>
</context-param>

in web.xml

Then in /WEB-INF/spring/appServlet/applicationContext.xml :

<context:component-scan base-package="your.package" />

Of course you need the actual schema in your applicationContext.xml

xmlns:context="http://www.springframework.org/schema/context"

And under schema location:

http://www.springframework.org/schema/context/spring-context-3.0.xsd

And then a class :

package your.package
.....
@Controller
MyController{

   .....

If you are using an annotation driven implementation of Spring you don't need to do anything special. Create a standard Java class inside the package that Spring is configured to scan. Then annotate the class with @Controller then create your method(s) and mappings using @RequestMapping .

In its simplest form a controller would be something like:

@Controller
public class MyClass {

  @RequestMapping("/myUrlMapping.do")
  public ModelAndView myMethod() {
    return new ModelAndView("myView");
  }
}

This assumes you already have Spring configured correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM