Get current logged in username in Spring Security

In this article, we will show you three ways to get the current logged in username in Spring Security. 1. SecurityContextHolder + Authentication.getName() import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class LoginController { @RequestMapping(value="/login", method = RequestMethod.GET) public String printUser(ModelMap model) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String name …

Read more

Display custom error message in Spring Security

In Spring Security, when authentication is failed, following predefined error messages will be displayed : Spring display : Bad credentials In this article, we show you how to override above error message and display your custom error message. For example, Spring display : Bad credentials You want override it with this message : Invalid username …

Read more

Spring Security hello world example

In this tutorial, we will show you how to integrate Spring Security with a Spring MVC web application to secure a URL access. After implementing Spring Security, to access the content of an “admin” page, users need to key in the correct “username” and “password”. Technologies used : Spring 3.2.8.RELEASE Spring Security 3.2.3.RELEASE Eclipse 4.2 …

Read more

How to loop ArrayList in Java

No nonsense, four ways to loop ArrayList in Java For loop For loop (Advance) While loop Iterator loop package com.mkyong.core; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ArrayListLoopingExample { public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("Text 1"); list.add("Text 2"); list.add("Text 3"); System.out.println("#1 normal for loop"); for (int i = …

Read more

Convert JSON string to Map using Jackson

This article uses the Jackson framework to parse JSON strings to a Map in Java. Table of contents: 1. Download Jackson 2. Convert JSON string to Map 3. Convert Map to JSON string 4. Download Source Code 5. References P.S Tested with Jackson 2.17.0 1. Download Jackson Simply declare jackson-databind in the pom.xml, and it …

Read more

Read and write JSON using JSON.simple

This article shows how to read and write JSON using JSON.simple. Table of contents: 1. Setup JSON.simple 2. Write JSON to File using JSON.simple 3. Read JSON from File using JSON.simple 4. Java object to JSON using JSON.simple 5. JSON to Java Object using JSON.simple 6. Download Source Code 7. References P.S Tested with json-simple …

Read more

Gson Streaming APIs to read and write JSON

Streaming APIs are efficient ways of processing large JSON files or data without loading the entire document into memory. Gson provides JsonReader and JsonWriter classes for JSON streaming. Gson’s Streaming API JsonWriter – Write JSON as a stream. JsonReader – Read JSON as a stream. Table of contents: 1. Setup Google Gson 1. Write JSON …

Read more

Jackson Streaming API examples

This article shows how to use Jackson’s Streaming API for both reading from and writing to JSON. Jackson’s Streaming API JsonGenerator – Write JSON data JsonParser – Read and Parse JSON data Table of contents: 1. Download Jackson 2. Write JSON using JsonGenerator 2. Write JSON Array using JsonGenerator 3. Read JSON using JsonParser 4. …

Read more

How to enable pretty print JSON with Jackson

In Jackson, we can use writerWithDefaultPrettyPrinter() to pretty print the JSON strings. Table of contents: 1. Setup Jackson 2. Compact print JSON (Default) 3. Pretty print JSON with Jackson 4. Pretty print JSON with Jackson (Globally) 5. Download Source Code 6. References P.S Tested with Jackson 2.17.0 1. Setup Jackson Puts jackson-databind at pom.xml. pom.xml …

Read more

How to pretty print JSON using Gson

This article shows how to pretty print JSON using Gson. Table of contents: 1. Setup Google Gson 2. Default Compact Print JSON 3. Pretty Print JSON using Gson 4. Download Source Code 5. References P.S Tested with Gson 2.10.1 1. Setup Google Gson Declare gson in the pom.xml. pom.xml <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.10.1</version> </dependency> 2. …

Read more

JAXB hello world example

Jakarta XML Binding (JAXB; formerly Java Architecture for XML Binding) is an XML binding framework to convert Java objects to and from XML. XML Marshalling – Convert Java objects into XML. XML Unmarshalling – Convert XML back into Java Objects. Note This article will focus on Java 11, JAXB 3 and EclipseLink MOXy JAXB RI. …

Read more

Spring 3 REST hello world example

In Spring 3, old RequestMapping class is enhanced to support RESTful features, which makes Spring developers easier to develop REST services in Spring MVC. In this tutorial, we show you how to use Spring 3 MVC annotations to develop a RESTful style web application. 1. Project Directory Review the project folder structure. 2. Project Dependency …

Read more

Spring 3 MVC ContentNegotiatingViewResolver example

Spring 3, ContentNegotiatingViewResolver, is an interesting view resolver, which allow you to output a same resource (content or data) to different type of views like JSP, XML, RSS, JSON and etc. Put it simple, see following web requested URL, which will return in different views. https://mkyong.com/fruit/banana.rss , returned as RSS file. https://mkyong.com/fruit/banana.xml , returned as …

Read more

Spring 3 MVC and JSR303 @Valid example

In Spring 3, you can enable “mvc:annotation-driven” to support JSR303 bean validation via @Valid annotation, if any JSR 303 validator framework on the classpath. Note Hibernate Validator is the reference implementation for JSR 303 In this tutorial, we show you how to integrate Hibernate validator with Spring MVC, via @Valid annotation, to perform bean validation …

Read more

Spring 3 MVC and JSON example

In this tutorial, we show you how to output JSON data in Spring MVC framework. Technologies used : Spring 3.2.2.RELEASE Jackson 1.9.10 JDK 1.6 Eclipse 3.6 Maven 3 P.S In Spring 3, to output JSON data, just puts Jackson library in the project classpath. 1. Project Dependencies Get Jackson and Spring dependencies. pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" …

Read more

Spring 3 MVC and XML example

In Spring 3, one of the feature of “mvc:annotation-driven“, is support for convert object to/from XML file, if JAXB is in project classpath. In this tutorial, we show you how to convert a return object into XML format and return it back to user via Spring @MVC framework. Technologies used : Spring 3.0.5.RELEASE JDK 1.6 …

Read more

Spring 3 MVC and RSS feed example

In Spring 3, comes with a abstract class “AbstractRssFeedView” to generate RSS feed view, using java.net’s ROME package. In this tutorial, we show you how to generate a RSS feed view from Spring MVC framework. Technologies used : Spring 3.0.5.RELEASE ROME 1.0.0 JDK 1.6 Eclipse 3.6 Maven 3 At the end of the tutorial, when …

Read more

ClassNotFoundException : com.sun.syndication.feed.WireFeed

Problem Developing RSS with Spring MVC, extends “AbstractRssFeedView“, hit following error message during application start up. Caused by: java.lang.NoClassDefFoundError: com/sun/syndication/feed/WireFeed at java.lang.Class.getDeclaredConstructors0(Native Method) at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389) at java.lang.Class.getDeclaredConstructors(Class.java:1836) //… Caused by: java.lang.ClassNotFoundException: com.sun.syndication.feed.WireFeed at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1516) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1361) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320) … 41 more Solution Spring MVC using “ROME” to generate RSS feed. For Maven, include below dependency …

Read more

Jersey + Spring integration example

This tutorial show you how to integrate Jersey web application with Spring framework. Technologies used : Jersey 1.8 Spring 3.0.5.RELEASE Eclipse 3.6 Maven 3 1. Project Dependency Declares Jersey 1.8, Spring3 and “jersey-spring.jar” dependencies in Maven pom.xml file. Note In “jersey-spring.jar” version, it will download all the Spring 2.5.6 dependencies. To use Spring 3, you …

Read more

Spring request scope error : No thread-bound request found

Problem Developing web application with Spring, make a bean with scope of “request“. @Component @Scope("request") public class PaymentService { @Autowired UserBo userBo; //… But hit following error message? Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally …

Read more

RESTful Java client with Jersey client

This tutorial show you how to use Jersey client APIs to create a RESTful Java client to perform “GET” and “POST” requests to REST service that created in this “Jersey + Json” example. 1. Jersey Client Dependency To use Jersey client APIs, declares “jersey-client.jar” in your pom.xml file. File : pom.xml <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-client</artifactId> <version>1.8</version> …

Read more

Jersey and JSON examples (Jackson)

This article shows how to return a JSON response in the Jersey application, using Jackson 2.x. Tested with Jersey 3.0.2 Grizzly 3 HTTP Server Jackson 2.12.2 Java 11 Maven JUnit 5 and JSONassert 1.5 (Unit Test) Table of contents 1. Jackson as the JSON provider in Jersey 2. Project Directory 3. Project dependencies 4. Jersey …

Read more

XML example with Jersey + JAXB

This tutorial show you how to use JAXB to convert object to XML in Jersey, and return it back to user. 1. Dependency To integrate JAXB with Jersey, no extra dependency is required. Just include “jersey-server.jar” will do. 2. JAXB Annotation Annotate object with JAXB annotation, for conversion later. import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; …

Read more

File upload example in Jersey

In this tutorial, we show you how do to file upload with Jersey, JAX-RS implementation. 1. Jersey Multipart Dependency To support multipart (file upload) in Jersey, you just need to include “jersey-multipart.jar” in Maven pom.xml file. <project …> <repositories> <repository> <id>maven2-repository.java.net</id> <name>Java.net Repository for Maven</name> <url>http://download.java.net/maven/2/</url> <layout>default</layout> </repository> </repositories> <dependencies> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-server</artifactId> <version>1.8</version> </dependency> …

Read more

Jersey hello world example

This article shows how to start a Grizzly HTTP server to run a JAX-RS or Eclipse Jersey application. Tested with Jersey 3.0.2 Grizzly 3 HTTP server Java 8 Maven JUnit 5 Table of contents 1. Project Directory 2. Jersey dependencies 3. Jersey and HK2 dependency injection 4. Jersey endpoints 5. Start Jersey application 6. Demo …

Read more

Jersey : The ResourceConfig instance does not contain any root resource classes

Problem Deploying Jersey REST service, hit following error message on Tomcat. SEVERE: Servlet /RESTfulExample threw load() exception com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes. //… code omitted Here’s the web.xml <web-app …> <servlet> <servlet-name>jersey-serlvet</servlet-name> <servlet-class> com.sun.jersey.spi.container.servlet.ServletContainer </servlet-class> <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <param-value>com.mkyong.rest</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>jersey-serlvet</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> </web-app> Solution Many reasons …

Read more

RESTful Java client with RESTEasy client framework

This tutorial show you how to create a RESTful Java client with RESTEasy client framework, to perform “GET” and “POST” requests to REST service that created in last “Jackson + JAX-RS” tutorial. 1. RESTEasy Client Framework RESTEasy client framework is included in RESTEasy core module, so, you just need to declares the “resteasy-jaxrs.jar” in your …

Read more

RESTful Java client with Apache HttpClient

Apache HttpClient is a robust and complete solution Java library to perform HTTP operations, including RESTful service. In this tutorial, we show you how to create a RESTful Java client with Apache HttpClient, to perform a “GET” and “POST” request. Note The RESTful services from last “Jackson + JAX-RS” article will be reused. 1. Get …

Read more

RESTful Java client with java.net.URL

In this tutorial, we show you how to create a RESTful Java client with Java build-in HTTP client library. It’s simple to use and good enough to perform basic operations for REST service. The RESTful services from last “Jackson + JAX-RS” article will be reused, and we will use “java.net.URL” and “java.net.HttpURLConnection” to create a …

Read more

ClassNotFoundException : com.thoughtworks.xstream.io.HierarchicalStreamReader

Problem XML development in Spring MVC, via oxm , hit “HierarchicalStreamReader” class not found exception? Caused by: java.lang.ClassNotFoundException: com.thoughtworks.xstream.io.HierarchicalStreamReader at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1516) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1361) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320) … 49 more Solution The class “HierarchicalStreamReader” class belong to “xstream.jar“. If you are using Maven, declares following dependency in your pom.xml file. <dependency> <groupId>com.thoughtworks.xstream</groupId> <artifactId>xstream</artifactId> <version>1.3.1</version> </dependency> Note For …

Read more

Illegal to inject a message body into a singleton into public org.codehaus.jackson.jaxrs.JacksonJsonProvider

Problem Using Jackson as JSON provider in RESTEasy. <dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-jaxrs</artifactId> <version>2.2.1.GA</version> </dependency> <dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-jackson-provider</artifactId> <version>2.2.1.GA</version> </dependency> With RESTEasy auto scanning enabled. <context-param> <param-name>resteasy.scan</param-name> <param-value>true</param-value> </context-param> When starting up, it hits following errors and failed to start up any of the RESTEasy services. SEVERE: Exception sending context initialized event to listener instance of class …

Read more