Showing posts with label rest. Show all posts
Showing posts with label rest. Show all posts

Thursday, 24 April 2025

Javalin: Hello world application

Prerequisite

Java17

 

Step 1: Create new maven project ‘javalin-hello-world’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

<project 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>javalin-hello-world</artifactId>
	<version>1.0.0</version>

	<properties>
		<packaging>jar</packaging>
		<jdk.version>17</jdk.version>
		<release.version>17</release.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>io.javalin</groupId>
			<artifactId>javalin</artifactId>
			<version>5.3.2</version>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-simple</artifactId>
			<version>2.0.3</version>
		</dependency>

	</dependencies>

	<build>
		<plugins>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.10.1</version>
				<configuration>
					<source>17</source>
					<target>17</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-assembly-plugin</artifactId>
				<version>2.6</version>
				<configuration>
					<descriptorRefs>
						<descriptorRef>jar-with-dependencies</descriptorRef>
					</descriptorRefs>
					<archive>
						<manifest>
							<addClasspath>true</addClasspath>
							<mainClass>com.sample.app.App</mainClass>
						</manifest>
					</archive>
				</configuration>
				<executions>
					<execution>
						<id>assemble-all</id>
						<phase>package</phase>
						<goals>
							<goal>single</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>

 

Step 3: Define main application class.

 

App.java

 

package com.sample.app;

import io.javalin.Javalin;

public class App {
	public static void main(String[] args) {
		Javalin app = Javalin.create(/* config */)
				.get("/", ctx -> ctx.result("Hello World"))
				.start(8080);
	}
}

Total project structure looks like below.


 


Build the project

Navigate to the folder, where pom.xml is located and execute the command ‘mvn package’.

 

Upon successful command execution, you can see a ‘javalin-hello-world-1.0.0-jar-with-dependencies.jar’ file. 

$ls ./target/
archive-tmp
classes
generated-sources
generated-test-sources
javalin-hello-world-1.0.0-jar-with-dependencies.jar
javalin-hello-world-1.0.0.jar
maven-archiver
maven-status
test-classes

 

Run the application

Execute below command to run the application.

 

$java -jar ./target/javalin-hello-world-1.0.0-jar-with-dependencies.jar 
[main] INFO io.javalin.Javalin - Starting Javalin ...
[main] INFO org.eclipse.jetty.server.Server - jetty-11.0.13; built: 2022-12-07T20:47:15.149Z; git: a04bd1ccf844cf9bebc12129335d7493111cbff6; jvm 17.0.5+9-LTS-191
[main] INFO org.eclipse.jetty.server.session.DefaultSessionIdManager - Session workerName=node0
[main] INFO org.eclipse.jetty.server.handler.ContextHandler - Started i.j.j.@29626d54{/,null,AVAILABLE}
[main] INFO org.eclipse.jetty.server.AbstractConnector - Started ServerConnector@1a8a8f7c{HTTP/1.1, (http/1.1)}{0.0.0.0:8080}
[main] INFO org.eclipse.jetty.server.Server - Started Server@b7dd107{STARTING}[11.0.13,sto=0] @393ms
[main] INFO io.javalin.Javalin - 
       __                  ___          ______
      / /___ __   ______ _/ (_)___     / ____/
 __  / / __ `/ | / / __ `/ / / __ \   /___ \
/ /_/ / /_/ /| |/ / /_/ / / / / / /  ____/ /
\____/\__,_/ |___/\__,_/_/_/_/ /_/  /_____/

       https://javalin.io/documentation

[main] INFO io.javalin.Javalin - Listening on http://localhost:8080/
[main] INFO io.javalin.Javalin - You are running Javalin 5.3.2 (released January 22, 2023).
[main] INFO io.javalin.Javalin - Javalin started in 268ms \o/

Open the url ‘http://localhost:8080/’ in browser, you will see below kind of screen.


   

You can download this application from this link.

 

Previous                                                    Next                                                    Home

Wednesday, 5 June 2024

Implementing HTTP 301 URL Redirects in Spring Boot

 

301: Moved Permanently

The 301 status code indicates that the requested resource has been permanently moved to a new URI, and future references should use the provided new URI.

 

Clients which can update links should automatically update references to the old URI with the new ones returned by the server. The detailed steps look like below.

 

Step 1: Client Makes a Request

The client (e.g., a web browser) makes a request to access a resource at a specific URL.

 

Step 2: Server Responds with 301 Status Code

The server receives the request and responds with a 301 Moved Permanently status code. The response includes a Location header that specifies the new URI where the resource has been moved.

 

Step 3: Client Receives the Response

The client processes the server’s response and recognizes the 301 status code, indicating a permanent move.

 

Step 4:  Automatic Redirection

The client automatically follows the Location header and sends a new request to the specified new URI. This ensures the client retrieves the intended resource from its new location.

 

Step 5: Updating References

If the client has link editing capabilities (such as a browser with bookmarks or a web application with stored links), it should update its stored references.

a.   Bookmarks: The client should update any bookmarks that reference the old URI to point to the new URI.

b.   History: The client should update its browsing history to replace the old URI with the new URI.

c.    Internal Links: In the context of a web application, any internal links or references within the application should be updated to reflect the new URI.

 

Step 6: Future Requests

As client caches this old to new URL mapping in its internal cache, for subsequent requests to the old URI, the client will not send to the server for redirection URL, instead the request is automatically redirected to the new URL directly.

 


Sample response looks like below.

HTTP/1.1 301 Moved Permanently
Location: https://www.myanalytics.com
Content-Type: text/html; charset=UTF-8

To prevent unintended actions, automatic redirection of non GET/HEAD requests will be confirmed by the user. For example,

 

