http 400 bad request when using date - Spring MVC, pickadate.js - spring

I have a simple form with 3 fields, one containing a pickadate(), the other a pickatime() and the last a simple number.
When I try to post my form, I get a bad request error.
Request dedails
Request URL:http://localhost:8080/CapTheater/admin/addProjection
Request Method:POST
Status Code:400 Mauvaise RequĂȘte
Request Headers
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/
Accept-Encoding:gzip,deflate,sdch
Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
Cache-Control:max-age=0
Connection:keep-alive
Content-Length:39
Content-Type:application/x-www-form-urlencoded
Cookie:JSESSIONID=EA0DDBF444BC5A4CA416715D72FF9D71
Host:localhost:8080
Origin:http://localhost:8080
Referer:http://localhost:8080/CapTheater/showMovie/1
User-Agent:Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36
Form Data
day:2014-01-01
date:09:30
place_nbr:0
Response Headers
Connection:close
Content-Length:986
Content-Type:text/html;charset=utf-8
Date:Mon, 30 Dec 2013 23:35:24 GMT
Server:Apache-Coyote/1.1
Here is the form :
<form:form method="post" action="../admin/addProjection" id="add_movie_form">
<form:label id="dayLabel" path="day">Date : </form:label>
<form:input type="text" id="dayInput" path="day" />
<form:label id="startLabel" path="date">Start : </form:label>
<form:input type="text" id="startInput" path="date" />
<form:label id="sizeLabel" path="place_nbr">Steats availables :
<form:input type="text" id="sizeInput" path="place_nbr" />
<input type="submit" class="btn btn-primary"value="Save" />
</form:form>
<script type="text/javascript">
$("#tabs").tabs();
$("#dayInput").pickadate({
format : 'yyyy-mm-dd',
min : new Date()
});
$("#startInput").pickatime({
format : 'HH:i',
min: [8, 0],
max: [22, 30]
});
</script>
The controller
#RequestMapping(value = "admin/addProjection", method = RequestMethod.POST)
public String addProjection(
#ModelAttribute("command") final Projection projection,
final ModelMap model)
{
projectionDao.save(projection);
return "/showMovie/" + projection.getMovieId() + "#tabs-4";
}
Finally, in the bean
public class Projection implements Comparable<Projection>
{
#DateTimeFormat(pattern = "yyyy-MM/dd")
private Date day;
public Date getDay()
{
return day;
}
public void setDay(Date day)
{
this.day = day;
}
}
Thank you :)

Related

Post HiddenField values to controller with model .net core 6

var tags = M.Chips.getInstance($('.chips')).chipsData;
var sendTags = JSON.stringify(tags, null, 2);
$('#Tags').val(sendTags);
with the above method I stored chips data to hiddenfileds with .onSubmit() method. But at controller level, couldn't get them.
I'am expecting hiddenfiled chips data at contorller level along with other model property.
But at controller level, couldn't get them.
If you want to get the hiddenfileds, I have a suggestion like below:
You can create a hidden input, and use name attribute to bind the data.
<input id="Tags" name="tags" type="hidden" />
The demo like below, you can refer to it:
Privacy view:
<form asp-action="Privacy" method="post">
<input id="Tags" name="tags" type="hidden" />
<input type="submit" value="submit"/>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
var tags = {
'x1': 1,
'x2': 2
}
var sendTags = JSON.stringify(tags, null, 2);
$('#Tags').val(sendTags);
</script>
Controller:
public IActionResult Privacy()
{
return View();
}
[HttpPost]
public IActionResult Privacy( string tags )
{
return View();
}
result:

Spring MVC: Required String parameter 'code is not present

