* Simple Boot REST application and example

* BAEL-509 - Removed extra duplicate ant matcher

* Example and Unit Tests

* documentation

* BAEL-1085 - changes per PR code review and document review - altered integration to unit test - all's good

* BAEL-1085 - Renamed unit tests and added both to pom.xml

* IntelliJ formatter

* REVERT - Had removed a duplicate ant matcher from BAEL-509 - this was the incorrect process - reverting now, article has been corrected, but will issue a seperate PR for this
This commit is contained in:
Adam InTae Gerard
2017-09-03 09:56:40 +02:00
committed by Zeger Hendrikse
parent b6830cc736
commit 4baaf9f984
18 changed files with 668 additions and 3 deletions
+4
View File
@@ -0,0 +1,4 @@
## Spring REST Angular Example Project
### Relevant Articles:
- [RequestBody and ResponseBody Annotations](http://www.baeldung.com/requestbody-and-responsebody-annotations)
+4 -2
View File
@@ -1,7 +1,7 @@
<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-rest-angular</artifactId>
<name>spring-rest-angular</name>
@@ -95,6 +95,7 @@
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
<include>**/*UnitTest.java</include>
</includes>
</configuration>
</execution>
@@ -113,6 +114,7 @@
<properties>
<guava.version>19.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<start-class>org.baeldung.web.main.Application</start-class>
</properties>
</project>
@@ -0,0 +1,38 @@
package com.baeldung.controllers;
import com.baeldung.services.ExampleService;
import com.baeldung.transfer.ResponseTransfer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import com.baeldung.transfer.LoginForm;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/post")
public class ExamplePostController {
private static Logger log = LoggerFactory.getLogger(ExamplePostController.class);
@Autowired ExampleService exampleService;
@PostMapping("/request")
public ResponseEntity postController(@RequestBody LoginForm loginForm) {
log.debug("POST received - serializing LoginForm: " + loginForm.getPassword() + " " + loginForm.getUsername());
exampleService.fakeAuthenticate(loginForm);
return ResponseEntity.ok(HttpStatus.OK);
}
@PostMapping("/response")
@ResponseBody
public ResponseTransfer postResponseController(@RequestBody LoginForm loginForm) {
log.debug("POST received - serializing LoginForm: " + loginForm.getPassword() + " " + loginForm.getUsername());
return new ResponseTransfer("Thanks For Posting!!!");
}
}
@@ -0,0 +1,14 @@
package com.baeldung.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class ViewController {
@GetMapping("/")
public String welcome() {
return "index";
}
}
@@ -0,0 +1,12 @@
package com.baeldung.services;
import com.baeldung.transfer.LoginForm;
import org.springframework.stereotype.Service;
@Service
public class ExampleService {
public boolean fakeAuthenticate(LoginForm lf) {
return true;
}
}
@@ -0,0 +1,25 @@
package com.baeldung.transfer;
public class LoginForm {
private String username;
private String password;
public LoginForm() {
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
@@ -0,0 +1,18 @@
package com.baeldung.transfer;
public class ResponseTransfer {
private String text;
public ResponseTransfer(String text) {
this.setText(text);
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
@@ -0,0 +1,64 @@
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>
<!DOCTYPE html>
<html ng-app='angularApp'>
<head>
<title>Spring Secured Sockets</title>
<link href="<c:url value="/resources/styles/style.css"/>" rel="stylesheet">
<script src="<c:url value="/resources/vendor/jquery/jquery.min.js" />"></script>
<script src="<c:url value="/resources/vendor/angular/angular.min.js" />"></script>
<script src="<c:url value="/resources/scripts/app.js" />"></script>
<script src="<c:url value="/resources/scripts/factory.js" />"></script>
<script src="<c:url value="/resources/scripts/controllers.js" />"></script>
</head>
<body>
<c:set var="context" scope="session" value="${pageContext.request.contextPath}"/>
<h1>Welcome!</h1>
<br/>
<div class="requestBodyWrapper" ng-controller="requestBody">
<h1>Request Body Controller POST Example</h1>
<form>
<table>
<tr>
<td>User:</td>
<td><input id="requestBodyUserField" type="text" name="username"/></td>
</tr>
<tr>
<td>Password:</td>
<td><input id="requestBodyPasswordField" type="password" name="password"/></td>
</tr>
<tr>
<td>
<button ng-click='postForm("${context}")'>Submit</button>
</td>
</tr>
</table>
</form>
</div>
<div class="responseBodyWrapper" ng-controller="responseBody">
<h1>Response Body Controller POST Example</h1>
<form>
<table>
<tr>
<td>User:</td>
<td><input id="responseBodyUserField" type="text" name="username"/></td>
</tr>
<tr>
<td>Password:</td>
<td><input id="responseBodyPasswordField" type="password" name="password"/></td>
</tr>
<tr>
<td>
<button ng-click='postForm("${context}")'>Submit</button>
</td>
</tr>
</table>
</form>
<h3>{response}</h3>
</div>
</body>
</html>
@@ -0,0 +1,3 @@
'use strict';
var angularApp = angular.module('angularApp', ['ngRoute']);
@@ -0,0 +1,27 @@
angularApp
.controller('requestBody', function ($scope, Form) {
$scope.postForm = function (context) {
var userField = document.getElementById('userField');
var passwordField = document.getElementById('passwordField');
if (userField.value != '' && passwordField.value != '') {
Form.post(context, userField.value,
passwordField.value).then(function (v) {
});
}
};
})
.controller('responseBody', function ($scope, Form) {
$scope.response = "RESPONSEBODY WILL SHOW HERE";
$scope.postForm = function (context) {
var userField = document.getElementById('userField');
var passwordField = document.getElementById('passwordField');
if (userField.value != '' && passwordField.value != '') {
Form.post(context, userField.value,
passwordField.value).then(function (v) {
$scope.response = v;
});
}
};
});
@@ -0,0 +1,17 @@
angularApp
.factory('Form', function ($http, $q) {
return {
post: function (context, username, password) {
var deferred = $q.defer();
$http({
method: 'POST',
url: context + '/authenticate',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({username: username, password: password})
}).then(function (response) {
deferred.resolve(response);
});
return deferred.promise;
}
}
});
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,56 @@
package com.baeldung.controllers;
import com.baeldung.services.ExampleService;
import com.baeldung.transfer.LoginForm;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.baeldung.web.main.Application;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class ExamplePostControllerRequestUnitTest {
MockMvc mockMvc;
@Mock private ExampleService exampleService;
@InjectMocks private ExamplePostController exampleController;
private final String jsonBody = "{\"username\": \"username\", \"password\": \"password\"}";
private LoginForm lf = new LoginForm();
@Before
public void preTest() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders
.standaloneSetup(exampleController)
.build();
lf.setPassword("password");
lf.setUsername("username");
}
@Test
public void requestBodyTest() {
try {
when(exampleService.fakeAuthenticate(lf)).thenReturn(true);
mockMvc
.perform(post("/post/request")
.content(jsonBody)
.contentType("application/json"))
.andDo(print())
.andExpect(status().isOk());
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
@@ -0,0 +1,58 @@
package com.baeldung.controllers;
import com.baeldung.services.ExampleService;
import com.baeldung.transfer.LoginForm;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.baeldung.web.main.Application;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class ExamplePostControllerResponseUnitTest {
MockMvc mockMvc;
@Mock private ExampleService exampleService;
@InjectMocks private ExamplePostController exampleController;
private final String jsonBody = "{\"username\": \"username\", \"password\": \"password\"}";
private LoginForm lf = new LoginForm();
@Before
public void preTest() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders
.standaloneSetup(exampleController)
.build();
lf.setPassword("password");
lf.setUsername("username");
}
@Test
public void requestBodyTest() {
try {
when(exampleService.fakeAuthenticate(lf)).thenReturn(true);
mockMvc
.perform(post("/post/response")
.content(jsonBody)
.contentType("application/json"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().json("{\"text\":\"Thanks For Posting!!!\"}"));
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
-1
View File
@@ -199,7 +199,6 @@
<artifactId>cargo-maven2-plugin</artifactId>
<version>${cargo-maven2-plugin.version}</version>
<configuration>
<wait>true</wait>
<container>
<containerId>tomcat8x</containerId>
<type>embedded</type>