├── README.md ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── johnathanmsmith │ │ ├── client │ │ ├── Main.java │ │ └── RESTConfiguration.java │ │ └── mvc │ │ └── web │ │ ├── config │ │ └── WebMVCConfiguration.java │ │ ├── controller │ │ ├── IndexController.java │ │ └── JSonController.java │ │ ├── error │ │ └── ErrorHolder.java │ │ ├── exception │ │ └── ResourceNotFoundException.java │ │ └── model │ │ ├── RESTServer.java │ │ └── User.java ├── resources │ ├── application.properties │ └── log4j.xml └── webapp │ ├── WEB-INF │ └── web.xml │ ├── index.jsp │ └── views │ └── helloworld.jsp └── test └── java └── TestHelloWorldWeb.java /README.md: -------------------------------------------------------------------------------- 1 | ### Using Spring RESTTemplate to Post Objects to RESTful web services with Spring's Java Configuration (JavaConfig) style with Maven, JUnit, Log4J 2 | 3 | 4 | In this example I am going to show you how to post data to a RESTful web service in Java using Spring, Spring Java Configuration and more 5 | 6 | 7 | ### Web Service Code 8 | 9 | Let's take a quick look at the Spring MVC Web Service code on the server: 10 | 11 | @Controller 12 | @RequestMapping("/api") 13 | class JSonController 14 | { 15 | 16 | private static final Logger logger = LoggerFactory.getLogger(JSonController.class); 17 | 18 | 19 | 20 | @RequestMapping(value = "/{id}", method = RequestMethod.POST) 21 | @ResponseBody 22 | public User updateCustomer(@PathVariable("id") String id, @RequestBody User user) { 23 | 24 | logger.debug("I am in the controller and got ID: " + id.toString()); 25 | logger.debug("I am in the controller and got user name: " + user.toString()); 26 | 27 | return new User("NEW123", "NEW SMITH"); 28 | } 29 | 30 | 31 | As you can see from the code above the web service is goign to what for a ID and user object to be passed in and then its going to create a new User Object and send it back to the client. 32 | 33 | ### Time For The Client Code 34 | 35 | You can see from the client code below is that we are using Spring RESTTemaple and going to post an User Object to a web server and get one back. 36 | 37 | 38 | @PropertySource("classpath:application.properties") 39 | public class Main 40 | { 41 | 42 | /** 43 | * Setting up logger 44 | */ 45 | private static final Logger LOGGER = getLogger(Main.class); 46 | 47 | 48 | public static void main(String[] args) throws IOException 49 | { 50 | LOGGER.debug("Starting REST Client!!!!"); 51 | 52 | /** 53 | * 54 | * This is going to setup the REST server configuration in the applicationContext 55 | * you can see that I am using the new Spring's Java Configuration style and not some OLD XML file 56 | * 57 | */ 58 | ApplicationContext context = new AnnotationConfigApplicationContext(RESTConfiguration.class); 59 | 60 | /** 61 | * 62 | * We now get a RESTServer bean from the ApplicationContext which has all the data we need to 63 | * log into the REST service with. 64 | * 65 | */ 66 | RESTServer mRESTServer = context.getBean(RESTServer.class); 67 | 68 | 69 | 70 | /** 71 | * 72 | * Setting up data to be sent to REST service 73 | * 74 | */ 75 | Map vars = new HashMap(); 76 | vars.put("id", "JS01"); 77 | 78 | 79 | 80 | 81 | /** 82 | * 83 | * Doing the REST call and then displaying the data/user object 84 | * 85 | */ 86 | 87 | 88 | try 89 | { 90 | 91 | /* 92 | 93 | This is code to post and return a user object 94 | 95 | */ 96 | 97 | RestTemplate rt = new RestTemplate(); 98 | rt.getMessageConverters().add(new MappingJacksonHttpMessageConverter()); 99 | rt.getMessageConverters().add(new StringHttpMessageConverter()); 100 | 101 | String uri = new String("http://" + mRESTServer.getHost() + ":8080/springmvc-resttemplate-test/api/{id}"); 102 | 103 | User u = new User(); 104 | u.setName("Johnathan M Smith"); 105 | u.setUser("JS01"); 106 | 107 | 108 | User returns = rt.postForObject(uri, u, User.class, vars); 109 | LOGGER.debug("User: " + u.toString()); 110 | 111 | } 112 | catch (HttpClientErrorException e) 113 | { 114 | /** 115 | * 116 | * If we get a HTTP Exception display the error message 117 | */ 118 | 119 | LOGGER.error("error: " + e.getResponseBodyAsString()); 120 | 121 | ObjectMapper mapper = new ObjectMapper(); 122 | ErrorHolder eh = mapper.readValue(e.getResponseBodyAsString(), ErrorHolder.class); 123 | 124 | LOGGER.error("error: " + eh.getErrorMessage()); 125 | 126 | } 127 | catch(Exception e) 128 | { 129 | LOGGER.error("error: " + e.getMessage()); 130 | 131 | } 132 | } 133 | 134 | } 135 | 136 | 137 | You can see from the above code how easy it is to use RESTTeample to post data to a web service. 138 | 139 | 140 | 141 | You can see how easy it is to use Spring's Java Configuration (JavaConfig) style and Not XML.. The time of using XML files with Springs is over... 142 | 143 | ### We Can I Get The Sourcec Code 144 | 145 | You can checkout the project from github. 146 | 147 | git clone git@github.com:JohnathanMarkSmith/springmvc-resttemplate-test.git 148 | cd springmvc-resttemplate-test.git 149 | 150 | 151 | If you have any questions please email me at john@johnathanmarksmith.com -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | springmvc-resttemplate-test 5 | springmvc-resttemplate-test 6 | war 7 | 1.0-SNAPSHOT 8 | springmvc-resttemplate-test Maven Webapp 9 | http://maven.apache.org 10 | 11 | 12 | 13 | jsmith 14 | Johnathan Marm Smith 15 | john@johnathanmarksmith.com 16 | 17 | Architect 18 | 19 | -5 20 | 21 | 22 | 23 | 24 | 1.7 25 | 3.2.0.RELEASE 26 | 27 | 1.6.6 28 | 4.1.1.Final 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | com.jayway.jsonpath 37 | json-path 38 | 0.8.1 39 | 40 | 41 | 42 | com.jayway.jsonpath 43 | json-path-assert 44 | 0.8.1 45 | test 46 | 47 | 48 | 49 | 50 | org.springframework 51 | spring-orm 52 | ${springframework-version} 53 | 55 | 56 | 57 | 58 | org.springframework 59 | spring-test 60 | ${springframework-version} 61 | 62 | 63 | 64 | org.springframework 65 | spring-aspects 66 | ${springframework-version} 67 | 68 | 69 | 70 | org.springframework 71 | spring-webmvc 72 | ${springframework-version} 73 | 74 | 75 | commons-logging 76 | commons-logging 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | org.codehaus.jackson 85 | jackson-mapper-asl 86 | 1.9.12 87 | 88 | 89 | 90 | 91 | javax.transaction 92 | jta 93 | 1.1 94 | 95 | 96 | 97 | 98 | cglib 99 | cglib 100 | 2.2.2 101 | 102 | 103 | 104 | 105 | org.aspectj 106 | aspectjtools 107 | 1.6.2 108 | 109 | 110 | 111 | jstl 112 | jstl 113 | 1.2 114 | 115 | 116 | 117 | 118 | 119 | 120 | org.slf4j 121 | slf4j-ext 122 | ${org.slf4j-version} 123 | 124 | 125 | 126 | org.slf4j 127 | slf4j-log4j12 128 | ${org.slf4j-version} 129 | 130 | 131 | 132 | org.slf4j 133 | slf4j-api 134 | ${org.slf4j-version} 135 | 136 | 137 | org.slf4j 138 | jcl-over-slf4j 139 | ${org.slf4j-version} 140 | 141 | 142 | log4j 143 | log4j 144 | 1.2.16 145 | 146 | 147 | 148 | 149 | javax.inject 150 | javax.inject 151 | 1 152 | 153 | 154 | 155 | javax.servlet 156 | servlet-api 157 | 2.5 158 | provided 159 | 160 | 161 | javax.servlet.jsp 162 | jsp-api 163 | 2.1 164 | provided 165 | 166 | 167 | javax.servlet 168 | jstl 169 | 1.2 170 | 171 | 172 | 173 | com.sun.faces 174 | jsf-api 175 | 2.1.7 176 | 177 | 178 | com.sun.faces 179 | jsf-impl 180 | 2.1.7 181 | 182 | 183 | 184 | 185 | 186 | javax.validation 187 | validation-api 188 | 1.0.0.GA 189 | 190 | 191 | 193 | 194 | 195 | org.hibernate 196 | hibernate-entitymanager 197 | ${hibernate.version} 198 | 199 | 200 | 201 | org.hibernate 202 | hibernate-validator 203 | 4.0.2.GA 204 | 205 | 206 | 207 | 208 | junit 209 | junit 210 | 4.7 211 | test 212 | 213 | 214 | org.springframework 215 | spring-test 216 | 3.2.1.RELEASE 217 | 218 | 219 | org.springframework 220 | spring-test 221 | 3.2.1.RELEASE 222 | 223 | 224 | org.hibernate 225 | hibernate 226 | 3.2.6.ga 227 | 228 | 229 | org.apache.httpcomponents 230 | httpclient 231 | 4.2.1 232 | 233 | 234 | commons-httpclient 235 | commons-httpclient 236 | 3.1 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | org.apache.tomcat.maven 247 | tomcat7-maven-plugin 248 | 2.0 249 | 250 | 251 | 252 | springmvc-resttemplate-test 253 | 254 | 255 | 256 | -------------------------------------------------------------------------------- /src/main/java/com/johnathanmsmith/client/Main.java: -------------------------------------------------------------------------------- 1 | package com.johnathanmsmith.client; 2 | 3 | 4 | import com.johnathanmsmith.mvc.web.error.ErrorHolder; 5 | import com.johnathanmsmith.mvc.web.model.RESTServer; 6 | import com.johnathanmsmith.mvc.web.model.User; 7 | import org.apache.log4j.Logger; 8 | import org.codehaus.jackson.map.ObjectMapper; 9 | import org.springframework.context.ApplicationContext; 10 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; 11 | import org.springframework.context.annotation.PropertySource; 12 | import org.springframework.http.converter.StringHttpMessageConverter; 13 | import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter; 14 | import org.springframework.web.client.HttpClientErrorException; 15 | import org.springframework.web.client.RestTemplate; 16 | 17 | import java.io.IOException; 18 | import java.util.HashMap; 19 | import java.util.Map; 20 | 21 | import static org.apache.log4j.Logger.getLogger; 22 | 23 | @PropertySource("classpath:application.properties") 24 | public class Main 25 | { 26 | 27 | /** 28 | * Setting up logger 29 | */ 30 | private static final Logger LOGGER = getLogger(Main.class); 31 | 32 | 33 | public static void main(String[] args) throws IOException 34 | { 35 | LOGGER.debug("Starting REST Client!!!!"); 36 | 37 | /** 38 | * 39 | * This is going to setup the REST server configuration in the applicationContext 40 | * you can see that I am using the new Spring's Java Configuration style and not some OLD XML file 41 | * 42 | */ 43 | ApplicationContext context = new AnnotationConfigApplicationContext(RESTConfiguration.class); 44 | 45 | /** 46 | * 47 | * We now get a RESTServer bean from the ApplicationContext which has all the data we need to 48 | * log into the REST service with. 49 | * 50 | */ 51 | RESTServer mRESTServer = context.getBean(RESTServer.class); 52 | 53 | 54 | 55 | /** 56 | * 57 | * Setting up data to be sent to REST service 58 | * 59 | */ 60 | Map vars = new HashMap(); 61 | vars.put("id", "INID"); 62 | 63 | /** 64 | * 65 | * Doing the REST call and then displaying the data/user object 66 | * 67 | */ 68 | try 69 | { 70 | 71 | /* 72 | 73 | This is code to post and return a user object 74 | 75 | */ 76 | 77 | RestTemplate rt = new RestTemplate(); 78 | rt.getMessageConverters().add(new MappingJacksonHttpMessageConverter()); 79 | rt.getMessageConverters().add(new StringHttpMessageConverter()); 80 | 81 | String uri = new String("http://" + mRESTServer.getHost() + ":8080/springmvc-resttemplate-test/api/{id}"); 82 | 83 | User u = new User(); 84 | u.setName("Johnathan M Smith"); 85 | u.setUser("JMS"); 86 | 87 | 88 | User returns = rt.postForObject(uri, u, User.class, vars); 89 | 90 | LOGGER.debug("User: " + u.toString()); 91 | 92 | } 93 | catch (HttpClientErrorException e) 94 | { 95 | /** 96 | * 97 | * If we get a HTTP Exception display the error message 98 | */ 99 | 100 | LOGGER.error("error: " + e.getResponseBodyAsString()); 101 | 102 | ObjectMapper mapper = new ObjectMapper(); 103 | ErrorHolder eh = mapper.readValue(e.getResponseBodyAsString(), ErrorHolder.class); 104 | 105 | LOGGER.error("error: " + eh.getErrorMessage()); 106 | 107 | } 108 | catch(Exception e) 109 | { 110 | LOGGER.error("error: " + e.getMessage()); 111 | 112 | } 113 | } 114 | 115 | } 116 | -------------------------------------------------------------------------------- /src/main/java/com/johnathanmsmith/client/RESTConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.johnathanmsmith.client; 2 | 3 | import com.johnathanmsmith.mvc.web.model.RESTServer; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.ComponentScan; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.context.annotation.PropertySource; 8 | import org.springframework.core.env.Environment; 9 | import org.springframework.transaction.annotation.EnableTransactionManagement; 10 | 11 | 12 | /** 13 | * Date: 5/24/13 / 8:05 AM 14 | * Author: Johnathan Mark Smith 15 | * Email: john@johnathanmarksmith.com 16 | *

