Last active
October 11, 2023 20:07
-
-
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!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* <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