spring-mvc,spring-el , @DateTimeFormat annotation not working in Spring Controller


@DateTimeFormat annotation not working in Spring Controller

Question:

Tag: spring-mvc,spring-el

I am following Spring Documentation 4. Through its guidelines I successfully collected the correctly formatted Date field. The Controller Class is

@Controller
public class HomeController{

    @RequestMapping("/home")
    public ModelAndView handleRequest(HttpServletRequest request,
                                      HttpServletResponse response) throws Exception {
    return new ModelAndView("page1", "myForm", new MyForm());
    }
}

MyForm Class has a field date annotated with @DateTimeFormat

public class MyForm{

    @NumberFormat(style = Style.CURRENCY)
    private Double value = 50.00;

    @DateTimeFormat(pattern = "dd/MM/yyyy")
    private Date date = new Date();

    @NumberFormat(style = Style.CURRENCY)
    public Double getValue() {
    return value;
   }

    @DateTimeFormat(pattern = "dd/MM/yyyy")
    public Date getDate() {
        return date;
    }
}

The JSP code that takes this myForm object and evaluates correctly formatted value of date field is

<spring:eval expression="myForm.date"/>

This far everything is correct. But when I try to use the date field inside my Spring Controller class

@Controller
public class HomeController {

    @DateTimeFormat(pattern = "dd/MM/yyyy")
    private Date date;

    @RequestMapping("/home")
    public ModelAndView handleRequest(HttpServletRequest request,
                                      HttpServletResponse response) throws Exception {
    date = new Date();
    return new ModelAndView("page1", "date", getDate());
    }
   @DateTimeFormat(pattern = "dd/MM/yyyy")
    public Date getDate() {
        return date;
    }

}

The JSP code that takes this myForm object and evaluates incorrectly formatted value of date field is

<spring:eval expression="date"/>

It still displays the date but doesn't format it. Please explain why it formats a field in MyForm Class but not a field in Controller.


Answer:

POJO MyForm is populated by Spring framework itself while submitting the form. Spring takes request parameters, convert into correct format and populate fields of your empty POJO but if you call methods annotated by @DateTimeFormat manually then it doesn't work as expected.

You have to use java SimpleDateFormat or joda DateTime in controller.


Related:


Submitting a Form with Angular JS and Spring MVC


java,angularjs,spring-mvc
I am noob with Angular JS and I am having difficulties to submit a simple Form using Angular JS and Spring MVC. I am getting this error: The requested resource is not available mock.jsp <%@taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core'%> <%@taglib prefix="spring" uri="http://www.springframework.org/tags"%> <%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <%@taglib prefix="security"uri="http://www.springframework.org/security/tags" %> <!doctype html> <html> <head>...

Multiple Controllers appropriate with one entity in spring framework


spring,spring-mvc
I'm starting to develop website that use the spring framework.I have three controller.There are newCustomerController,editCustomerController and deleteCustomerController.These controllers are mapped with view that use for create update and delete, but I create only customer. So, I would like to know.Is it appropriate to declare the controllers like this. Thank ...

How can I test my Struts 1.2 web application without server?


java,unit-testing,spring-mvc,struts-1
I have a Struts 1.2 web application. It has service & DAO classes as well. How can I test each and every layer without any Web/Application server. I heard, Spring provides the same facility for Spring MVC application. How I can test my application end to end? Please suggest?

How to check JAVA variable ${account} in jsp?


java,spring-mvc
I have a dropdown-menu, and I want to check if ${uaccount} equals admin show users_info item I don't konw how to write this in jsp . Please guide me <ul class="dropdown-menu dropdown-user"> <%if(${uaccount}).equals('admin')){ %> <li><a href="users_info">user info</a></li> <%} %> <li><a href="${pageContext.request.contextPath}/logout">logout</a></li> </ul> ...

Spring Webservices gives 406 error


java,spring,web-services,spring-mvc
I have created a simple Spring with webservices example but when I try to get the response I am getting error as : HTTP Status 406 - The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers. This...

Hibernate : Stale state exception


java,spring,hibernate,spring-mvc,transactions
I am working on a Spring-MVC application in which I am trying to delete an object from the database. Some days back, this error all of a sudden started, and now I am unable to delete. I checked on net, but I cannot find what am I doing wrong and...