17 | * Comments: 18 | *

19 | * This is a example on how to setup a database with Spring's Java Configuration (JavaConfig) style. 20 | *

21 | * As you can see from the code below this is easy and a lot better then using the old style of XML files. 22 | *

23 | * This is used to read in a properties file and setup access to the RESTServer bean/ 24 | */ 25 | 26 | @Configuration 27 | @EnableTransactionManagement 28 | @ComponentScan(basePackageClasses = {Main.class}) 29 | @PropertySource("classpath:application.properties") 30 | public class RESTConfiguration 31 | { 32 | 33 | @Bean 34 | public RESTServer restServer(Environment env) 35 | { 36 | return new RESTServer(env.getProperty("rest.user"), 37 | env.getProperty("rest.password"), 38 | env.getProperty("rest.host")); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/johnathanmsmith/mvc/web/config/WebMVCConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.johnathanmsmith.mvc.web.config; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.ComponentScan; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.web.servlet.ViewResolver; 9 | import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; 10 | import org.springframework.web.servlet.config.annotation.EnableWebMvc; 11 | import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; 12 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 13 | import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver; 14 | import org.springframework.web.servlet.view.JstlView; 15 | import org.springframework.web.servlet.view.UrlBasedViewResolver; 16 | 17 | import java.util.Properties; 18 | 19 | /** 20 | * Date: 6/5/13 / 7:57 AM 21 | * Author: Johnathan Mark Smith 22 | * Email: john@johnathanmarksmith.com 23 | *

24 | * Comments: 25 | *

26 | * This is a VERY basic Spring Config setup for a web apps 27 | */ 28 | 29 | @Configuration 30 | @EnableWebMvc 31 | @ComponentScan(basePackages = {"com.johnathanmsmith.mvc.web"}) 32 | public class WebMVCConfiguration extends WebMvcConfigurerAdapter 33 | { 34 | 35 | private static final Logger logger = LoggerFactory.getLogger(WebMVCConfiguration.class); 36 | 37 | @Bean 38 | public ViewResolver resolver() 39 | { 40 | UrlBasedViewResolver url = new UrlBasedViewResolver(); 41 | url.setPrefix("/views/"); 42 | url.setViewClass(JstlView.class); 43 | url.setSuffix(".jsp"); 44 | return url; 45 | } 46 | 47 | @Override 48 | public void addResourceHandlers(ResourceHandlerRegistry registry) 49 | { 50 | logger.debug("setting up resource handlers"); 51 | registry.addResourceHandler("/resources/").addResourceLocations("/resources/**"); 52 | } 53 | 54 | @Override 55 | public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) 56 | { 57 | logger.debug("configureDefaultServletHandling"); 58 | configurer.enable(); 59 | } 60 | 61 | @Bean 62 | public SimpleMappingExceptionResolver simpleMappingExceptionResolver() 63 | { 64 | SimpleMappingExceptionResolver b = new SimpleMappingExceptionResolver(); 65 | 66 | Properties mappings = new Properties(); 67 | mappings.put("org.springframework.web.servlet.PageNotFound", "p404"); 68 | mappings.put("org.springframework.dao.DataAccessException", "dataAccessFailure"); 69 | mappings.put("org.springframework.transaction.TransactionException", "dataAccessFailure"); 70 | b.setExceptionMappings(mappings); 71 | return b; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/com/johnathanmsmith/mvc/web/controller/IndexController.java: -------------------------------------------------------------------------------- 1 | package com.johnathanmsmith.mvc.web.controller; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.stereotype.Controller; 6 | import org.springframework.ui.ModelMap; 7 | import org.springframework.web.bind.annotation.PathVariable; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RequestMethod; 10 | 11 | /** 12 | * Date: 6/5/13 / 7:58 AM 13 | * Author: Johnathan Mark Smith 14 | * Email: john@johnathanmarksmith.com 15 | *

16 | * Comments: 17 | *

18 | * This is my basic controller for my web app. 19 | */ 20 | 21 | 22 | @Controller 23 | @RequestMapping("/ask") 24 | class IndexController 25 | { 26 | 27 | private static final Logger logger = LoggerFactory.getLogger(IndexController.class); 28 | 29 | 30 | @RequestMapping(value = "/{name}", method = RequestMethod.GET) 31 | public String getName(@PathVariable String name, ModelMap model) 32 | { 33 | 34 | logger.debug("I am in the controller and got user name: " + name); 35 | 36 | /* 37 | 38 | Taking the REST call param 'name' and setting it to the user 39 | attribute for the output screen 40 | 41 | */ 42 | 43 | model.addAttribute("user", name); 44 | 45 | return "helloworld"; 46 | 47 | } 48 | 49 | @RequestMapping(value = "/", method = RequestMethod.GET) 50 | public String getDisplayDefault(ModelMap model) 51 | { 52 | 53 | /* 54 | 55 | you did not enter a name so the default is going to run 56 | 57 | */ 58 | 59 | 60 | model.addAttribute("user", "Johnathan Mark Smith"); 61 | return "helloworld"; 62 | 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/johnathanmsmith/mvc/web/controller/JSonController.java: -------------------------------------------------------------------------------- 1 | package com.johnathanmsmith.mvc.web.controller; 2 | 3 | import com.johnathanmsmith.mvc.web.error.ErrorHolder; 4 | import com.johnathanmsmith.mvc.web.exception.ResourceNotFoundException; 5 | import com.johnathanmsmith.mvc.web.model.User; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.http.HttpStatus; 9 | import org.springframework.http.ResponseEntity; 10 | import org.springframework.stereotype.Controller; 11 | import org.springframework.ui.ModelMap; 12 | import org.springframework.web.bind.annotation.*; 13 | 14 | /** 15 | * Date: 6/5/13 / 7:58 AM 16 | * Author: Johnathan Mark Smith 17 | * Email: john@johnathanmarksmith.com 18 | *

19 | * Comments: 20 | *

21 | * This is my basic controller for my web app but its going to return JSON data. 22 | */ 23 | 24 | 25 | @Controller 26 | @RequestMapping("/api") 27 | class JSonController 28 | { 29 | 30 | private static final Logger logger = LoggerFactory.getLogger(JSonController.class); 31 | 32 | 33 | 34 | @RequestMapping(value = "/{id}", method = RequestMethod.POST) 35 | @ResponseBody 36 | public User updateCustomer(@PathVariable("id") String id, @RequestBody User user) { 37 | 38 | logger.debug("I am in the controller and got ID: " + id.toString()); 39 | logger.debug("I am in the controller and got user name: " + user.toString()); 40 | 41 | return new User("NEW123", "NEW SMITH"); 42 | } 43 | 44 | @RequestMapping(value = "/{name}", method = RequestMethod.GET) 45 | @ResponseBody 46 | public User getName(@PathVariable String name, ModelMap model) throws ResourceNotFoundException 47 | { 48 | 49 | logger.debug("I am in the controller and got user name: " + name); 50 | 51 | /* 52 | 53 | Simulate a successful lookup for 2 users, this is where your real lookup code would go 54 | 55 | */ 56 | 57 | if ("JohnathanMarkSmith".equals(name)) 58 | { 59 | return new User("Johnathan Mark Smith", name); 60 | } 61 | 62 | if ("Regan".equals(name)) 63 | { 64 | return new User("Regan Smith", name); 65 | } 66 | 67 | throw new ResourceNotFoundException("User Is Not Found"); 68 | } 69 | 70 | @RequestMapping(value = "/", method = RequestMethod.GET) 71 | @ResponseBody 72 | public ResponseEntity getDisplayDefault(ModelMap model) 73 | { 74 | /* 75 | you did not enter a name so the default is going to run 76 | */ 77 | return new ResponseEntity(new User("Johnathan Mark Smith", "JohnathanMarkSmith"), HttpStatus.OK); 78 | 79 | } 80 | 81 | @ExceptionHandler 82 | @ResponseBody 83 | public ResponseEntity handle(ResourceNotFoundException e) 84 | { 85 | logger.warn("The resource was not found", e); 86 | return new ResponseEntity(new ErrorHolder("The resource was not found"), HttpStatus.NOT_FOUND); 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/com/johnathanmsmith/mvc/web/error/ErrorHolder.java: -------------------------------------------------------------------------------- 1 | package com.johnathanmsmith.mvc.web.error; 2 | 3 | /** 4 | * Date: 6/12/13 / 8:48 AM 5 | * Author: Johnathan Mark Smith 6 | * Email: johnathansmith1969@gmail.com 7 | *

8 | * Comments: 9 | *

10 | * This is used to return a error to the client 11 | */ 12 | 13 | public class ErrorHolder 14 | { 15 | 16 | public ErrorHolder(String errorMessage) 17 | { 18 | this.errorMessage = errorMessage; 19 | } 20 | 21 | @Override 22 | public String toString() 23 | { 24 | return "ErrorHolder{" + 25 | "errorMessage='" + errorMessage + '\'' + 26 | '}'; 27 | } 28 | 29 | public String getErrorMessage() 30 | { 31 | return errorMessage; 32 | } 33 | 34 | public void setErrorMessage(String errorMessage) 35 | { 36 | this.errorMessage = errorMessage; 37 | } 38 | 39 | public String errorMessage; 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/johnathanmsmith/mvc/web/exception/ResourceNotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.johnathanmsmith.mvc.web.exception; 2 | 3 | /** 4 | * Date: 6/12/13 / 8:50 AM 5 | * Author: Johnathan Mark Smith 6 | * Email: johnathansmith1969@gmail.com 7 | *

8 | * Comments: 9 | *

10 | * This is used to throw a exception if the resource is not foun 11 | */ 12 | 13 | 14 | public class ResourceNotFoundException extends Exception 15 | { 16 | public ResourceNotFoundException(String message) 17 | { 18 | super(message); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/johnathanmsmith/mvc/web/model/RESTServer.java: -------------------------------------------------------------------------------- 1 | package com.johnathanmsmith.mvc.web.model; 2 | 3 | /** 4 | * Date: 6/7/13 / 8:29 AM 5 | * Author: Johnathan Mark Smith 6 | * Email: john@johnathanmarksmith.com 7 | *

8 | * Comments: 9 | *

10 | * This bean is used to hold the user name, password and host which we need to make the 11 | * call to the REST service. 12 | */ 13 | 14 | public class RESTServer 15 | { 16 | private String user; 17 | private String password; 18 | private String host; 19 | 20 | 21 | public RESTServer(String user, String password, String host) 22 | { 23 | this.user = user; 24 | this.password = password; 25 | this.host = host; 26 | } 27 | 28 | public String getUser() 29 | { 30 | return user; 31 | } 32 | 33 | public String getPassword() 34 | { 35 | return password; 36 | } 37 | 38 | public String getHost() 39 | { 40 | return host; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/johnathanmsmith/mvc/web/model/User.java: -------------------------------------------------------------------------------- 1 | package com.johnathanmsmith.mvc.web.model; 2 | 3 | /** 4 | * Date: 6/6/13 / 10:09 AM 5 | * Author: Johnathan Mark Smith 6 | * Email: john@johnathanmarksmith.com 7 | *

8 | * Comments: 9 | *

10 | * This is the model that is going to be use for return the JSON data 11 | */ 12 | 13 | public class User 14 | { 15 | private String user; 16 | private String name; 17 | 18 | 19 | public User() 20 | { 21 | } 22 | 23 | public User(String user, String name) 24 | { 25 | this.user = user; 26 | this.name = name; 27 | } 28 | 29 | public String getUser() 30 | { 31 | return user; 32 | } 33 | 34 | public void setUser(String user) 35 | { 36 | this.user = user; 37 | } 38 | 39 | public String getName() 40 | { 41 | return name; 42 | } 43 | 44 | public void setName(String name) 45 | { 46 | this.name = name; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | rest.host=127.0.0.1 2 | 3 | rest.user=test 4 | rest.password=test 5 | -------------------------------------------------------------------------------- /src/main/resources/log4j.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | Spring MVC Dispatcher Servlet 9 | org.springframework.web.servlet.DispatcherServlet 10 | 11 | contextClass 12 | org.springframework.web.context.support.AnnotationConfigWebApplicationContext 13 | 14 | 15 | contextConfigLocation 16 | com.johnathanmsmith.mvc.web.config, com.johnathanmsmith.mvc.web.controller 17 | 18 | 1 19 | 20 | 21 | 22 | Spring MVC Dispatcher Servlet 23 | / 24 | 25 | -------------------------------------------------------------------------------- /src/main/webapp/index.jsp: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 14 | 15 | 16 |

Spring-MVC REST Hello World Examples!

17 | 18 |

This is a Example of Spring MVC REST using JavaConfig.

19 | 20 |

This Will Display a Web Page

21 | 22 |

If you want to see if the controller really works just click here (REST call 23 | for JohnathanMarkSmith).

24 | 25 |

If you want to see if the controller really works just click here (REST call for Regan). 26 |

27 | 28 | 29 |

This Will Return JSON

30 | 31 |

If you want to see if the controller really works just click here (REST call 32 | for JohnathanMarkSmith).

33 | 34 |

If you want to see if the controller really works just click here (REST call for Regan). 35 |

36 | 37 | 38 | http://www.JohnathanMarkSmith.com 39 | 40 | 41 | -------------------------------------------------------------------------------- /src/main/webapp/views/helloworld.jsp: -------------------------------------------------------------------------------- 1 | <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> 2 | <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> 3 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 4 | 5 | 6 | 7 | 8 | 17 | 18 | 19 |

Hello World Page from Spring MVC Controller!!

20 | 21 |

22 | Thanks for clicking on the link and making the controller do some work..... 23 | 24 |

25 | This Example was created by ${user} 26 |

27 | http://www.JohnathanMarkSmith.com 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /src/test/java/TestHelloWorldWeb.java: -------------------------------------------------------------------------------- 1 | import com.johnathanmsmith.mvc.web.config.WebMVCConfiguration; 2 | import org.junit.Before; 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.http.MediaType; 7 | import org.springframework.test.context.ContextConfiguration; 8 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 9 | import org.springframework.test.context.web.WebAppConfiguration; 10 | import org.springframework.test.web.servlet.MockMvc; 11 | import org.springframework.test.web.servlet.result.MockMvcResultMatchers; 12 | import org.springframework.test.web.servlet.setup.MockMvcBuilders; 13 | import org.springframework.web.context.WebApplicationContext; 14 | 15 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 16 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; 17 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 18 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; 19 | 20 | /** 21 | * Date: 6/5/13 / 9:05 AM 22 | * Author: Johnathan Mark Smith 23 | * Email: john@johnathanmarksmith.com 24 | *

25 | * Comments: 26 | *

27 | * This class is going to be use for testing my Spring MVC Hello World Web App. 28 | */ 29 | 30 | @RunWith(SpringJUnit4ClassRunner.class) 31 | @ContextConfiguration(classes = {WebMVCConfiguration.class}) 32 | @WebAppConfiguration 33 | public class TestHelloWorldWeb 34 | { 35 | @Autowired 36 | private WebApplicationContext wac; 37 | 38 | private MockMvc mockMvc; 39 | 40 | @Before 41 | public void setup() 42 | { 43 | this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); 44 | } 45 | 46 | @Test 47 | public void getHTML() throws Exception 48 | { 49 | /* 50 | This following code will do 'GET' to the web apps 51 | and check that the return view is "helloworld" 52 | and also that it has a attribute "user" to "JohnathanMarkSmith" 53 | 54 | */ 55 | this.mockMvc.perform(get("/ask/JohnathanMarkSmith") 56 | .accept(MediaType.TEXT_HTML)) 57 | .andExpect(status().isOk()) 58 | .andExpect(view().name("helloworld")) 59 | .andExpect(MockMvcResultMatchers.model().attribute("user", "JohnathanMarkSmith")); 60 | 61 | 62 | } 63 | 64 | @Test 65 | public void getJSON() throws Exception 66 | { 67 | /* 68 | This following code will do 'GET' to the web apps 69 | and also that it has a attribute "user" to "JohnathanMarkSmith" 70 | 71 | */ 72 | this.mockMvc.perform(get("/json/JohnathanMarkSmith") 73 | .accept(MediaType.APPLICATION_JSON)) 74 | .andExpect(status().isOk()) 75 | .andExpect(jsonPath("$.user").value("Johnathan Mark Smith")); 76 | } 77 | } 78 | --------------------------------------------------------------------------------