1.   A user submits a form (POST request) to http://mybank.com/trasfer-money.

2.   The server responds with a 301 status, redirecting to https://fakebank.com/transfer-money.

3.   If the browser automatically resends the POST request to the new URL without user confirmation, it might lead to unintended data submission or actions.

 

Follow below step-by-step procedure to build a working application.

 

Step 1: Create new maven project “permanent-redirect”.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

<project 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>permanent-redirect</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.2.2</version>
	</parent>

	<dependencies>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springdoc</groupId>
			<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
			<version>2.0.4</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

Step 3: Define RedirectController class.

 

RedirectController.java

package com.sample.app.controller;

import java.net.URI;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class RedirectController {

    @GetMapping("/redirect")
    public ResponseEntity<Void> redirect() {
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(URI.create("https://self-learning-java-tutorial.blogspot.com/"));
        return new ResponseEntity<>(headers, HttpStatus.MOVED_PERMANENTLY);
    }
}

Step 4: Define main application class.

 

App.java

package com.sample.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}

}

Build the Project

Go to the location where pom.xml is located, and execute the command ‘mvn package’. Upon successful completion of the command, you can see a jar file ‘permanent-redirect-0.0.1-SNAPSHOT.jar’ located in target folder.

 

Run the Application

Execute below command to run the application.

java -jar ./target/permanent-redirect-0.0.1-SNAPSHOT.jar

Open the url "http://localhost:8080/api/redirect" in browser, you can see this is redirected to the url "https://self-learning-java-tutorial.blogspot.com". Response header looks like below.


 

Note

A 302 status code indicates a temporary redirect, so browsers do not cache the new URL. Instead, they always send requests to the server, which reads the new URL from the Location response header and redirects to it. For permanent moves, always use a 301 status code. In this case, browsers cache the response, reducing the load on the server.

You can download the application from this link


Previous                                                    Next                                                    Home

Monday, 29 May 2023

Micronaut REST API development tutorial

Micronaut: rest: Hello world application
Micronaut rest: test the hello world application
Micronaut: Customize the running port of the server
Run the Micronaut application on a random port
Micronaut: Execute the code when server completes startup
Micronaut: @PostConstruct: Execute the code post dependency injection
Micronaut: URI path variables
Supported HTTP Methods or verbs in Micronaut
Micronaut: Map multiple uris to a controller method
Micronaut: support non-standard HTTP methods
Micronaut: @Body: Bind the request body to a POJO
Micronaut: @CookieValue: bind a cookie value to method argument
Micronaut: Bind HTTP header to a method parameter
Micronaut: @QueryValue: bind the request query parameter to a method argument
Micronaut: How to make a request parameter optional in Micronaut?
Micronaut: @RequestBean: bind any bindable value to bean object
Micronaut: Upload a file as InputStream
Micronaut: bind all the query parameters to a POJO
Micronaut: bind path variables, headers and query parameters to a POJO
Micronaut: type based binding demo
Micronaut: Inject HttpRequest object
Micronaut: Inject HttpRequest using ServerRequestContext
Micronaut: Send response with status code
Micronaut: Set the http status code using @Status annotation
Micronaut: How to Send a Response Code Only?
How to Specify the MediaType Consumed by a REST API in Micronaut?
Micronaut Request Payload Validation Guide

Previous                                                    Next                                                    Home

Wednesday, 30 November 2022

Using Jersey in a Spring boot application

In this post, I am going to explain how to integrate spring and Jersy in a rest application.

 

Jersey implements JAX-RS specification. JAX-RS document the Java APIs for restful web services.

 

Follow below step-by-step procedure to build the working application.

 

Step 1: Create new maven project ‘spring-jersey-hello-world’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

<project 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>spring-jersey-hello-world</artifactId>
	<version>1.0.0</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.7.5</version>
	</parent>

	<properties>
		<swagger.version>2.1.6</swagger.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<!-- <version.java>17</version.java> -->
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jersey</artifactId>
		</dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

 

Step 3: Define HelloEndpoint interface.

 

HelloEndpoint.java
package com.sample.app.rs;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/hello")
public interface HelloEndpoint {

	@GET
	@Produces(MediaType.TEXT_PLAIN)
	public String sayHello();
}

 

Step 4: Define HelloEndpointImpl class.

 

HelloEndpointImpl.java

package com.sample.app.rs.impl;

import org.springframework.stereotype.Service;

import com.sample.app.rs.HelloEndpoint;

@Service
public class HelloEndpointImpl implements HelloEndpoint{

	public String sayHello() {
		return "Hello World";
	}
}

 

Step 5: Define JerseyConfig class.

 

JerseyConfig.java
package com.sample.app.config;

import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.context.annotation.Configuration;

import com.sample.app.rs.impl.HelloEndpointImpl;

@Configuration
public class JerseyConfig extends ResourceConfig {
	public JerseyConfig() {
		register(HelloEndpointImpl.class);
	}
}

 

Step 6: Define main application class.

 

App.java
package com.sample.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

Total project structure looks like below.


 

Generate the artifact

Navigate to the folder where pom.xml file is located and execute the command ‘mvn package’. Upon command execution, you can see the ‘spring-jersey-hello-world-1.0.0.jar’ file in target folder.

$ ls ./target/
classes
generated-sources
generated-test-sources
maven-archiver
maven-status
spring-jersey-hello-world-1.0.0.jar
spring-jersey-hello-world-1.0.0.jar.original
test-classes

Execute below command to run the application.

java -jar ./target/spring-jersey-hello-world-1.0.0.jar

Open the url ‘http://localhost:8080/hello’ in browser, you will see below kind of screen.

 


You can download this application from this link.

 

Previous                                                 Next                                                 Home