Spring MVC BeanNameUrlHandlerMapping example

In Spring MVC, BeanNameUrlHandlerMapping is the default handler mapping mechanism, which maps URL requests to the name of the beans. For example, <beans …> <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/> <bean name="/welcome.htm" class="com.mkyong.common.controller.WelcomeController" /> <bean name="/streetName.htm" class="com.mkyong.common.controller.StreetNameController" /> <bean name="/process*.htm" class="com.mkyong.common.controller.ProcessController" /> </beans> In above example, If URI pattern /welcome.htm is requested, DispatcherServlet will forward the request to the …

Read more

Spring MVC hello world example (Maven and Thymeleaf)

This tutorial shows you how to create a Spring Web MVC application with the Thymeleaf template. Technologies and tools used: Java 11 Spring 5.2.22.RELEASE Thymeleaf 3.0.15.RELEASE Embedded Jetty Server 9.4.45.v20220203 Servlet API 4.0.4 Bootstrap 5.2.0 (webjars) IntelliJ IDEA Maven 3.8.6 Spring Test 5.2.22.RELEASE Hamcrest 2.2 JUnit 5.9 Table of contents: 1. Spring Web MVC Basic …

Read more

ModelAndView’s model value is not displayed in JSP via EL

Problem In Spring MVC development, developer try to set a value into a model, and display the value in JSP via EL, e.g ${msg}, but it just outputs the result as it is – ${msg}, not the “value” stored in the model. The EL is just not working in JSP, why? Spring’s Controller import javax.servlet.http.HttpServletRequest; …

Read more

Download standard.jar (taglib) from Maven

The standard.jar (taglib) library is used to enable the JSTL expression language in JSP page, and it’s always used together with the jstl.jar together. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> …. </html> To download both standard.jar and jstl.jar from Maven, just put the following Maven coordinate in the pom.xml file. <!– standard.jar –> <dependency> <groupId>taglibs</groupId> …

Read more

Top 20 Java Websites

Here’s the best 20 Java websites in my collections, which provides latest Java news, articles and tutorials. If you have other great Java websites, please leave a comment to share with others. P.S The order doesn’t means any priority. 1. O’Reilly Java URL : http://www.onjava.com Since : 10-feb-2000 Rss : http://www.oreillynet.com/pub/feed/7?format=rss2 Description : O’Reilly’s, contains …

Read more

Java object sorting example (Comparable and Comparator)

