RESTful web services provides http endpoints. Http endpoints can have functions like POST, PUT, DELETE and GET. Http methods can be mapped to operations like create, update, retrieve and delete. For example we can have Http GET endpoint to retrieve user information and http POST to create customer. PUT can be for update and DELETE for deleting customer.
Spring Boot provides very simple way to create Restful Webservice with embedded tomcat or jetty server. Below mentioned is dependency to be added for creating Restful WebService using Spring Boot.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
We also require to add parent element inside pom.xml file as mentioned below.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.1.10.RELEASE</version>
</parent>
Now, RestEndpoint can be created by annotating class with @RestController as shown below.
@RestController
@RequestMapping("/users")
public class UserController {
.....
}
@RestController will facilitate to create http endpoints for each function defined in UserController class. @RequestMapping will map /users URL to functions.
Functions can be declared as shown in below to create Http POST method.
@RequestMapping(method = RequestMethod.POST)
public CreateUserResponse createUser(@RequestBody User user) throws Exception {
validateUser(user);
String token = userService.createUser(user);
return new CreateUserResponse(token);
}
Here, method is annotated with POST method type and RequestMapping e.g. http://<host-name>:port/users ensure that it will call createUser function. @RequestBody will marshal json text to Java Object. For e.g. json request like {"firstName":"steven","lastName":"sharma"} will create java object as described below. Marshalling / Unmarshalling operation are provided by Jackson API.
class User {
private String firstName;
private String lastName;
// getter and setter
}
To accept parameters from query string @RequestParam is used. so below function will be mapped to URL http://<localhost>:port/users/=?firstName=myname
@RequestMapping(method = RequestMethod.GET)
public List<User> searchUser(@RequestParam("firstName") String firstName) throws Exception {
return null;
}
To accept parameter as a part of URL path for e.g. URL http://<localhost>:port/users/firstName/myname
@RequestMapping(value = "/firstName/{name}",method = RequestMethod.GET)
public List<User> searchUser(@PathVariable("name") String name) throws Exception {
return userService.getUsersByFirstName(name);
}
Main function of the method is defined below.
@ComponentScan("basepackage")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
mvn clean package
java -jar project.jar
Above commands will start tomcat as embedded server and generate rest endpoints as per discussed above.
Changing server port :
Configuration parameters can be passed through yml file which is part of resource directory, To change port of tomcat which is embedded in spring-boot project. Add application.yml file in resources directory and add below mentioned configuration parameters, to ensure that rest endpoint will have port no. 9191 associated with.
server:
port: 9191
Enabling Https :
Generating self signed certificate and private key using below mentioned command
keytool -genkey -alias aliasName -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore myapp.p12 -validity 365
This will create myapp.p12 file. Create Spring Bean as shown below from configuration file.
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() throws FileNotFoundException {
final String absoluteKeystoreFile = ResourceUtils.getFile(keyStore).getAbsolutePath();
final TomcatConnectorCustomizer customizer = new GruberTomcatConnectionCustomizer(
absoluteKeystoreFile, "changeit", "PKCS12", "gruber",tomcatPort);
return new EmbeddedServletContainerCustomizer() {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
if(container instanceof TomcatEmbeddedServletContainerFactory) {
TomcatEmbeddedServletContainerFactory containerFactory = (TomcatEmbeddedServletContainerFactory) container;
containerFactory.addConnectorCustomizers(customizer);
}
};
};
}
Create below mentioned class
public class GruberTomcatConnectionCustomizer implements TomcatConnectorCustomizer {
private String absoluteKeystoreFile;
private String keystorePassword;
private String keystoreType;
private String keystoreAlias;
private int tomcatPort;
public GruberTomcatConnectionCustomizer(String absoluteKeystoreFile,
String keystorePassword, String keystoreType, String keystoreAlias, int tomcatPort) {
this.absoluteKeystoreFile = absoluteKeystoreFile;
this.keystorePassword = keystorePassword;
this.keystoreType = keystoreType;
this.keystoreAlias = keystoreAlias.toLowerCase();
this.tomcatPort = tomcatPort;
}
@Override
public void customize(Connector connector) {
connector.setPort(tomcatPort);
connector.setSecure(true);
connector.setScheme("https");
connector.setAttribute("SSLEnabled", true);
connector.setAttribute("sslProtocol", "TLS");
connector.setAttribute("protocol", "org.apache.coyote.http11.Http11Protocol");
connector.setAttribute("clientAuth", false);
connector.setAttribute("keystoreFile", absoluteKeystoreFile);
connector.setAttribute("keystoreType", keystoreType);
connector.setAttribute("keystorePass", keystorePassword);
connector.setAttribute("keystoreAlias", keystoreAlias);
connector.setAttribute("keyPass", keystorePassword);
}
}
This configuration will start tomcat on secured port.
Here is configuration to be placed on application.yml file
tomcat-port: 7443
In case if you want to run tomcat with https and self-signed
https://looksok.wordpress.com/2014/11/16/configure-sslhttps-on-tomcat-with-self-signed-certificate/
Spring Boot provides very simple way to create Restful Webservice with embedded tomcat or jetty server. Below mentioned is dependency to be added for creating Restful WebService using Spring Boot.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
We also require to add parent element inside pom.xml file as mentioned below.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.1.10.RELEASE</version>
</parent>
Now, RestEndpoint can be created by annotating class with @RestController as shown below.
@RestController
@RequestMapping("/users")
public class UserController {
.....
}
@RestController will facilitate to create http endpoints for each function defined in UserController class. @RequestMapping will map /users URL to functions.
Functions can be declared as shown in below to create Http POST method.
@RequestMapping(method = RequestMethod.POST)
public CreateUserResponse createUser(@RequestBody User user) throws Exception {
validateUser(user);
String token = userService.createUser(user);
return new CreateUserResponse(token);
}
Here, method is annotated with POST method type and RequestMapping e.g. http://<host-name>:port/users ensure that it will call createUser function. @RequestBody will marshal json text to Java Object. For e.g. json request like {"firstName":"steven","lastName":"sharma"} will create java object as described below. Marshalling / Unmarshalling operation are provided by Jackson API.
class User {
private String firstName;
private String lastName;
// getter and setter
}
To accept parameters from query string @RequestParam is used. so below function will be mapped to URL http://<localhost>:port/users/=?firstName=myname
@RequestMapping(method = RequestMethod.GET)
public List<User> searchUser(@RequestParam("firstName") String firstName) throws Exception {
return null;
}
To accept parameter as a part of URL path for e.g. URL http://<localhost>:port/users/firstName/myname
@RequestMapping(value = "/firstName/{name}",method = RequestMethod.GET)
public List<User> searchUser(@PathVariable("name") String name) throws Exception {
return userService.getUsersByFirstName(name);
}
Main function of the method is defined below.
@ComponentScan("basepackage")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
mvn clean package
java -jar project.jar
Above commands will start tomcat as embedded server and generate rest endpoints as per discussed above.
Changing server port :
Configuration parameters can be passed through yml file which is part of resource directory, To change port of tomcat which is embedded in spring-boot project. Add application.yml file in resources directory and add below mentioned configuration parameters, to ensure that rest endpoint will have port no. 9191 associated with.
server:
port: 9191
Enabling Https :
Generating self signed certificate and private key using below mentioned command
keytool -genkey -alias aliasName -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore myapp.p12 -validity 365
This will create myapp.p12 file. Create Spring Bean as shown below from configuration file.
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() throws FileNotFoundException {
final String absoluteKeystoreFile = ResourceUtils.getFile(keyStore).getAbsolutePath();
final TomcatConnectorCustomizer customizer = new GruberTomcatConnectionCustomizer(
absoluteKeystoreFile, "changeit", "PKCS12", "gruber",tomcatPort);
return new EmbeddedServletContainerCustomizer() {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
if(container instanceof TomcatEmbeddedServletContainerFactory) {
TomcatEmbeddedServletContainerFactory containerFactory = (TomcatEmbeddedServletContainerFactory) container;
containerFactory.addConnectorCustomizers(customizer);
}
};
};
}
Create below mentioned class
public class GruberTomcatConnectionCustomizer implements TomcatConnectorCustomizer {
private String absoluteKeystoreFile;
private String keystorePassword;
private String keystoreType;
private String keystoreAlias;
private int tomcatPort;
public GruberTomcatConnectionCustomizer(String absoluteKeystoreFile,
String keystorePassword, String keystoreType, String keystoreAlias, int tomcatPort) {
this.absoluteKeystoreFile = absoluteKeystoreFile;
this.keystorePassword = keystorePassword;
this.keystoreType = keystoreType;
this.keystoreAlias = keystoreAlias.toLowerCase();
this.tomcatPort = tomcatPort;
}
@Override
public void customize(Connector connector) {
connector.setPort(tomcatPort);
connector.setSecure(true);
connector.setScheme("https");
connector.setAttribute("SSLEnabled", true);
connector.setAttribute("sslProtocol", "TLS");
connector.setAttribute("protocol", "org.apache.coyote.http11.Http11Protocol");
connector.setAttribute("clientAuth", false);
connector.setAttribute("keystoreFile", absoluteKeystoreFile);
connector.setAttribute("keystoreType", keystoreType);
connector.setAttribute("keystorePass", keystorePassword);
connector.setAttribute("keystoreAlias", keystoreAlias);
connector.setAttribute("keyPass", keystorePassword);
}
}
This configuration will start tomcat on secured port.
Here is configuration to be placed on application.yml file
tomcat-port: 7443
In case if you want to run tomcat with https and self-signed
https://looksok.wordpress.com/2014/11/16/configure-sslhttps-on-tomcat-with-self-signed-certificate/
No comments:
Post a Comment