How to make a file read only in Java

A Java program to demonstrate the use of java.io.File setReadOnly() method to make a file read only. Since JDK 1.6, a new setWritable() method is provided to make a file to be writable again. Example package com.mkyong; import java.io.File; import java.io.IOException; public class FileReadAttribute { public static void main(String[] args) throws IOException { File file …

Read more

How to check if a file is hidden in Java

A Java program to demonstrate the use of java.io.File isHidden() to check if a file is hidden. package com.mkyong; import java.io.File; import java.io.IOException; public class FileHidden { public static void main(String[] args) throws IOException { File file = new File("c:/hidden-file.txt"); if(file.isHidden()){ System.out.println("This file is hidden"); }else{ System.out.println("This file is not hidden"); } } } Note …

Read more

Spring MVC – Neither BindingResult nor plain target object for bean name ‘xxx’ available as request attribute.

Problem Recently, just converted the Spring MVC xml-based form controller to annotation-based form controller, and hits the following error message. SEVERE: Neither BindingResult nor plain target object for bean name ‘customerForm’ available as request attribute java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name ‘customerForm’ available as request attribute Above error message is clearly …

Read more

Spring MVC file upload example

Spring uses MultipartResolver interface to handle the file uploads in web application, two of the implementation : StandardServletMultipartResolver – Servlet 3.0 multipart request parsing. CommonsMultipartResolver – Classic commons-fileupload.jar Tools used in this article : Spring 4.3.5.RELEASE Maven 3 Tomcat 7 or 8, Jetty 9 or any Servlet 3.0 container In a nutshell, this article shows …

Read more

Spring MVC failed to convert property value in file upload form

Problem In Spring MVC application, while clicking on the file upload button, it hits the following property type conversion error? Failed to convert property value of type [org.springframework.web.multipart.commons.CommonsMultipartFile] to required type [byte[]] for property file; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [org.springframework.web.multipart.commons.CommonsMultipartFile] to required type [byte] for property file[0]: PropertyEditor [org.springframework.beans.propertyeditors.CustomNumberEditor] returned …

Read more

Spring MVC MultiActionController annotation example

In this tutorial, we show you how to develop a Spring MVC annotation-based MultiActionController, by using @RequestMapping. In XML-based MultiActionController, you have to configure the method name resolver (InternalPathMethodNameResolver, PropertiesMethodNameResolver or ParameterMethodNameResolver) to map the URL to a particular method name. But, life is more easier with annotation support, now you can use @RequestMapping annotation …

Read more

Spring MVC and PDF file via AbstractPdfView

Spring MVC comes with AbstractPdfView class to export data to pdf file via Bruno Lowagie’s iText library. In this tutorial, it show the use of AbstractPdfView class in Spring MVC application to export data to pdf file for download. 1. iText Get the iText library to generate the pdf file. <!– Pdf library –> <dependency> …

Read more

Spring MVC and Excel file via AbstractJExcelView

Spring MVC comes with AbstractJExcelView class to export data to Excel file via JExcelAPI library. In this tutorial, it show the use of AbstractJExcelView class in Spring MVC application to export data to Excel file for download. 1. JExcelAPI Get the JExcelAPI library. <!– JExcelAPI library –> <dependency> <groupId>net.sourceforge.jexcelapi</groupId> <artifactId>jxl</artifactId> <version>2.6.3</version> </dependency> 2. Controller A …

Read more

Spring MVC ParameterMethodNameResolver example

ParameterMethodNameResolver, a MultiActionController method name resolver to map URL to method name via request parameter name, and the parameter name is customizable through the “paramName” property. See following example : 1. MultiActionController A MultiActionController example. package com.mkyong.common.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.multiaction.MultiActionController; public class CustomerController extends MultiActionController{ public ModelAndView add(HttpServletRequest request, HttpServletResponse …

Read more

Spring MVC PropertiesMethodNameResolver example

PropertiesMethodNameResolver, a flexible MultiActionController method name resolver, to define the mapping between the URL and method name explicitly. See following example : 1. MultiActionController A MultiActionController example. package com.mkyong.common.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.multiaction.MultiActionController; public class CustomerController extends MultiActionController{ public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception { return new ModelAndView("CustomerPage", "msg","add() …

Read more

Spring MVC MultiActionController example

In Spring MVC application, MultiActionController is used to group related actions into a single controller, the method handler have to follow below signature : public (ModelAndView | Map | String | void) actionName( HttpServletRequest, HttpServletResponse [,HttpSession] [,CommandObject]); 1. MultiActionController See a MultiActionController example. package com.mkyong.common.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.multiaction.MultiActionController; public class …

Read more

Configure multiple view resolvers priority in Spring MVC

Problem In Spring MVC application, often times, you may applying few view resolver strategies to resolve the view name. For example, combine three view resolvers together : InternalResourceViewResolver, ResourceBundleViewResolver and XmlViewResolver. <beans …> <bean class="org.springframework.web.servlet.view.XmlViewResolver"> <property name="location"> <value>/WEB-INF/spring-views.xml</value> </property> </bean> <bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver"> <property name="basename" value="spring-views" /> </bean> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" > <property name="prefix"> <value>/WEB-INF/pages/</value> </property> …

Read more

Spring MVC RedirectView example

In Spring MVC, org.springframework.web.servlet.view.RedirectView, as name indicated, a view redirect to another absolute, context relative, or current request relative URL. In this tutorial, we show you a complete example to use RedirectView class. 1. RedirectView Declare a RedirectView bean, named “DummyRedirect“, redirect to URL “DummyRedirectPage.htm“. File : spring-views.xml <beans …> <!– Redirect view –> <bean …

Read more

Handling duplicate form submission in Spring MVC

In last Spring MVC form handling example, if you refresh the form success view, most browsers will prompt a pop-up dialog to confirm about the form resubmission. If you click “yes”, the form will be resubmitted again, this scenario is well-known as duplicated form submission. Figure : example of duplicated form submission. The common solution …

Read more

Spring MVC form handling example

This tutorial shows you how to do form handling in Spring Web MVC application. Technologies and tools used: Java 11 Spring 5.2.22.RELEASE JSP JSTL 1.2 Embedded Jetty Server 9.4.45.v20220203 Servlet API 4.0.4 Bootstrap 5.2.0 (webjars) Hibernate Validator 6.2.5.Final HSQLDB 2.7.0 IntelliJ IDEA Maven 3.8.6 Spring Test 5.2.22.RELEASE Hamcrest 2.2 JUnit 5.9 Table of contents: 1. …

Read more

Spring MVC hidden value example

In Spring MVC, you can use <form:hidden /> to render a HTML hidden value field. For example, <form:hidden path="secretValue" /> It will render the following HTML code <input id="secretValue" name="secretValue" type="hidden" value="I’m hidden value"/> P.S Assume “secretValue” property contains value “I’m hidden value”. In this tutorial, we show you how to use Spring’s form tag …

Read more

Spring MVC form errors tag example

In Spring MVC, the field error messages are generated by validators associated with the controller, and you can use the <form:errors /> tag to render those field error messages in an default HTML “span” tag. For example, 1. Validator A validator to check the “username” field, if empty, return the “required.username” error message from the …

Read more

Spring MVC dropdown box example

In Spring MVC, form tags – <form:select />, <form:option /> or <form:options />, are used to render HTML dropdown box. See following examples : //SimpleFormController protected Map referenceData(HttpServletRequest request) throws Exception { Map referenceData = new HashMap(); Map<String,String> country = new LinkedHashMap<String,String>(); country.put("US", "United Stated"); country.put("CHINA", "China"); country.put("SG", "Singapore"); country.put("MY", "Malaysia"); referenceData.put("countryList", country); } 1. …

Read more

Spring MVC textarea example

In Spring MVC, use <form:textarea /> to render a HTML textarea field. For example, <form:textarea path="address" rows="5" cols="30" /> It will render the following HTML code <textarea id="address" name="address" rows="5" cols="30"></textarea> In this tutorial, we show you how to use Spring’s form tag “textarea” to render a HTML textarea to store the “address“. Additionally, add …

Read more

Spring MVC checkbox and checkboxes example

In Spring MVC, <form:checkbox /> is used to render a HTML checkbox field, the checkbox values are hard-coded inside the JSP page; While the <form:checkboxes /> is used to render multiple checkboxes, the checkbox values are generated at runtime. In this tutorial, we show you 3 different ways of render HTML checkbox fields: 1. <form:checkbox …

Read more

Spring MVC password example

In Spring MVC, you can use <form:password /> tag to render a HTML password field. For example, <form:password path="password" /> It will renders following HTML code <input id="password" name="password" type="password" value=""/> Note In Spring’s documentation, it mention about the ‘showPassword‘ attribute will display the password value, but it’s failed in my testing, may be you …

Read more

Spring MVC textbox example

In Spring MVC, you can use <form:input /> tag to render a HTML textbox field. For example, <form:input path="userName" /> It will renders following HTML code <input id="userName" name="userName" type="text" value=""/> In this tutorial, we show you how to use Spring’s form tag “input” to render a HTML textbox to store the “userName“. Additionally, add …

Read more

Spring MVC ParameterizableViewController example

In general, to return a view or page in Spring MVC application, you need to create a class, which extends the AbstractController , and return a ModelAndView() object. public class WelcomeController extends AbstractController{ @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("WelcomePage"); return model; } } In the bean …

Read more

Spring MVC Exception Handling Example

In J2EE / servlet web application, you can map error page to specify exception like this : web.xml <error-page> <error-code>404</error-code> <location>/WEB-INF/pages/404.jsp</location> </error-page> <error-page> <exception-type>com.mkyong.web.exception.CustomException</exception-type> <location>/WEB-INF/pages/error/custom_error.jsp</location> </error-page> <error-page> <exception-type>java.lang.Exception</exception-type> <location>/WEB-INF/pages/generic_error.jsp</location> </error-page> The above code should be self-exploratory. If the exception handling function exists in the servlet container, why we still need to use the Spring to …

Read more

404 error code is not working in Spring MVC

Problem In Spring MVC application, the 404 error code is configured properly. See the following web.xml snippet. File : web.xml <web-app …> <servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name> <url-pattern>*.htm</url-pattern> </servlet-mapping> //… <error-page> <error-code>404</error-code> <location>/WEB-INF/pages/404.htm</location> </error-page> </web-app> However, when user access any non-exist resources, it will display a blank page instead of the 404.htm. Solution …

Read more

Spring MVC ResourceBundleViewResolver example

In Spring MVC, ResourceBundleViewResolver is used to resolve “view named” based on view beans in “.properties” file. By default, ResourceBundleViewResolver will loads the view beans from file views.properties, which located at the root of the project class path. However, this location can be overridden through the “basename” property, for example, <beans …> <bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver"> <property …

Read more

Spring MVC XmlViewResolver example

In Spring MVC, XmlViewResolver is used to resolve “view name” based on view beans in the XML file. By default, XmlViewResolver will loads the view beans from /WEB-INF/views.xml, however, this location can be overridden through the “location” property : <beans …> <bean class="org.springframework.web.servlet.view.XmlViewResolver"> <property name="location"> <value>/WEB-INF/spring-views.xml</value> </property> </bean> </beans> In above case, it loads the …

Read more

Spring MVC InternalResourceViewResolver example

In Spring MVC, InternalResourceViewResolver is used to resolve “internal resource view” (in simple, it’s final output, jsp or htmp page) based on a predefined URL pattern. In additional, it allow you to add some predefined prefix or suffix to the view name (prefix + view name + suffix), and generate the final view page URL. …

Read more

Spring MVC internationalization example

In Spring MVC application, comes with few “LocaleResolver” to support the internationalization or multiple languages features. In this tutorial, it shows a simple welcome page, display the message from properties file, and change the locale based on the selected language link. 1. Project Folder Directory structure of this example. 2. Properties file Two properties files …

Read more

Cannot change HTTP accept header – use a different locale resolution strategy

Problem In Spring MVC application, while changing the locale with “org.springframework.web.servlet.i18n.LocaleChangeInterceptor“, it hits the following error java.lang.UnsupportedOperationException: Cannot change HTTP accept header – use a different locale resolution strategy …AcceptHeaderLocaleResolver.setLocale(AcceptHeaderLocaleResolver.java:45) Solution In Spring MVC application, if you do not configure the Spring’s LocaleResolver, it will use the default AcceptHeaderLocaleResolver, which does not allow to change …

Read more

Spring MVC + Log4j example

In this tutorial, we will show you how to use the log4j framework to do the logging in a Spring MVC web application. Technologies and tools used : Log4j 1.2.17 Spring 4.1.6.RELEASE Maven 3 Tomcat 6 Eclipse Kepler 4.3 Note By default, Spring (spring-core) is using the JCL (commons-logging) for logging, and the JCL has …

Read more

Spring MVC handler interceptors example

Spring MVC allow you to intercept web request through handler interceptors. The handler interceptor have to implement the HandlerInterceptor interface, which contains three methods : preHandle() – Called before the handler execution, returns a boolean value, “true” : continue the handler execution chain; “false”, stop the execution chain and return it. postHandle() – Called after …

Read more

Configure the handler mapping priority in Spring MVC

Often times, you may mix use of multiple handler mappings strategy in Spring MVC development. For example, use ControllerClassNameHandlerMapping to map all the convention handler mappings, and SimpleUrlHandlerMapping to map other special handler mappings explicitly. <beans …> <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <value> /index.htm=welcomeController /welcome.htm=welcomeController /main.htm=welcomeController /home.htm=welcomeController </value> </property> <property name="order" value="0" /> </bean> <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" …

Read more

Spring MVC SimpleUrlHandlerMapping example

In Spring MVC application, the SimpleUrlHandlerMapping is the most flexible handler mapping class, which allow developer to specify the mapping of URL pattern and handlers explicitly. The SimpleUrlHandlerMapping can be declared in two ways. 1. Method 1 – prop key The property keys are the URL patterns while the property values are the handler IDs …

Read more

Spring MVC ControllerClassNameHandlerMapping example

In Spring MVC, ControllerClassNameHandlerMapping use convention to map requested URL to Controller (convention over configuration). It takes the Class name, remove the ‘Controller’ suffix if exists and return the remaining text, lower-cased and with a leading “/”. See following few examples to demonstrate the use of this ControllerClassNameHandlerMapping class. 1. Before and After By default, …

Read more