How get value from property file to input in springConfig.xml


java,xml,spring-mvc
I want to get the property value in email.properties file to input in the springConfig.xml. but there is an error occur. here is my code below springConfig.xml <bean class="org.springframework.mail.javamail.JavaMailSenderImpl" id="mailSender"> <property name="host" value="${email.host}" /> <property name="protocol" value="${email.protocol}" /> <property name="port" value="${email.port}" /> <property name="username" value="${email.username}"/> <property name="password" value="${email.password}" />...

Ambiguous mapping found when I use extends clause


java,spring-mvc,inheritance,annotations
I have a CustomerController and CustomerCardController classes that extend CrudMethods class. I choose so, because these two controller use the same methods (getFileCustomer() is one of these). And I thought that it had been better use the inheritance to save code's rows. CustomerController @Controller public class CustomerController extends CrudMethods {...

How to get some utf-8 characters using hibernate and spring mvc in database?


java,spring,hibernate,spring-mvc,tomcat
I have developed small server program. When I extract tuple from database, some characters become ÇѱÛÃàÁ¦. I modify server.xml. However ÇѱÛÃàÁ¦ characters still appear. Help me. How can I get correct characters? This is my server.xml. (I use apache tomcat 7.0 server.) <?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the Apache...

Default Spring bean when profile is not present


java,spring,spring-mvc,spring-profiles
I'm using Spring MVC controllers, and I'd like to make some extra request-mapped methods available during development. I can do this using Spring profiles: @Controller @Profile("!dev") public class DefaultController { } @Controller @Profile("dev") public class DevController extends DefaultController { } But ideally, I'd rather not pollute the production classes' code...

