Repository files navigation
Create a Maven web app project
Configure POM file
[pom.xml ]
Change JDK version (Servlet 3.0 require JDK 6+)
spring-webmvc dependency: support Spring MVC and REST
com.fasterxml.jackson.core/jackson-databind dependency: convert JSON
javax.servlet/javax.servlet-api dependency: support Servlet
javax.servlet.jsp/javax.servlet.jsp-api dependency: support JSP (get rid of Eclipse error)
maven-war-plugin plugin: support Maven war plugin
Update Maven project (Alt+F5)
Configure by Java for Spring MVC
[Reference ]
Create a Rest Controller (Service)
[DemoRestController ]
@RestController
@RequestMapping
Add endpoint (method)
Test Spring REST by running project on server and access the created endpoint (url)
Create POJO class
[Student ]
Create Rest Controller with @RestController and @RequestMapping
[StudentRestController ]
Add endpoints to the Controller
@PathVariable: bind URL variable to method parameter
Global Exception Handling
Create custom Error Response class (POJO)
[StudentErrorResponse ]
Create custom Exception extends RuntimeException
[StudentNotFoundException ]
Update REST service to throw exception
[StudentRestController ]
Create a Exception Handler class with @ControllerAdvice (for Global Handling)
[StudentRestExceptionHandler ]
Add a custom exception handler and a generic exception handler with @ExceptionHandler (for Local Handling, put in the Controller)
If src/main/java and src/test/java are not availalbe, go to Build Path -> Order and Export -> Choose JRE and Maven Dependencies.
Default welcome page: index.jsp inside src/main/webapp
REST controller automatically converts between JSON and Java POJO using Jackson
Get the Context Root: ${pageContext.request.contextPath}
Change Servlet 2.3 (generated by archertype webapp) to Servlet 3.0, to use ${pageContext.request.contextPath}
Modify web.xml file in src/main/webapp/WEB-INF
[web.xml ]
Close project and delete it from the workspace (don't delete files on the disk)
Delete .project and .classpath files and .settings directory from the project folder
Re-import project: Import -> Existing Maven Project
Clean the server
[!] Eclipse default browser does not display JSON -> Use external browsers or Postman
Append "?" to end of URL to get reload fresh data
Prefer Global Exception Handling for many controllers using @ControllerAdvice (real-time use of AOP)
Naming convention for API/endpoints: use only entity, not the action. For example: /api/customers/ instead of /api/getCustomers/
Path variable: {var} or :var
Secure Spring REST API
[URL ]
About
Built with Maven, configured by Java code.
Topics
Resources
Stars
Watchers
Forks
You can’t perform that action at this time.