I have a Date variable in client side and I want to pass the Date variable to my controller at server side.
I have passed as a normal field and the date is defaulting to 01-01-0001 12:00:00 AM.
help me to convert the date field with the right format.
ASP.NET MVC expects the DateTime value to be in the format of Thread.CurrentLanguage. Please check what language you are using.
Its like that because users might enter a Date in a TextBox and the they would enter the format of their language.
Like Pieter said: an easy way is to use a string in this case.
Another way is to use
protected void Application_BeginRequest(object sender, EventArgs e)
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
}
in Global.Asax.
You can switch back to the language of the user in a filter after the ModelBinding happend:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string language = //find a way to get the language - I have it in the route
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(language);
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(language);
base.OnActionExecuting(filterContext)
}
This way has some risks, but I find it easier in lots of situations if modelBinding uses InvariantCulture (think of decimal values in the route, datetime in the route...)
I think it would be the easiest to pass the string representation of the date to the ASP.NET MVC action and attempt to parse it using DateTime.TryParse(..).
[HttpPost]
public ActionResult(string dateTimeString)
{
DateTime tempDateTime;
if(DateTime.TryParse(dateTimeString, out tempDateTime))
{
//Handle
}
}
Related
I want to know the location from httpServletRequest. Is there any way to do that?
I want to use one of the getters methods of httpServletRequest like getRemoteAddr()..
Thanks in advance.
This looks old post. For upcoming visitors adding this answer.
Try to use httpServletRequest.getLocale().getCountry() this will return country name as string.
Another option to get more precise values like ISO3 country code, ISO language codes use below methods
Pass the HttpServletRequest object to RequestContext(org.springframework.web.servlet.support.RequestContext)
RequestContext requestContext = new RequestContext(httpServletRequest);
String countryISO3 = requestContext.getLocale().getISO3Country();
It has many methods.
I am using react-datepicker to handle date inputs and when i submit my form to my Spring-Mvc API, the date field is a javacript date object like below
And it get mapped (and saved into database with JPA/Hibernate) without problem in my spring bean
public class FooBean {
...
public Date dateStart;
With my Controller
#PostMapping(value = "/foos")
public Integer saveFoos(#RequestBody FooBean bean) {
return fooService.saveFoo(bean);
}
and the date field in the entity is mapped like this
#Temporal(TemporalType.DATE)
#Column(name = "date_os_start")
private Date dateStart;
But when i try to read the value from the database and send it to the client with the same FooBean (dto/json), the date value is a number like this :
And I got this Error
Warning: Failed prop type: Invalid prop `selected` of type `Number` supplied to `DatePicker`,
expected instance of `Date`.
How can I get date from database in the same format as JavaScript date object ?
It seems like when the date is saved to your database it's converted into a unix timestamp.
You would have to convert the unix timestamp back into a JS date object before passing it to whichever react-datepicker component you are using.
const date = new Date(1555372800000)
I am working on a react application that has a java backend. The react frontend sends a URL request to a java web service controller, and within that webservice controller, the variable types are defined. Since a URL request is a string I’m having trouble dealing with non-string values. And since Javascript is not a strongly-typed language like Java I cannot definie variable types on the front end.
Web Request Example:
localhost:8080/filteredCSV.json?status=UNDER_ACTIVE_REVIEW,AUTHORIZED_BY_DWB,UNDER_CONSTRUCTION,CONSTRUCTION_COMPLETED&engineerEmail=null&issues=null&date=null
Web Service Controller:
#RequestMapping(value = "/filteredCSV.json")
#ResponseBody
public WebserviceResponse<?>filteredCSV(
#RequestParam(value="status") ArrayList status,
#RequestParam(value="engineerEmail") ArrayList engineerEmail,
#RequestParam(value="issues", required=false) Boolean issues,
#RequestParam(value="date", required=false) Local Date date){
return service.filteredCSV(status, engineerEmail, issues, date);
}
If the Boolean or Date values are null, then null is getting passed as a string which causes a TypeMismatch Error and the program stops. I do not appear to have a way to change the string to to a non-string null value once it hits the web service controller. I understand why this is occurring, but I am not sure if there is a way to work around it so that I can pass null as a value and not null as a string. Am I just screwed? Is there not a way to deal with this?
You're not sending null as a value, you're sending a string that contains the word 'null.
Send no value "" instead of the string value 'null'. This is what the #RequestParameter is expecting when it should be ignoring a parameter.
#RequestParameter docs
If you can't edit the javascript you still have some options ... what spring is really doing there is data binding values from the http request to instances of Java variables. You can override or bypass this as you need. (This sort of approach is the 'old' way of doing this and the very problem spring annotations hope to solve).
#RequestMapping(value = "/filteredCSV.json")
#ResponseBody
public WebserviceResponse<?>filteredCSV(HttpRequest request){
String date = request.getParameter('date');
// Convert date if not 'null' here, and so on
}
I like the suggestion posted by #zmf, However If want find other work arounds. Please refer some of the approaches I think will work:
Solution 1: You can introduce a filter, and parse all the request parameters as string. When you encounter null as string do not send the param further, it will be considered as null at controller level.
Solution 2: Replace RequestParam type like Date, Boolean with String. You can then process accordingly.
I have a webapi function that retrieves data from a T-SQL database using SqlConnection, SqlCommand etc. I get a DataTable which I convert to a data structure using
var foobars = ColumnMapping.DataTableToObjectList<Foobar>(dt)
The Foobar class contains DateTime fields.
When I return my foobars from the webapi method, those datetimes will be sent over the network in the following format:
2016-10-12T12:00:00
which seems to be a timezone-less datetime. AngularJS will treat it as 12:00, and javascript´s Date.getHours() will return 14 (I am in the +2 timezone).
If I do this operation before I return from my Web api method:
foobar.d = foobar.d.ToUniversalTime();
the string will get an additional Z
2016-10-12T12:00:00Z
and both AngularJS and javascript will agree about which time that is (12:00, which is also the indended time).
If I do
foobar.d = foobar.d.DateStart.ToLocalTime();
the string will be
2016-10-12T14:00:00+02:00
and AngularJS and javascript both reports it is 14:00, two hours more than the intended time).
From this, I conclude that
A DateTime object can be timezoneless, but if you try to convert it, it will be treated as if it was UTC.
ColumnMapping.DataTableToObjectList creates structures where DateTime objects are timezoneless.
I do not want to "patch" every DateTime object, that would be an error source (that would involve calling ToUniversalTime() on every DateTime object).
Can I specify a locale when I call ColumnMapping.DataTableToObjectList?
In webapi you can configure your JsonFormatter to serialize your datetimes how you want:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
}
}
This way you don't have to do it for every datetime, assuming I'm understanding your issue...
I use spring, spring restcontroller, I have an enum in Java.
public enum PaymentModeEnum {
CASH, DEBIT, CHECK, CREDITCARD;
}
How to get enum value in javascript and to to send enum value to java?
If you are trying to set/get enum value using Javascript REST call to Spring API-
Enum name can be set using path variable or query string. Below example is for query string.
//https://localhost:8444/getByEnumVal?enumVal1=CASH
#RequestMapping(value = "/getByEnumVal", method = RequestMethod.GET)
public String setEnum(
#RequestParam(value="enumVal1", required=false) String enumVal1) {
Service.methodcall(enumVal1);
...
}
Enum value can be returned as JSON directly, or by setting it in POJO
#RequestMapping(value = "/getEnumVal", method = RequestMethod.GET)
public String getEnumVal() {
return PaymentModeEnum.CASH;
}
From your question I assume you have a frontend with some javascript that calls a REST endpoint written in Java, using Spring.
I don't know how to share an enum between javascript and Java (they are different languages), but you can either send its ordinal value, or the name of the enum value. I would go with the latter.
This way you can just get it as a query parameter in your endpoint. Like so:
#RequestMapping(
path = some/path
method = GET)
public SomeTypeAsResponse method(#RequestParam(name = "payment_mode") PaymentModeEnum paymentMode) {
...
}
1.For extracting Enum in JavaScript do something like below:
var enumvar = document.inputId.Packages.com.MyClass$MyEnumYesNo.YES
2.For sending Enum from Javscript to RestController, pass it as a String directly and then map it as a Enum in the methods input parameter in Controller.