In this tutorial, it shows the use of java.lang.Comparable and java.util.Comparator to sort a Java object based on its property value. 1. Sort an Array To sort an Array, use the Arrays.sort(). String[] fruits = new String[] {"Pineapple","Apple", "Orange", "Banana"}; Arrays.sort(fruits); int i=0; for(String temp: fruits){ System.out.println("fruits " + ++i + " : " + …

Read more

How to sort an Array in java

Java example to show the use of Arrays.sort() to sort an Array. The code should be self-explanatory. import java.util.Arrays; import java.util.Collections; public class ArraySorting{ public static void main(String args[]){ String[] unsortStringArray = new String[] {"c", "b", "a", "3", "2", "1"}; int[] unsortIntArray = new int[] {7,5,4,6,1,2,3}; System.out.println("Before sort"); System.out.println("— unsortStringArray —"); for(String temp: unsortStringArray){ System.out.println(temp); …

Read more

How to sort an ArrayList in java

By default, the ArrayList’s elements are display according to the sequence it is put inside. Often times, you may need to sort the ArrayList to make it alphabetically order. In this example, it shows the use of Collections.sort(‘List’) to sort an ArrayList. import java.util.ArrayList; import java.util.Collections; import java.util.List; public class SortArrayList{ public static void main(String …

Read more

How to sort a Map in Java

Few Java examples to sort a Map by its keys or values. Note If you are using Java 8, refer to this article – How to use Stream APIs to sort a Map 1. Sort by Key 1.1 Uses java.util.TreeMap, it will sort the Map by keys automatically. SortByKeyExample1.java package com.mkyong.test; import java.util.HashMap; import java.util.Map; …

Read more

How to initialize an ArrayList in one line

Here’s a few ways to initialize an java.util.ArrayList, see the following full example: InitArrayList.java package com.mkyong.examples; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class InitArrayList { public static void main(String[] args) { //1. Normal way List<String> list = new ArrayList<String>(); list.add("String A"); list.add("String B"); list.add("String C"); System.out.println("List 1……"); for (String temp : list) { System.out.println(temp); …

Read more

java.lang.ClassFormatError : Absent Code attribute in method that is not native or abstract in class file …

Problem A very strange and rare problem, happened in JPA or Hibernate development. Caused by: java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/persistence/GenerationType at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClassCond(Unknown Source) at java.lang.ClassLoader.defineClass(Unknown Source) at java.security.SecureClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.access$000(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) …

Read more

java.lang.ClassNotFoundException: javax.transaction.TransactionManager

Problem In JPA or Hibernate development, it hits the following error message : Caused by: java.lang.ClassNotFoundException: javax.transaction.TransactionManager at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) … 23 more Solution The javax.transaction.TransactionManager is a class inside the J2EE SDK library “javaee.jar“, you are missing this jar …

Read more

java.lang.ClassNotFoundException: javax.persistence.Entity

Problem In JPA or Hibernate development, it hits the following error message : Caused by: java.lang.ClassNotFoundException: javax.persistence.Entity at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) … 24 more Solution The javax.persistence.Entity is a class inside the J2EE SDK library “javaee.jar“, you are missing this jar …

Read more

java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter

Problem In Hibernate development, it’s common to hits the following error message. SEVERE: Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in ServletContext resource [/WEB-INF/classes/config/database/spring/HibernateSessionFactory.xml]: Invocation of init method failed; nested exception is Caused by: org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer] … … Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown …

Read more

How to copy directory in Java

In Java, we can use the Java 1.7 FileVisitor or Apache Commons IO FileUtils.copyDirectory to copy a directory, which includes its sub-directories and files. This article shows a few of the common ways to copy a directory in Java. FileVisitor (Java 7+) FileUtils.copyDirectory (Apache commons-io) Custom Copy using Java 7 NIO and Java 8 Stream. …

Read more

How to check if directory is empty in Java

Here’s an example to check if a directory is empty. Example package com.mkyong.file; import java.io.File; public class CheckEmptyDirectoryExample { public static void main(String[] args) { File file = new File("C:\\folder"); if(file.isDirectory()){ if(file.list().length>0){ System.out.println("Directory is not empty!"); }else{ System.out.println("Directory is empty!"); } }else{ System.out.println("This is not a directory"); } } }

How to delete directory in Java

If we use the NIO Files.delete to delete a non-empty directory in Java, it throws DirectoryNotEmptyException; for legacy IO File.delete to delete a non-empty directory, it returns a false. The standard solution is to loop the directory recursively, and delete all its children’s contents first (sub-files or sub-directories), and delete the parent later. This example …

Read more

How to create directory in Java

In Java, we can use the NIO Files.createDirectory to create a directory or Files.createDirectories to create a directory including all nonexistent parent directories. try { Path path = Paths.get("/home/mkyong/a/b/c/"); //java.nio.file.Files; Files.createDirectories(path); System.out.println("Directory is created!"); } catch (IOException e) { System.err.println("Failed to create directory!" + e.getMessage()); } 1. Create Directory – Java NIO 1.1 We can …

Read more

How to create a temporary file in Java

In Java, we can use the following two Files.createTempFile() methods to create a temporary file in the default temporary-file directory. Path createTempFile(Path dir, String prefix, String suffix, FileAttribute<?>… attrs) throws IOException Path createTempFile(String prefix, String suffix, FileAttribute<?>… attrs) throws IOException The default temporary file folder is vary on operating system. Windows – %USER%\AppData\Local\Temp Linux – …

Read more

How to append text to a file in Java

This article shows how to use the following Java APIs to append text to the end of a file. Files.write – Append a single line to a file, Java 7. Files.write – Append multiple lines to a file, Java 7, Java 8. Files.writeString – Java 11. FileWriter FileOutputStream FileUtils – Apache Commons IO. In Java, …

Read more

How to delete a temporary file in Java

In Java, we can use the NIO Files.delete() or Files.deleteIfExists() to delete a temporary file, it works the same like delete a regular text file. // create a temporary file Path path = Files.createTempFile(null, ".log"); // delete Files.delete(path); // or if(Files.deleteIfExists(path)){ // success }else{ // file does not exist } 1. Delete Temporary File – …

Read more

How to delete a file in Java

In Java, we can use the NIO Files.delete(Path) and Files.deleteIfExists(Path) to delete a file. 1. Delete a file with Java NIO 1.1 The Files.delete(Path) deletes a file, returns nothing, or throws an exception if it fails. DeleteFile1.java package com.mkyong.io.file; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class DeleteFile1 { public static void main(String[] args) { …

Read more

How to rename or move a file in Java

In Java, we can use the NIO Files.move(source, target) to rename or move a file. import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; //… Path source = Paths.get("/home/mkyong/newfolder/test1.txt"); Path target = Paths.get("/home/mkyong/newfolder/test2.txt"); try{ Files.move(source, target); } catch (IOException e) { e.printStackTrace(); } 1. Rename a file in the same directory. 1.1 This example renames a …

Read more

How to write to file in Java – BufferedWriter

In Java, we can use BufferedWriter to write content into a file. // jdk 7 try (FileWriter writer = new FileWriter("app.log"); BufferedWriter bw = new BufferedWriter(writer)) { bw.write(content); } catch (IOException e) { System.err.format("IOException: %s%n", e); } Note If possible, uses Files.write instead, one line, simple and nice. List<String> list = Arrays.asList("Line 1", "Line 2"); …

Read more

How to write data to a temporary file in Java

The temporary file is just a regular file created on a predefined directory. In Java, we can use the NIO Files.write() to write data to a temporary file. // create a temporary file Path tempFile = Files.createTempFile(null, null); // Writes a string to the above temporary file Files.write(tempFile, "Hello World\n".getBytes(StandardCharsets.UTF_8)); // Append List<String> content = …

Read more

How to construct a file path in Java

In this tutorial, we will show you three Java examples to construct a file path : File.separator or System.getProperty(“file.separator”) (Recommended) File file = new File(workingDir, filename); (Recommended) Create the file separator manually. (Not recommend, just for fun) 1. File.separator Classic Java example to construct a file path, using File.separator or System.getProperty(“file.separator”). Both will check the …

Read more

How to get the temporary file path in Java

In Java, we can use System.getProperty("java.io.tmpdir") to get the default temporary file location. For Windows, the default temporary folder is %USER%\AppData\Local\Temp For Linux, the default temporary folder is /tmp 1. java.io.tmpdir Run the below Java program on a Ubuntu Linux. TempFilePath1 package com.mkyong.io.temp; public class TempFilePath1 { public static void main(String[] args) { String tmpdir …

Read more

jQuery mousemove() example

The mousemove() event is fire when the mouse moves inside the matched element, and keep fire the event for every single pixel mouse moves around the matched element. For example, a big 300 x 200 div box with an id of “bigbigbox”. <style type="text/css"> #bigbigbox{ margin:16px 16px 16px 48px; border:1px groove blue; background-color : #BBBBBB; …

Read more