I'm getting the following error:
Required String parameter 'code' is not present.
I want to retrieve the person's code when I enter the email and password data, i.e. I have the following query:
SELECT code FROM authentication WHERE email=? AND password=?
Controller:
#RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView customerLogin(#RequestParam("code") String code,#RequestParam("email") String email, #RequestParam("password") String password) {
ModelAndView mv = new ModelAndView();
Customer customer = new Customer();
customer.setCode(code);
customer.setEmail(email);
customer.setPassword(password);
String name = customerDao.loginCustomer(customer);
String cf=customer.getCode();
if (name != null) {
mv.setViewName("redirect:/update/" +cf);
} else {
mv.addObject("msg", "Invalid user id or password.");
mv.setViewName("login");
}
return mv;
}
Dao:
#Override
public String loginCustomer(Customer customer) {
String sql = "SELECT code FROM authentication WHERE email=? AND password=?";
List<String> customers = jdbcTemplate.queryForList(sql, new Object[] {customer.getCode(), customer.getEmail(), customer.getPassword() },String.class);
if (customers.isEmpty()) {
return null;
} else {
return customers.get(0);
}
}
login.jsp
<%# page isELIgnored="false"%>
<html>
<head>
<title></title>
</head>
<body>
<form action="login" method="post">
<pre>
Email: <input type="text" name="email" />
Password: <input type="password" name="password" />
<input type="submit" value="Login" />
</pre>
</form>
${msg}
</body>
</html>
The reason is obvious: you do not pass code parameter into your controller method:
#RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView customerLogin(#RequestParam("code") String code,
#RequestParam("email") String email, #RequestParam("password") String password) {
}
In order to solve this issue, you have two ways:
a. make code not required, thus we need to add required=false in controller method:
#RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView customerLogin(#RequestParam(value = "code", required=false) String code,
#RequestParam("email") String email, #RequestParam("password") String password) {
}
b. add code field in your html form:
<%# page isELIgnored="false"%>
<form action="login" method="post">
<pre>
Code: <input type="text" name="code" />
Email: <input type="text" name="email" />
Password: <input type="password" name="password" />
<input type="submit" value="Login" />
</pre>
</form>
${msg}
That exception happening at controller level. You are not passing the code Param in the URL.

Custom log in box with Spring security and Ajax

I have a login box which is a popup on my site, I am having some issues with configuring spring security and the AJAX call to login and authenticate. I am unsure if I've set it up correctly, I'm currently getting a 401() error and reaching Critical Error of the login.js, which is unauthorized access as it stands and the /user/login method not being called.... ! Just a basic idea of how an AJAX login and authentication process should be handled in spring security would be great, including the security config.
THE HTML
<form onSubmit="login()" id="notifyMe" method="POST" role="form">
div class="form-group">
<div class="controls">
<!-- Field -->
<input type="text" id="username" name="username" placeholder="Enter your username" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Click here to write your username'" class="form-control email srequiredField" />
<input type="password" id="password" name="password" placeholder="Enter your password" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Click here to write your password'" class="form-control email srequiredField" />
<!-- Spinner top left during the submission -->
<i class="fa fa-spinner opacity-0"></i>
<!-- Button -->
<button id="login-btw" class="btn btn-lg submit">LOG IN</button>
<div class="clear"></div>
</div>
</div>
</form>
THE AJAX
function login() {
console.info("Attempting to authenticate");
$.ajax({
type: 'POST',
url: '/user/login',
data: $('#notifyMe').serialize(),
cache: false,
dataType: "json",
contentType: "application/json;charset=utf-8",
beforeSend:function(xhr) {
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
},
crossDomain: false,
success: function (data) {
var response = jQuery.parseJSON(data);
if (response == true) {
$(".message").html('<p class="notify-valid">Logging in...</p>').fadeIn();
window.location.reload();
console.info("Authentication Success!");
}
else {
console.error("Unable to login");
console.log(response);
$(".message").html('<p class="notify-valid">Your log in details are incorrect. Please try again.</p>').fadeIn();
}
},
error: function (data) {
console.error("Critical error");
console.log(data);
}
});
SPRING SECURITY CONFIG
#Configuration
#EnableWebSecurity
public class SpringSecurityConfigurer extends WebSecurityConfigurerAdapter{
//Used in context with custom log in form (no /j_spring_security_check)
#Autowired
private CustomAuthenticationProvider cap;
#Autowired
private AjaxAuthenticationSuccessHandler successHandler;
#Autowired
private AjaxAuthenticationFailureHandler failureHandler;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(cap);
}
#Bean(name = "requestCache")
public RequestCache getRequestCache() {
return new HttpSessionRequestCache();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
//CSS FILES AND IMAGES
.antMatchers("/fonts/**", "/css/**", "/img/**", "/js/**", "/admin/css/**", "/admin/img/**", "/admin/js/**" ).permitAll()
//PAGES FOR ALL PEOPLE
.antMatchers("/user/login", "/", "/user/**", "/register/**").permitAll()
//PAGES FOR ADMIN
.antMatchers("/admin/").access("hasAuthority('ROLE_ADMIN')")
.antMatchers("/admin/**").access("hasAuthority('ROLE_ADMIN')")
//PAGES FOR USERS
.antMatchers("/event/**").access("hasAuthority('ROLE_USER')")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/")
.loginProcessingUrl("/user/login")
.failureHandler(failureHandler)
.successHandler(successHandler)
.and()
.csrf().disable()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/user/logout"))
.logoutSuccessUrl("/")
.and().exceptionHandling().accessDeniedPage("/")
//.authenticationEntryPoint(ajaxEntryPoint);
;
}
}
Response header
pragma: no-cache
date: Sun, 05 Nov 2017 11:08:12 GMT
x-content-type-options: nosniff
x-frame-options: DENY
content-type: application/json;charset=UTF-8
cache-control: no-cache, no-store, max-age=0, must-revalidate
transfer-encoding: chunked
x-xss-protection: 1; mode=block
expires: 0
js console image