Cron expression must consist of 6 fields (found 1 in “#{systemEnvironment['db_cron']}”)


spring,groovy,cron,spring-el
I'm trying to set a cron Scheduled annotation as follows: @Scheduled(cron = "#{systemEnvironment['db_cron']}") def void schedule() { } Next set the environment variable as: export db_cron="0 19 21 * * *" However, I get the runtime error: Cron expression must consist of 6 fields (found 1 in "#{systemEnvironment['db_cron']}") What can...

Spring Portlet Jquery Ajax post to Controller


javascript,jquery,json,spring-mvc,spring-portlet-mvc
EDIT: The startdate and enddate are joda dateTime in the POJO and the error I get is: SystemOut O 14:10:16.040 [WebContainer : 2] DEBUG org.springframework.beans.BeanUtils - No property editor [org.joda.time.DateTimeEditor] found for type org.joda.time.DateTime according to 'Editor' suffix convention ... SystemOut O Error::Failed to convert property value of type 'java.lang.String'...

Bean Creation exception, Injection of autowired dependency failed


java,spring,hibernate,spring-mvc
I'm using spring hibernate in my application. I used all the required jar files but still getting bean creation exception saying the following: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'voteController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.mindtree.service.VoteService com.mindtree.controller.VoteController.voteService; nested exception is...

i am passing a model class object but it print ad normal object


hibernate,spring-mvc,jstl
i am passing hibernate model class object type list but it prints as [Ljava.lang.Object;@1ec3adc.i am using spring mvc and tile hibernate.i want to pass "Subtab" type list.but it's passing "object" type list. here's the code for returning the list : DAOImpl : public List<Subtab> listSubtab(int usertype){ List<Subtab> subtablist=sessionFactory.getCurrentSession().createQuery("SELECT s.maintab, s.description,...

Dyanamic web module 3.0 required java 1.6 or newer


java,maven,spring-mvc
In my project i got following error in Markers. I also set java 1.6 in project facets ,java compliler and buildpath but not solve this error. ...

Is it possible to login from a winforms application to a website which uses spring security?


java,c#,winforms,spring-mvc,spring-security
I want to call a web service from my winforms application. My application is written on c# and the webservice is secured using spring security. Is it possible to login to the website and call that web service?. If it is possible how to do that?...

spring dynamic views of different directories


java,spring,spring-mvc
this is my first post in stackoverflow and also i'm new to spring. this is my question(please don't mind my language) this is my folder structure of the project in netbeans(i cant post images yet because i have no 10 reputations) WEB-INF views sales sales_invoice.jsp sales_order.jsp sales_order_list.jsp sales_invoice_list.jsp purchase purchase_order.jsp...

Spring MVC Validation error


java,spring,spring-mvc,java-ee
I have a Spring controller that accepts one of my business objects as an argument, that spring is automatically building from form data. One of the attributes of the object is an enum that comes from a select dropdown in the form. I am also using the @Valid notation to...

Spring Mobile apps to be deployed in emulator


javascript,android,html5,spring,spring-mvc
I'm trying to develop an application based on Spring MVC for mobile device. Spring Mobile do provide such features to view our application in mobile browser. But how can I run/deploy the application in emulator since it's non-android based application? Also if can anybody tell me, how can I test...

Issues with mapping multiple controllers


java,spring,spring-mvc
I am new to spring.My mappings not working correctly though my Tomcat logs show that my URL is mapped. INFO: Mapped URL path [/movie/{name}] onto handler 'movieController' Jun 21, 2015 9:03:24 PM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler INFO: Mapped URL path [/movie/{name}.*] onto handler 'movieController' Jun 21, 2015 9:03:24 PM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler INFO:...

Angularjs - Spring MVC Rest : how to handle exceptions


java,angularjs,spring-mvc
I am developping an single page app with angularjs and Spring Mcv Rest. I am calling my service (mail sending with javax mail) like that in Angularjs : SendProformaFax.get({idCommande:$scope.commande.id}) And on server side my service : @RequestMapping(value = "/sendProformaFax/{idCommande}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public void imprimeProforma(@PathVariable String...

Importing Spring MVC Project Manually to Eclipse


java,eclipse,spring,spring-mvc
I have a little problem. I had googled for this problem and I haven't found any solution related. My problem is, my office internet using proxy that banned me to download zip file. I need Spring MVC Project template in Spring Tool Suite (STS). So I downloaded the zip file...

Spring MVC - How to return simple String as JSON in Rest Controller


java,json,spring,rest,spring-mvc
My question is essentially a follow-up to this question. @RestController public class TestController { @RequestMapping("/getString") public String getString() { return "Hello World"; } } In the above, Spring would add "Hello World" into the response body. How can I return a String as a JSON response? I understand that I...

Bean property xxxDAO is not writable or has an invalid setter method


java,xml,spring,hibernate,spring-mvc
I know this question has been asked many times. But I could not find my solution. I am using spring with hibernate. There is a connection between User and UserWord as one to many mapping I have done same logic for other models and everything went OK. However when I...

Sending text file to client through Spring MVC web application


java,spring,jsp,spring-mvc,servlets
After doing some research online on the subject I currently managed to get things working with this code: @RequestMapping(value = "/report040Generated", method = RequestMethod.GET) public String index(Model model, HttpServletResponse response, HttpServletRequest request) throws IOException { String myString = "Hello"; response.setContentType("text/plain"); response.setHeader("Content-Disposition","attachment;filename=myFile.txt"); ServletOutputStream out = response.getOutputStream(); out.println(myString); out.flush(); out.close(); return...

Intercept @RequestBody after serialization but before controller


spring-mvc
My request body objects all implement a interface call Auditable, where the username and lastUpdate timestamp could be set. I would like to intercept calls to controller functions after serialization but before it hits controller so can I can these values in a single place. I looked at HandlerInterceptor.prehandle but...

Adding external static files (css, js, png …) in spring boot


java,spring,spring-mvc,spring-boot,thymeleaf
Background I have a spring boot application which has the logo.png file added to the static folder of the resource file, which is eventually built into the jar file which is used in the execution. This jar application need to be run in multiple instances for different clients. So what...

Spring-MVC, Hibernate : Creating DTO objects from Domain objects


java,spring,hibernate,spring-mvc,dto
I am working on a Spring-MVC application in which I am trying to search for List of GroupNotes in database. The mapping in my project is GroupCanvas has one-to-many mapping with GroupSection and GroupSection has one-to-many mapping with GroupNotes. Because of these mappings, I was getting LazyInitializationException. As suggested on...

viewResolver with more folders inside of WEB-INF/jsp is not working in spring


java,spring,jsp,spring-mvc
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <!-- avoid '???' --> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp"/> </bean> if i create other subfolders under jsp , for instance /WEB-INF/jsp/reports , /WEB-INF/jsp/insertions how should i configure now the viewResolver to can resolve these new sub folders??...

Jsp list output [email protected]?


jsp,spring-mvc,spring-boot
I have a list of tweets inside a user and when I iterate through them all I get is the object but not the actual text <c:forEach items = "${tweets}" var="user" ></c:forEach> <h1><c:out value="${user.tweets}" /></h1> </div> how do I get the value of the tweets, they all save as text...

Job not executing at fixed rate


spring-mvc,jobs,execution
I have the following spring mvc configuration: <task:scheduled-tasks scheduler="defaultScheduler"> <task:scheduled ref="myTaskWorker" method="someMethod" fixed-rate="500" /> </task:scheduled-tasks> When I execute the above it is not executed in every 500ms but only executed after the finishing of the previous one. How can i resolve this?...

How to apply HandlerInterceptor to Spring Boot Actuator endpoints?


java,spring,spring-mvc,spring-boot
I'm working with Java 8 and Spring 1.2.3 to build an application running inside a Tomcat 7 container. I do intercept every single call to my web application using a very simple HandlerInterceptor, that logs the overall time taken to create a response and the return code for every request....

How to send current page number in Ajax request


javascript,jquery,ajax,spring-mvc,datatables
I am using jQuery DataTable to display huge amount of data in a table. I am getting data page wise on Ajax request like this: var pageNo = 1; $('#propertyTable').dataTable( { "processing": true, "serverSide": true, "ajax": "${contextPath}/admin/getNextPageData/"+pageNo+"/"+10, "columns": [ { "data": "propertyId" }, { "data": "propertyname" }, { "data": "propertyType"...

Server Side Pagination with jQuery Data Tables plugin


jquery,spring-mvc,datatables
How can I achieve server side pagination using data table? Currently, on load of page I am initializing the data table & filling the table with Data (JSON) coming from database via Java Spring controller. I am making an Ajax call by passing search criteria in query string. Since we...

Spring, Java : Passing Generic object List as return type


java,spring,spring-mvc,generics,casting
I am working on a Spring-MVC application in which depending upon the mode set by the user, I have to return a List of either Object1 or Object2. Ideally, I can create two controller methods and send the List appropriately, but I would like to know is there any way,...

Send Mail using Spring MVC


spring,spring-mvc,spring-integration
I have a custom MailDto object in which I set the to,cc, bCc field and send it using RestTemplate to Spring MVC controller as below @RequestMapping(value = "/SendMail" ) public ResponseEntity<String> SendMail( @RequestBody MailMessageDto mailDto) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException From the controller I invoke the Gateway (Spring integration). The...

Spring service and Spring web app in one


spring,web-services,rest,spring-mvc,web
I'm making a Spring RESTFUL service and i wonder. Can I make a Spring RESTFUL service combine with a web app in a project. If it is possible, how to configure it? ....

unable to pass two lits to the jsp using apachi tiles


hibernate,jsp,spring-mvc,tiles
i am using spring mvc with Apache tile and hibernate.i pass tow lists to the jsp page.but it is print by but there's no any thing prints. my controller class as follows : if(userExists!=0){ model.addAttribute("Maintabs",new Maintab()); model.addAttribute("MaintabsList",loginService.listMaintabs()); model.addAttribute("Subtabs",new Subtab()); model.addAttribute("SubtabsList",loginService.listSubtab(userExists)); return "redirect:/Loginsucess"; }else{ model.addAttribute("error", "ERROR : invaliduser !,Please Try Again!");...

Not Able to Resolve View Using Spring boot


spring,spring-mvc,spring-boot
I have put all jsp on classpath in views folder. Folder structure is : src/main/resources/ src/main/resources/static/ src/main/resources/static/views/ src/main/resources/static/views/*.jsp src/main/resources/static/views/*.png I am able to retrieve images file from static folder. But When It comes to jsp I am getting following error. While hitting url:http://localhost:9001/login There was an unexpected error (type=Not Found,...

Dynamic fields thymeleaf list iteration


spring,spring-mvc,spring-boot,thymeleaf
I'm getting a really weird error ! while iterating on list thymeleaf identified index as a property of my bean and not an index value ! <div th:each="phoneStat : *{phones}"> <select th:field="*{phones[__${phoneStat.index}__].variety}" > <option> </option> </select> <div class=" input-field col s4" > <input th:field="*{phones[__${phoneStat.index}__].number}" th:id="${'phonenumber-'+ phones[__${phoneStat.index}__]}" type="text" class="validate" /> <label...

Mybatis skipping update the specific column if its parameter is null


spring-mvc,mybatis
I HAVE A FOLLOWING UPDATE QUERY IN A MAPPER <update id="updTest" parameterType="TestDTO"> <![CDATA[ UPDATE TEST_USER SET EMAIL = #{email, jdbcType=VARCHAR} , USERNAME = #{username, jdbcType=VARCHAR} , PASSWORD = #{password, jdbcType=VARCHAR} , DOMAIN = #{domain, jdbcType=VARCHAR} , COMPANY = #{company, jdbcType=VARCHAR} , DEPARTMENT = #{department, jdbcType=VARCHAR} , JOBTITLE = #{jobtitle, jdbcType=VARCHAR}...

Spring framework unable to start embedded container


java,spring,maven,spring-mvc,spring-boot
I'm following Spring in Action 4th Edition Chapter 5, but I'm stuck at the very first example. Here is my Eclipse Luna project structure: If I run this project as Spring Boot App, then it throws exceptions: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start...

REST-API Different Content-Type on Error Response


java,json,api,rest,spring-mvc
Since some weeks I'm working on an rest api using spring-mvc. The REST-API is working properly and I`m almost done until one last problem when it comes to error handling with specific error-objects. The REST-API is using JSON as format to serialize Java-Objects. When an error occurs during service-execution an...

JSON data binding in spring mvc


java,json,spring-mvc,data-binding
I have received json data from android application in my Spring MVC controller using following code . import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RequestHeader; @RequestMapping(method = RequestMethod.POST, produces = "application/json") public @ResponseBody String getMethod(@RequestHeader(value="json") String headerStr) { System.out.println("POST"); System.out.println(headerStr); return "hello"; } The output of...

Spring Security login with UserDetailsService and Java config


java,spring,spring-mvc,spring-security
I am trying to add login functionality with a database lookup with Spring Security, and I am really struggling. I want to look up the user by implementing the UserDetailsService interface. I have read a ton of documentation and Googled for hours, but I am still stuck. Most of the...

Form submit portlet with Spring MVC


java,jsp,spring-mvc,liferay,portlet
I'm trying to achieve a Liferay portlet of submit form using spring MVC. The model: package com.model; public class Person { String firstName; String middleName; public String getFirstName() { return this.firstName; } public String getMiddleName() { return this.middleName; } public void setFirstName(String firstName) { this.firstName=firstName; } public void setMiddleName(String middleName)...

GenericApplicationContext cannot be cast to WebApplicationContext : Spring Web Flow


java,spring,spring-mvc,classcastexception,spring-webflow-2
I'm trying to set up Spring Web Flow using only Java annotations in a Spring environment that also uses only Java annotations. However when I attempt to access my flow I get the following exception SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/forms] threw exception [Request processing failed;...

Logging all network traffic in Spring mvc


java,spring,spring-mvc,logging,slf4j
I have spring mvc application using RequestBody and ResponseBody annotations. They are configured with MappingJackson2HttpMessageConverter. I also have slf4j set up. I would like to log all json as it comes in and out from my controller. I did extend MappingJackson2HttpMessageConverter @Override public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage)...

Spring Resttemplate login fails


java,spring,spring-mvc,spring-security,csrf
after an update to spring-4.1.6 i'am not able to login to my rest services any more. I looked on different sides, but couldn't solve the problem... so i ask for help. Here is my my web.xml: <?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <!-- The definition of the...

Spring controller unit testing with spring-test-mvc is failing


java,spring,unit-testing,spring-mvc
I am learning unit testing of spring controller with EasyMock and Spring test framework. I have done a simple unit testing for my controller. import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import...