How to install Hibernate / JBoss Tools in Eclipse IDE

Hibernate Tools is a handy tool for Java’s developers to generate tedious hibernate related stuffs like mapping files and annotation code. The common use case is the “reverse engineering” feature to generate Hibernate model class, hbm mapping file or annotation code from database tables. Note Hibernate Tools is bundled as the core component of JBoss …

Read more

A simple HttpSessionAttributeListener example

Here’s a simple “HttpSessionAttributeListener” example to keep track session’s attribute in a web application. If you want to keep monitor your session’s attribute add , update and remove behavior, then consider this listener. Java Source package com.mkyong; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionBindingEvent; public class MyAttributeListener implements HttpSessionAttributeListener { @Override public void attributeAdded(HttpSessionBindingEvent event) { String attributeName …

Read more

A simple HttpSessionListener example – active sessions counter

Here’s a simple “HttpSessionListener” example to keep track the total number of active sessions in a web application. If you want to keep monitor your session’s create and remove behavior, then consider this listener. Java Source package com.mkyong; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class SessionCounterListener implements HttpSessionListener { private static int totalActiveSessions; public static int …

Read more

SAX Error – Content is not allowed in prolog

We use SAX parser to parse an XML file, and hist the following error message: Terminal org.xml.sax.SAXParseException; systemId: ../src/main/resources/staff.xml; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog. In short, invalid text or BOM before the XML declaration or different encoding will cause the SAX Error – Content is not allowed in prolog. 1. …

Read more

How to access the Cookies at the Client site

Here’s a example to access the Cookies at the previous article “simple cookie example” Java Source package com.mkyong; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ServletDemoCookie extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{ response.setContentType("text/html"); PrintWriter pw = response.getWriter(); Cookie[] cookie = request.getCookies(); pw.println("All Cookies in …

Read more

A simple cookie example in servlet

Here’s a simple Cookie example in Servlet Java Source package com.mkyong; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ServletDemo extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{ response.setContentType("text/html"); PrintWriter pw = response.getWriter(); Cookie cookie = new Cookie("url","mkyong dot com"); cookie.setMaxAge(60*60); //1 hour response.addCookie(cookie); pw.println("Cookies created"); } …

Read more

Where does FireFox store the Cookies ?

Simple question, but not anyone will know the answer. Actually the Firefox 3.x does stored the Cookies in the following folder C:\Documents and Settings\{your username} \Application Data\Mozilla\Firefox\Profiles\{random mix char}.default The cookie information is stored in the files “cookies.sqlite” and “permissions.sqlite”. However the content inside are all rubbish characters, you may not able to view it …

Read more

Tomcat deploy Maven project web.xml to a wrong folder in Eclipse

Problem During the Eclipse debugging session, the “web.xml” will always deploy to a wrong folder. It’s always cause by manual migrated or converted a Java web project to Maven’s project. See the Eclipse’s workspace folder structure, Tomcat in Eclipse is deploy “web.xml” to a wrong folder, and causing the entire web application fail to run. …

Read more

How to configure the session timeout in servlet

The session timeout in a web application can be configurable in two ways 1) Timeout in the deployment descriptor (web.xml) – Specified the timeout value in “minute” , enclose with “session-config” element. <web-app …> <session-config> <session-timeout>20</session-timeout> </session-config> </web-app> The above setting is apply for the entire web application, and session will be kill by container …

Read more

Different between ServleConfig and ServletContext

Many servlet’s developers are confuse about the different between “ServletConfig” and “ServletContext”. Actually the “ServletContext” name is quite confusing, it should change to “AppConfig” or “AppContext” in the future release 🙂 ContextConfig 1) This is one per “web application”, access globally by all the servlets’ class 2) web.xml – within the web-app element and outside …

Read more

How to check whether the session is existed?

There are two ways to detect whether the session is existed. 1) request.getSession(); + session.isNew() – Retrieve a session from “request.getSession();”, this function will always return a session no matter what, it’s equivalent to request.getSession(true);. The only problem is you do not know whether this is new or existed session. – Later you can check …

Read more

How to add remote repository in Maven

Not every library is stored in the Maven Central Repository, some libraries are only available in Java.net or JBoss repository (remote repository). 1. Java.net Repository pom.xml <repositories> <repository> <id>java-net-repo</id> <url>https://maven.java.net/content/repositories/public/</url> </repository> </repositories> 2. JBoss Repository pom.xml <repositories> <repository> <id>jboss-repo</id> <url>http://repository.jboss.org/nexus/content/groups/public/</url> </repository> </repositories> 3. Spring Repository pom.xml <repositories> <repository> <id>spring-repo</id> <url>https://repo.spring.io/release</url> </repository> </repositories> References Configuring Maven …

Read more

Annotations are not supported in -source 1.3 – Maven

Problem Building a Maven project, hit following annotation error message in Maven output console. [INFO] Compilation failure E:\workspace\serlvetdemo\src\main\java\com\mkyong\AppServletContextListener.java: [8,2] annotations are not supported in -source 1.3 (use -source 5 or higher to enable annotations) @Override Solution Maven default is using JDK1.3 for the project compilation, building or packaging (mvn compile, install). Since JDK1.3 is not …

Read more

ServletContextListener Example

The listener is something sitting there and wait for specified event happened, then “hijack” the event and run its own event. Problem You want to initialize a database connection pool before the web application is started, is there a “main ()” method in the web application environment? Solution The ServletContextListener is what you want, it …

Read more

How to pass parameters to whole web application – ServletContext

Here’s a serlvet code example to demonstrate how to pass a parameter to whole web application by using ServletContext “init-param” in web.xml. In the deployment descriptor (web.xml) Put your parameter value in “init-param” and make sure outside the “servlet” element <servlet> <servlet-name>ServletName</servlet-name> <servlet-class>com.mkyong.ServletDemo</servlet-class> </servlet> <context-param> <param-name>email</param-name> <param-value>[email protected]</param-value> </context-param> Servlet code public void doGet(HttpServletRequest request, HttpServletResponse …

Read more

How to convert Java web project to Maven based project

There is no exact or official solution to convert an existing Java web project to a Maven based web application project. Basically, the Maven based project conversion will involve two major changes, which is : Folder structure – Follow this Maven’s folder structure. Dependency library – Put all your dependency libraries in pom.xml file. Steps …

Read more

How to pass parameters to a servlet – ServletConfig

Here’s a serlvet code example to demonstrate how to pass a parameter to a servlet by using ServletConfig “init-param” in web.xml In the deployment descriptor (web.xml) Put your parameter value in “init-param” and make sure inside the “servlet” element <servlet> <servlet-name>ServletName</servlet-name> <servlet-class>com.mkyong.ServletDemo</servlet-class> <init-param> <param-name>email</param-name> <param-value>[email protected]</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>ServletName</servlet-name> <url-pattern>/Demo</url-pattern> </servlet-mapping> Servlet code public void …

Read more

Servlet code to download text file from website – Java

Here’s a servlet code example to download a text file from a website. For example Let’s say a text file named “testing.txt” , and you want to let user download it with a URL , for example “http://localhost:8080/servlet/DownloadDemo” . 1. Create a text file named “testing.txt” , put it into the project root folder. \–servlet …

Read more

A Simple Servlet Example – (write, deploy, run)

Talking about the web technology, Java developers will keep talking about how powerful the Spring , Struts, Wicket, JSF…..When talking about the deployment, they will say using Ant script or Maven to build or deploy. Ironically, without the IDE or technology help, many Java developers do not know either how to create a simple servlet …

Read more

Java – How to display all System properties

In Java, you can use System.getProperties() to get all the system properties. Properties properties = System.getProperties(); properties.forEach((k, v) -> System.out.println(k + ":" + v)); // Java 8 1. Example DisplayApp.java package com.mkyong.display; import java.util.Properties; public class DisplayApp { public static void main(String[] args) { Properties properties = System.getProperties(); // Java 8 properties.forEach((k, v) -> System.out.println(k …

Read more

Java – Convert Character to ASCII

In Java, we can cast the char to int to get the ASCII value of the char. char aChar = ‘a’; //int ascii = (int) aChar; // explicitly cast, optional, improves readability int ascii = aChar; // implicit cast, auto cast char to int, System.out.println(ascii); // 97 The explicit cast (int)char is optional, if we …

Read more

How to change Eclipse splash welcome screen image

Eclipse IDE has many customize components, the splash welcome image (purple color loading image) is one of those. I’m very boring to see the purple image loading everyday, a new fresh image will make my development more encouraging 🙂 How to change Eclipse IDE splash image 1) Find “config.ini” file Find the Eclipse’s configuration file …

Read more

TestNG parameter testing example

Yet another TestNG parameter testing example, with @DataProvider. 1. CharUtil Class Let’s say, a class to convert a character to ASCII or vice verse, how can you unit test it with TestNG? CharUtils.java package com.mkyong.testng.examples.parameter; /** * Character Utility class * * @author mkyong * */ public class CharUtils { /** * Convert the characters …

Read more

Maven dependency mechanism, how it works

Maven’s dependency mechanism help to download all the necessary dependency libraries automatically, and maintain the version upgrade as well. Case study Let see a case study to understand how it works. Assume you want to use Log4J as your project logging mechanism. Here is what you do… 1. In traditional way Visit http://logging.apache.org/log4j/ Download the …

Read more

How to create a project with Maven template

In this tutorial we will show you how to use mvn archetype:generate to generate a project from a list of existing Maven templates. In Maven 3.1.1, there are 1000+ templates, crazy, Maven team should filter out some useless templates. Normally, we just use the following two templates : maven-archetype-webapp – Java Web Project (WAR) maven-archetype-quickstart …

Read more

10 Java Regular Expression Examples You Should Know

Regular expression is an art of the programing, it’s hard to debug , learn and understand, but the powerful features are still attract many developers to code regular expression. Let’s explore the following 10 practical regular expression ~ enjoy 🙂 1. Username Regular Expression Pattern ^[a-z0-9_-]{3,15}$ ^ # Start of the line [a-z0-9_-] # Match …

Read more

How to extract HTML Links with regular expression

In this tutorial, we will show you how to extract hyperlink from a HTML page. For example, to get the link from following content : this is text1 <a href=’mkyong.com’ target=’_blank’>hello</a> this is text2… First get the “value” from a tag – Result : a href=’mkyong.com’ target=’_blank’ Later get the “link” from above extracted value …

Read more

How to validate HTML tag with regular expression

HTML tag Regular Expression Pattern <("[^"]*"|'[^’]*’|[^’">])*> Description < #start with opening tag "<" ( # start of group #1 "[^"]*" # allow string with double quotes enclosed – "string" | # ..or ‘[^’]*’ # allow string with single quote enclosed – ‘string’ | # ..or [^’">] # cant contains one single quotes, double quotes and …

Read more

Java regex validate date format examples

This article shows how to use regex + code to validate a date format, support single and leading zero month and day format (1 or 01), check for the 30 or 31 days of the month, and leap year validation. Below are the requirements for a valid date. Year format, 1900, 2099 regex Month format, …

Read more

How to validate Time in 24 Hours format with regular expression

Time in 24-Hour Format Regular Expression Pattern ([01]?[0-9]|2[0-3]):[0-5][0-9] Description ( #start of group #1 [01]?[0-9] # start with 0-9,1-9,00-09,10-19 | # or 2[0-3] # start with 20-23 ) #end of group #1 : # follow by a semi colon (:) [0-5][0-9] # follw by 0..5 and 0..9, which means 00 to 59 The 24-hour clock …

Read more

Java IP Address (IPv4) regex examples

This article focus on how to validate an IP address (IPv4) using regex and Apache Commons Validator. Here is the summary. IPv4 regex explanation. Java IPv4 validator, using regex. Java IPv4 validator, using commons-validator-1.7 JUnit 5 unit tests for the above IPv4 validators. IPv4 regex final version. ^(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.(?!$)|$)){4}$ # Explanation ( [0-9] # 0-9 | …

Read more

How to validate image file extension with regular expression

Image File Extension Regular Expression Pattern ([^\s]+(\.(?i)(jpg|png|gif|bmp))$) Description ( #Start of the group #1 [^\s]+ # must contains one or more anything (except white space) ( # start of the group #2 \. # follow by a dot "." (?i) # ignore the case sensive checking for the following characters ( # start of the …

Read more

Java regex validate username examples

This article shows how to use regex to validate a username in Java. Username requirements Username consists of alphanumeric characters (a-zA-Z0-9), lowercase, or uppercase. Username allowed of the dot (.), underscore (_), and hyphen (-). The dot (.), underscore (_), or hyphen (-) must not be the first or last character. The dot (.), underscore …

Read more

Java regex validate password examples

This article shows how to use regex to validate a password in Java. Secure Password requirements Password must contain at least one digit [0-9]. Password must contain at least one lowercase Latin character [a-z]. Password must contain at least one uppercase Latin character [A-Z]. Password must contain at least one special character like ! @ …

Read more