Django Rest Framework - DELETE ajax call failure due to incorrect CSFR token

I'm trying to use the django rest framework to to easily handle some models as restful resources.
this is the code that I have:
Django: 1.7.1
Django REST Framework: 2.4.4
jQuery: 2.1.1
# models.py
class DocumentNodeTemplate(MPTTModel):
"""
"""
document_template = models.ForeignKey(
DocumentTemplate,
related_name="nodes",
verbose_name="Document template"
)
parent = TreeForeignKey(
'self',
null=True, blank=True,
related_name='children'
)
section_template = models.ForeignKey(
'SectionTemplate',
related_name="node_templates",
verbose_name="Section template"
)
def __unicode__(self):
return self.section_template.name
def get_class(self):
type = self.section_template.type
return import_string(type)
# serializers.py
class DocumentNodeTemplateSerializer(serializers.ModelSerializer):
class Meta:
model = DocumentNodeTemplate
fields = ('document_template', 'parent', 'section_template')
# views.py
class DocumentNodeTemplateAPIView(CreateAPIView, RetrieveUpdateDestroyAPIView):
queryset = DocumentNodeTemplate.objects.all()
serializer_class = DocumentNodeTemplateSerializer
<!-- HTML (section - admin's change form customization)-->
<fieldset class="module aligned">
<h2>{{ node_fieldset_title }}</h2>
<div class="form-row document-nodes">
<div
style="width: 100%; min-height: 450px;" id="general-container"
data-document_model="{{ document_model }}"
>
<form id="changelist-form" action="" method="post" novalidate>{% csrf_token %}
<div id="tree-container">
<div id="tree"
data-url="{{ tree_json_url }}"
data-save_state="{{ app_label }}_{{ model_name }}"
data-auto_open="{{ tree_auto_open }}"
data-autoescape="{{ autoescape }}"
>
</div>
<div class="add-node">
<a href="/admin/document/{{ model_name }}/add/?_to_field=id&document_id={{ object_id }}" class="add-another"
onclick="return showCustomAddAnotherPopup(event, this);">
<img src="/sitestatic/admin/img/icon_addlink.gif" width="10" height="10"
alt="Add another node"> Add another node
</a>
</div>
<ul class='node-custom-menu'>
<li data-action="delete">Delete node</li>
</ul>
</div>
</form>
<div id="node-container">
<h3 id="node-name"></h3>
<br/>
<div id="node-content"></div>
</div>
</div>
</div>
</fieldset>
// javascript
var performCRUDaction = function(action, api_url, callback) {
var csfrtoken = $('input[name="csrfmiddlewaretoken"]').prop('value');
var _reloadNodeTree = function () {
window.nodeTree.tree('reload');
}
var _performAction = function () {
jQuery.ajax({
type: actionType,
url: api_url,
data: { 'csrfmiddlewaretoken': csfrtoken },
success: function () {
console.log("action " + action + " successfully performed on resource " + api_url);
_reloadNodeTree();
},
error: function () {
console.log("action " + action + " failed on resource " + api_url);
}
});
}
var actionType,
documentModel = null;
var nodeDataObj = {};
switch (action) {
case "delete":
actionType = "DELETE";
break;
case "update":
actionType = "PUT";
break;
case "create":
actionType = "POST";
break;
case "retrieve":
actionType = "GET";
break;
}
_performAction();
callback();
}
I didn't posted all the code, anyway when that ajax call is triggered, I obtain a 403 error:
// headers
Remote Address:127.0.0.1:8050
Request URL:http://127.0.0.1:8050/api/documentnodetemplates/46
Request Method:DELETE
Status Code:403 FORBIDDEN
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-GB,en;q=0.8,en-US;q=0.6,it;q=0.4
Cache-Control:no-cache
Connection:keep-alive
Content-Length:52
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:djdt=hide; sessionid=x5cw6zfifdene2p7h0r0tbtpkaq7zshq; csrftoken=NyMqLlKxeeAdc4Eq2nFpFOebh0SUBBVY
Host:127.0.0.1:8050
Origin:http://127.0.0.1:8050
Pragma:no-cache
Referer:http://127.0.0.1:8050/admin/document/documenttemplate/1/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36
X-CSRFToken:NyMqLlKxeeAdc4Eq2nFpFOebh0SUBBVY
X-Requested-With:XMLHttpRequest
Form Dataview sourceview URL encoded
csrfmiddlewaretoken:NyMqLlKxeeAdc4Eq2nFpFOebh0SUBBVY
Response Headersview source
Allow:GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS
Content-Type:application/json
Date:Thu, 20 Nov 2014 09:52:31 GMT
Server:WSGIServer/0.1 Python/2.7.6
Vary:Accept, Cookie
X-Frame-Options:SAMEORIGIN
// response
{"detail": "CSRF Failed: CSRF token missing or incorrect."}
Anybody experienced the same or similar problem and can help?
Thanks
LuKe
You should delete all your Cookies and other site and plug-in data and Cached images and files by going into history tab and then clear browsing data...ANother option is to use #csrf_exempt decorator with your class based views..

MVC 3 - Entity Framework - Post data from ajax-invoked Partial View

I have a problem with the binding of a complex model from a View that has updatable content, first things first, entites:
public partial class Diagnosis
{
public Diagnosis()
{
this.DiagZones = new HashSet<DiagZone>();
...
}
public int diagnosisid { get; set; }
public int playerid { get; set; }
public int userid { get; set; }
...
public virtual ICollection<DiagZone> DiagZones { get; set; }
}
My DiagZones Collection is the intermediate table between Diagnosis and Zones but it exist in my Model cause has more fields than the id's.
I have a Select control where you can select and unselect the Zones, when onchange fires, I Get a Partial View with an ajax call.
The code:
EditDiagnosis.cshtml
#model Gfire.Models.DiagnosisViewModel
<h2>
#ViewBag.playername</h2>
#using (Html.BeginForm("EditDiagnosis", "Diagnosis", FormMethod.Post))
{
#Html.HiddenFor(d => d.Diagnosis.diagnosisid)
<table>
...
</table>
<table>
<tr>
<td>
Zones:
</td>
<td>
#Html.ListBoxFor(d => d.SelectedZones, new SelectList(Model.Zones, "zoneid", "description"), new
{
style = "width:305px;",
onchange = "QualityMovement(this);",
id = "lbZone",
#class = "chzn-select"
})
</td>
<td>
...
</td>
</tr>
</table>
<div id="qualitymovement">
#Html.Partial("_QualityMovement", Model.Diagnosis.DiagZones)
</div>
<div>
<input type="submit" value="Save" />
&nbsp | &nbsp #Html.ActionLink("Cancel", "IndexDiagnosisPlayer", new { playerid = ViewBag.playerid })
</div>
}
Partial View (_QualityMovement.cshtml):
#model List<Gfire.Domain.Entities.Diagnosis.DiagZone>
#if (Model.Count() != 0)
{
<table>
#foreach (var dz in Model)
{
<tr>
<tr>
<td>
Flex:
</td>
<td>
#Html.TextBoxFor(d => dz.flex))
</td>
</tr>
</tr>
}
</table>
}
The Ajax.Get call:
<script type="text/javascript" language="javascript">
function JointBalance(item) {
...
$.ajax({
url: '#Url.Action("GetJointBalances", "Diagnosis")',
data: arrayToParamObject('zonesid', items),
contentType: "application/json; charset=utf-8",
success: function (data) {
// Successful requests get here
$("#jointbalance").html(data);
$("#jointbalance").fadeIn('slow');
},
type: "GET",
datatype: "json"
});
...
}
</script>
In server I have a Method that initialize a new list of DiagZones and update correctly the EditView.cshtml.
The problem comes when I try to Submit the complete Diagnosis object with all the fields and the list of DiagZones but my method:
[HttpPost]
public ActionResult EditDiagnosis(DiagnosisViewModel DiagnosisViewModel)
{
if (ModelState.IsValid)
{
// Save the model
...
return RedirectToAction("IndexDiagnosisPlayer", new { playerid = SessionHelper.Player.playerid });
}
else
{
return View("EditDiagnosis", new { diagnosisid = DiagnosisViewModel.diagnosisid });
}
}
My Model has empty the DiagnosisViewModel.DiagZones list.
I've tried to use EditorFor, pass the complete model to the partial View, add several forms... but it was useless, how can I bind that list to my model?
Thanks in advance.
UPDATE
Here is what the server side action is expecting:
[HttpGet]
public ActionResult GetJointBalances(int[] zonesid) { ... }
GET ajax request data looks like:
Request URL:http://localhost/Gfire.WebUI/Diagnosis/GetQualityMovement?zonesid=47
Request Method:GET
Status Code:200 OK
Request Headersview source
...
Connection:keep-alive
Content-Type:application/json; charset=utf-8
...
Referer:http://localhost/Gfire.WebUI/Diagnosis/EditDiagnosis?diagnosisid=0&playerid=23
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.152 Safari/537.22
X-Requested-With:XMLHttpRequest
Query String Parametersview sourceview URL encoded
zonesid:47
I found a temporal solution, not the best of course, but I thougth it would help to understand what I was trying to do and how to solve this.
The problem, as Justin said, was binding the list<DiagZones> to main model, the Diagnosis object, following the posts of this:
ASP.Net MVC4 bind a "create view" to a model that contains List
I understand a little bit of the binding functionality, with that in mind I code my new PartialView _QualityMovement.cshtml:
#model List
#if (Model.Count() != 0)
{
<table>
#foreach (var dz in Model)
{
<tr>
<tr>
<td>
Flex:
</td>
<td>
Html.TextBox("Diagnosis.DiagZones[" + i + "].ext", Model[i].ext)
</td>
</tr>
</tr>
}
</table>
}
It's a bad solution but at least I had my Model binded in server side.
The problem is the abstraction made by the entity framework to my entities, as an ICollection so I cannot iterate as a List and found myself "casting" everywhere.
I suppose a better approach should be a CustomBinder to retrieve the data in the Request or type it in a neater and understandable way.
Thanks Justin for all the help you gave me.

Resources