Skip to content

Instantly share code, notes, and snippets.

@joshlong
Last active October 11, 2023 20:07
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save joshlong/6431608 to your computer and use it in GitHub Desktop.
Save joshlong/6431608 to your computer and use it in GitHub Desktop.
This is a complete working Spring MVC REST application. The only thing unspecified are the imports and the Maven pom.xml. Deploy this class as a .war using Spring MVC 3.2.x (and, specifically, the spring-webmvc library) and you're done!
/**
* <p>This will be picked up in a Servlet 3 environment like Apache Tomcat 7.
*
* <p>This replaces <code>web.xml</code>.
*
*/
public class MvcRestApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override protected Class<?> [] getRootConfigClasses() {
return new Class<?>[]{};
}
@Override protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{ RestConfiguration.class };
}
@Override protected String[] getServletMappings(){ return new String[]{"/"}; }
}
/**
* Installs Spring MVC and all the required support for JSON assuming
* Jackson's on the CLASSPATH
*/
@EnableWebMvc
@ComponentScan
@Configuration
class RestConfiguration {
// that's all!
}
/**
* A simple Spring MVC REST controller. The returned value (Customer) will
* be converted into JSON if the client signals that it can read JSON (using the
* <CODE>ACCEPT</CODE> header.)
*/
@Controller
class StatusController {
@RequestMapping(value= "/customers/{customerId}", method= RequestMethod.GET)
public @ResponseBody Customer loadCustomer(@PathVariable long customerId ) {
// return a POJO Customer somehow (perhaps look it up in a database?)
return someCustomer ;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment