I'm trying to upload multiple files to springboot server from angular but I don't know why I'm getting error.But in postman the code is working fine and I'm able to upload files and output format.
I'm getting this error in browser
HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "OK", url: 'http://localhost:8080/file/Upload', ok: false, …}
Error in backend terminal:
DefaultHandlerExceptionResolver : Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'fileN' is not present]
springboot restapi:
#postMapping(value="/Upload")
public ResponseEntity<List<String>> uploadFiles(#RequestParam ("fileN")List<MultipartFile> multipartFiles,#RequestParam("fileFormat")String id) throws IOException, FOPException, TransformerException{
List<String> filenames = new ArrayList<>();
try{
for(MultipartFile file : multipartFiles){
String filename = StringUtils.cleanPath(file.getOriginalFilename());
Path fileStorage = get(DIRECTORY, filename).toAbsolutePath().normalize();
copy(file.getInputStream(), fileStorage, REPLACE_EXISTING);
filenames.add(filename);
}
fileConversion.Convert(id);
}
catch (Exception e){
e.printStackTrace();
}
return ResponseEntity.ok().body(filenames);
user service:
constructor(private http: HttpClient){}
uploadFile(formData: FormData): Observable<any>{
const headerDist = {
'Access-Control-Allow-Origin': '*';
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',
'access-control-allow-credentials':'true'
'Content-Type': 'multipart/form data; boundary=Inflow'
}
const requestOptions = {
headers: new HttpHeaders(headerDist),
};
return this.http.post('http://localhost:8080/file/Upload',formData,requestOptions);
}
appcomponent:
onSubmit(){
const formData = new formData();
formData.append('fileN', this.angForm.get('file1').value);
formData.append('fileN', this.angForm.get('file2').value);
formData.append('fileN', this.angForm.get('file3').value);
formData.append('fileN', this.angForm.get('fileFormat').value);
this.userService.uploadFile(formData).subscribe (
(res) => console.log(res),
(err) => console.log(err)
)};
html:
<h2 id="zone" xmlns="http://www.w3.org/1999/html">File Conversions</h2>
<form [formGroup]="angForm" enctype="multipart/form-data" (ngSubmit)="onSubmit()" >
<div class="main">
<div class="classOne">
<div class="form-two">
<input type="file" class="file-input" formControlName="file1" id="ixml" value="" accept="xml/*" required (change)='uploadF($any($event.target).files)' #open>
<div class="file-upload">
<p class="para-tag">Input XML :</p>
<button mat-raised-button color="primary" class="upload-btn" (click)="open.click()">Choose File</button>
</div>
</div>
</div>
<div *ngIf="angForm.controls['file1'].invalid" class ="alert alert-danger">
<div *ngIf="angForm.controls['file1'].errors.required"></div>
</div>
<div class="classTwo">
<div class="form-two">
<input type="file" class="file-input" formControlName="file2" id="udtd" value="" accept="dtd/*" required (change)="uploadFile($event.target.files)"#ele>
<div class="file-upload">
<p class="para-tag">Upload DTD : </p>
<button mat-raised-button color="primary" class="upload-btn" (click)="ele.click()">Choose File</button>
</div>
</div>
</div>
<div *ngIf="angForm.controls['file2'].invalid" class ="alert alert-danger">
<div *ngIf="angForm.controls['file2'].errors.required"></div>
</div>
<div class="classThree">
<div class="form-two">
<input type="file" class="file-input" formControlName="file3" id="uxsl" value="" accept="xsl/*" required (change)="uploading($event.target.files);"#choose>
<div class="file-upload">
<p class="para-tag">Upload XSL : </p>
<button mat-raised-button color="primary" class="upload-btn" (click)="choose.click()">Choose File</button>
</div>
</div>
</div>
<div *ngIf="angForm.controls['file3'].invalid" class ="alert alert-danger">
<div *ngIf="angForm.controls['file3'].errors.required"></div>
</div>
<div class="classFour">
<p class="para-tag-two">Choose Your Output Format :</p>
<div>
<input type="radio" id="pdf" value="pdf" name="fileFormat" formControlName="fileFormat">
<label for="pdf">PDF</label><br>
<input type="radio" id="ps" value="ps" name="fileFormat" formControlName="fileFormat">
<label for="ps">PostScript</label><br>
<input type="radio" id="png" value="png" name="fileFormat" formControlName="fileFormat">
<label for="png">PNG</label><br>
<input type="radio" id="txt" value="txt" name="fileFormat" formControlName="fileFormat">
<label for="txt">Text</label><br>
<input type="radio" id="print" value="print" name="fileFormat" formControlName="fileFormat">
<label for="print">Print</label><br><br>
</div>
</div>
<div *ngIf="angForm.controls['fileFormat'].invalid" class ="alert alert-danger">
<div *ngIf="angForm.controls['fileFormat'].errors.required"></div>
</div>
<div class="submit">
<button style="width:100px;" type="submit" [disabled]="angForm.invalid" mat-raised-button color="warn"disabled="true" >Submit</button>
</div>
</div>
</form>
Related
I am trying to save an image inserted by an <input> field in a form by the user to a folder named imgs under the WEB-INF folder and store in the table column of the product the path of that photo so i can later display them in a products page for my online shop.
I don't know how to send the image to the java file (using jdbc server) so i can save it and also how i can save it. I have researched online but I have not fount what i am looking for. Below is my .jsp file.
<body>
<%
if(request.getParameter("btn") != null){
String name = request.getParameter("name");
String description = request.getParameter("description");
double price = Double.valueOf( request.getParameter("price"));
String brand = request.getParameter("brand");
String type = request.getParameter("type");
int quantity = Integer.parseInt( request.getParameter("quantity"));
File picture =
Client client = Client.create();
WebResource webResource =client.resource("...link.../"+name+"/"+description+"/"+price+"/"+brand+"/"+type+"/"+quantity+"/"+picture);
ClientResponse myresponse = webResource.accept("text/plain").get(ClientResponse.class);
}
%>
<div class="p-5" >
<h1 id="title" class="d-flex justify-content-center" style="font-size:4rem;">Edit your Profile</h1>
<form class="container " method="post">
<div class="form-row">
<div class="form-group col-6">
<label for="name">Product name:</label>
<input class="form-control" type="text" name="name"><br>
</div >
</div>
<div class="form-row">
<div class="form-group col-6">
<label for="description">Description:</label>
<textarea class="form-control" name="description" cols="40" rows="5"></textarea><br>
</div >
</div>
<div class="form-row">
<div class="form-group col-3">
<label for="price">Price:</label>
<input class="form-control" type="number" name="price"><br>
</div >
<div class="form-group col-6">
<label for="brand">Product brand:</label>
<input class="form-control" type="text" name="brand"><br>
</div >
</div>
<div class="form-row">
<div class="form-group col-6">
<label for="type">Product type(running, walking, casual ,etc...):</label>
<input class="form-control" type="text" name="type"><br>
</div >
<div class="form-group col-6">
<label for="quantity">Available quantity:</label>
<input class="form-control" type="text" name="quantity"><br>
</div >
</div>
<div class="form-row">
<div class="form-group col-6">
<label for="picture">Product picture:</label>
<input class="form-control" type="file" name="picture"><br>
</div >
</div>
<button type="submit" name="btn">Sign in</button>
</form>
</div>
</body>
Here I have a form that accepts package details and I have added dynamic form fields to get all the itineraries of that package. Please comment on what I must add to my question to make it more clear.
insert function
#PostMapping("/save-tour-package")
public String saveTourPackage(#ModelAttribute("tourPackage") TourPackage tourPackage, #RequestParam String[] day, #RequestParam String[] itinerary_title, #RequestParam String[] itinerary_description, #RequestParam String[] itinerary_altitude) {
// save package to database
TourPackage tour = tourPackageService.saveTourPackage(tourPackage);
for (int i = 0; i < day.length; i++) {
Itinerary ite = new Itinerary();
ite.setPackages(tour);
ite.setDay(day[i]);
ite.setTitle(itinerary_title[i]);
ite.setDescription(itinerary_description[i]);
ite.setAltitude(itinerary_altitude[i]);
itineraryRepo.save(ite);
}
return "redirect:/";
}
save service implementation
#Override
public TourPackage saveTourPackage(TourPackage tourPackage) {
return this.tourPackagesRepo.save(tourPackage);
}
view file
<div layout:fragment="content">
<div class="container">
<form th:action="#{/save-tour-package}" th:object="${tourPackage}" method="POST">
<div class="form-group">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" th:field="*{title}" placeholder="Title">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" id="description" th:field="*{description}"
placeholder="Description"></textarea>
</div>
<div class="row">
<div class="col-3">
<div class="form-group">
<label for="geography">Geography</label>
<input type="text" class="form-control" id="geography" th:field="*{geography}"
placeholder="Geography">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="location">Location</label>
<input type="text" class="form-control" id="location" th:field="*{location}"
placeholder="Location">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="difficulty">Difficulty</label>
<input type="text" class="form-control" id="difficulty" th:field="*{difficulty}"
placeholder="Difficulty">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="altitude">Altitude</label>
<input type="text" class="form-control" id="altitude" th:field="*{altitude}"
placeholder="Altitude">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="religion">Religion</label>
<input type="text" class="form-control" id="religion" th:field="*{religion}"
placeholder="Title">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="ethnic_people">Ethnic People</label>
<input type="text" class="form-control" id="ethnic_people" th:field="*{ethnic_people}"
placeholder="Ethnic People">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="accommodation">Accommodation</label>
<input type="text" class="form-control" id="accommodation" th:field="*{accommodation}"
placeholder="Title">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="transportation">Transportation</label>
<input type="text" class="form-control" id="transportation" th:field="*{transportation}"
placeholder="Transportation">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="minimum_pax">Minimum Pax</label>
<input type="text" class="form-control" id="minimum_pax" th:field="*{minimum_pax}"
placeholder="Minimum Pax">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="price">Price</label>
<input type="text" class="form-control" id="price" th:field="*{price}" placeholder="Price">
</div>
</div>
</div>
<div class="row">
<div class="col-2">Day</div>
<div class="col-3">Title</div>
<div class="col-3">Description</div>
<div class="col-3">Altitude</div>
<div class="col-1"></div>
</div>
<div class="row delete-field append-new-field">
<div class="col-2">
<input type="text" class="form-control" name="day">
</div>
<div class="col-3">
<input type="text" class="form-control" name="itinerary_title">
</div>
<div class="col-3">
<input type="text" class="form-control" name="itinerary_description">
</div>
<div class="col-3">
<input type="text" class="form-control" name="itinerary_altitude">
</div>
<div class="col-1">
<i class="fas fa-minus-circle"></i>
</div>
</div>
Add Fields
<div class="form-group">
<button type="submit" class="btn btn-info col-2"> Save Tour Package</button>
</div>
</div>
</form>
</div>
</div>
<div layout:fragment="after-script">
<script>
function addItineraryFields() {
var html = '<div class="row delete-field"><div class="col-2">\n' +
' <input type="text" class="form-control" name="day">\n' +
' </div>\n' +
' <div class="col-3">\n' +
' <input type="text" class="form-control" name="itinerary_title">\n' +
' </div>\n' +
' <div class="col-3">\n' +
' <input type="text" class="form-control" name="itinerary_description">\n' +
' </div>\n' +
' <div class="col-3">\n' +
' <input type="text" class="form-control" name="itinerary_altitude">\n' +
' </div>' +
' <div class="col-1">\n' +
' <i class="fas fa-minus-circle"></i>\n' +
' </div></div>';
$('.append-new-field').append(html);
}
$(document).on('click', '.delete-row', function(e) {
$(this).closest('.delete-field').remove();
return false;
});
</script>
</div>
This is my Controller:
package br.com.apptrechos.torcidapremiada.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties.User;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import br.com.apptrechos.torcidapremiada.model.Beneficio;
import br.com.apptrechos.torcidapremiada.model.Imovel;
import br.com.apptrechos.torcidapremiada.model.Partida;
import br.com.apptrechos.torcidapremiada.repository.Imoveis;
import br.com.apptrechos.torcidapremiada.repository.Partidas;
import br.com.apptrechos.torcidapremiada.service.BeneficioService;
import br.com.apptrechos.torcidapremiada.service.exception.DadoJaCadastradoException;
#Controller
#RequestMapping("/beneficio")
public class BeneficioController {
#Autowired
private Partidas partidas;
#Autowired
private Imoveis imoveis;
#Autowired
private BeneficioService beneficioService;
#PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody ResponseEntity<?> validarBeneficio(#RequestBody Long codigo, #AuthenticationPrincipal User user) {
try {
Imovel imovel = this.imoveis.findByCodigoIn(codigo);
Partida proximaPartida = this.partidas.buscarProximaPartida();
Beneficio beneficio = new Beneficio(proximaPartida, user.getName(), imovel, imovel.getContribuinte());
this.beneficioService.salvar(beneficio);
} catch (DadoJaCadastradoException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
return ResponseEntity.ok().build();
}
}
My Javascript and my view:
var TorcidaPremiada = TorcidaPremiada || {};
TorcidaPremiada.ImovelConcederBeneficio = (function() {
function ImovelConcederBeneficio() {
this.validaBeneficioBtn = $('.js-valida-beneficio-btn');
this.containerMensagemErro = $('.js-container-mensagem-erro');
this.containerMensagemSucesso = $('.js-container-mensagem-sucesso');
}
ImovelConcederBeneficio.prototype.iniciar = function() {
this.validaBeneficioBtn.on('click', onBotaoValidaBeneficioClick.bind(this));
}
function onBotaoValidaBeneficioClick(event) {
var botao = $(event.currentTarget);
var codigo = botao.data('codigo');
var url = botao.data('url');
$.ajax({
url: url,
method: 'POST',
data: JSON.stringify({codigo: codigo}),
contentType: 'application/json',
success: onSuccess.bind(this),
error: onError.bind(this)
});
}
function onSuccess() {
var mensagem = 'Benefício concedido com sucesso!';
this.containerMensagemSucesso.removeClass('hidden');
this.containerMensagemSucesso.html('<span>' + mensagem + '</span>');
}
function onError(object) {
console.log(error);
var mensagem = object.responseText;
this.containerMensagemErro.removeClass('hidden');
this.containerMensagemErro.html('<i class="fa fa-exclamation-circle"></i><span> ' + mensagem + '</span>');
}
return ImovelConcederBeneficio;
}());
$(function() {
var imovelConcederBeneficio = new TorcidaPremiada.ImovelConcederBeneficio();
imovelConcederBeneficio.iniciar();
});
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:th="http://www.thymeleaf.org"
xmlns:tp="http://www.apptrechos.com.br"
xmlns:data="http://www.thymeleaf.org/extras/data"
layout:decorate="~{layout/layout-padrao}">
<head>
<title>Torcida Premiada - Cadastro de Imóveis</title>
<link rel="stylesheet" type="text/css" th:href="#{/stylesheets/vendors/bootstrap-switch.min.css}" />
</head>
<section layout:fragment="conteudo">
<div class="clearfix"></div>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<div class="x_title">
<h2 th:if="${imovel.novo}">Cadastro de Imóveis</h2>
<h2 th:unless="${imovel.novo}">Edição de Imóvel</h2>
<ul class="nav navbar-right panel_toolbox">
<li>
<a th:href="#{/imovel}"><i class="fa fa-search"></i> <span>Pesquisa de Imóveis</span></a>
</li>
</ul>
<div class="clearfix"></div>
</div>
<div class="x_content">
<br />
<form method="POST" class="form-horizontal form-label-left" th:object="${imovel}" th:action="#{/imovel/novo}">
<tp:message />
<div class="alert alert-danger alert-dismissible fade in hidden js-container-mensagem-erro" role="alert"></div>
<div class="alert alert-success alert-dismissible fade in hidden js-container-mensagem-sucesso" role="alert"></div>
<input type="hidden" th:field="*{codigo}" />
<div class="form-group tp-required" tp:classforerror="inscricaoImobiliaria">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="inscricaoImobiliaria">Inscrição Imobiliária</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input type="text" id="inscricaoImobiliaria" maxlength="16" class="form-control col-md-7 col-xs-12 input-imobiliario" th:readonly="${not imovel.novo}" th:field="*{inscricaoImobiliaria}" />
</div>
</div>
<div class="form-group tp-required" tp:classforerror="contribuinte.codigo">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="nomeContribuinte">Contribuinte</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<div class="input-group">
<input type="text" id="nomeContribuinte" class="form-control" readonly="readonly" th:field="*{contribuinte.nome}"
placeholder="Clique na lupa para pesquisar o contribuinte" />
<input type="hidden" id="codigoContribuinte" th:field="*{contribuinte}" />
<span class="input-group-btn">
<button type="button" class="btn btn-default js-tooltip" title="Pesquisar"
data-toggle="modal" data-target="#pesquisaRapidaDeContribuintes" th:disabled="${not imovel.novo}">
<i class="glyphicon glyphicon-search"></i>
</button>
</span>
</div>
</div>
</div>
<div class="form-group tp-required" tp:classforerror="condicaoDeResidente">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="condicaoDeResidente">Condição de Residente</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<select id="condicaoDeResidente" class="select2_single form-control" tabindex="-1" th:field="*{condicaoDeResidente}">
<option value="">Selecione uma condição</option>
<option th:each="condicaoDeResidente : ${condicoesDeResidencia}" th:value="${condicaoDeResidente}" th:text="${condicaoDeResidente.descricao}"></option>
</select>
</div>
</div>
<div class="form-group tp-required" tp:classforerror="situacao">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="situacao">Situação</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<select id="situacao" class="select2_single form-control" tabindex="-1" th:field="*{situacao}">
<option value="">Selecione uma situação</option>
<option th:each="situacao : ${situacoes}" th:value="${situacao}" th:text="${situacao.descricao}"></option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Status</label>
<div class="col-md-4 col-sm-4 col-xs-6">
<input type="checkbox" class="js-status" data-size="small"
data-on-color="primary" data-off-color="danger"
data-on-text="Ativo" data-off-text="Inativo"
data-inverse=true th:field="*{status}" />
</div>
<div class="col-md-5 col-sm-5 col-xs-6" th:unless="${imovel.novo}">
<button type="button" class="btn btn-success btn-sm js-valida-beneficio-btn" data:codigo="${imovel.codigo}" data:url="#{/beneficio}">Validar Benefício</button>
</div>
</div>
<div class="ln_solid"></div>
<div class="form-group">
<div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3">
<button type="submit" class="btn btn-primary js-cancelar-btn">Cancelar</button>
<button type="submit" class="btn btn-success">Salvar</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<th:block th:replace="pesquisa-rapida/pesquisa-rapida-de-contribuintes :: pesquisaRapidaDeContribuintes"></th:block>
</section>
<th:block layout:fragment="javascript-extra">
<script th:src="#{/javascripts/vendors/handlebars.min.js}"></script>
<script th:src="#{/javascripts/contribuinte.pesquisa-rapida.js}"></script>
<script th:src="#{/javascripts/vendors/bootstrap-switch.min.js}"></script>
<script th:src="#{/javascripts/imovel.condeder-beneficio.js}"></script>
<script>
$(".js-status").bootstrapSwitch();
</script>
</th:block>
</html>
When I click on the button, the ajax request doesn't reach to the controller. The browser console shows error HTTP Status 400 - The request sent by the client was syntactically incorrect.
The followings are the request data.
Would anybody help me?
My web app is basically: jsp + angularjs, but this datepicker is running with jQuery because of the template I am using.
Before explaining what is happening, my DTO's attributes matches my entity attributes, both java.util.Date, I am just informing that I already verified the attributes type because I got many 400 bad requests because of that.
I have a modal where I have many fields, but I inserted recently two datepickers (bootstrap) and till then app is crashing, when I send the POST via ajax to my java controller, I am receiving a bad request (400), I think that it is because the format is wrong (mm/dd/yyyy). I formatted correctly the date to pt_BR for Brazil but it is not working.
BoxApp.controller("UsuariosController", function($scope, $http) {
$scope.usuarios={};
$scope.usuariosParaAlterar={};
$scope.iniciar = function() {
$http.get('/boxmlV2/usuario').success(function (response) {
$scope.usuarios = response;
});
};
$scope.iniciar();
$scope.setSelected = function(selecao){
$scope.usuariosParaAlterar = selecao;
};
/**
* Trecho para validar o form ao submeter.
*/
$scope.submitted = false;
$scope.submitForm = function(formUsuarios) {
$scope.submitted = true;
if (formUsuarios.$valid) {
$("#dataValidadeConta").datepicker({
format: 'dd/mm/yyyy',
language: 'pt-BR'
});
$("#dataValidadeSenha").datepicker({
format: 'dd/mm/yyyy',
language: 'pt-BR'
});
$scope.editaUsuario();
}
};
$scope.editaUsuario = function() {
$http.post('/boxmlV2/usuario/salvarUsuario', {
ativo : $scope.usuariosParaAlterar.ativo,
idUsuario : idUsuario.value,
nome : nome.value,
senha : senha.value,
email : email.value,
bloqueado : $scope.usuariosParaAlterar.bloqueado,
dataValidadeConta : $scope.usuariosParaAlterar.dataValidadeConta,
dataValidadeSenha : $scope.usuariosParaAlterar.dataValidadeSenha,
resetSenha : $scope.usuariosParaAlterar.resetSenha,
perfil : $scope.usuariosParaAlterar.perfil
}).then(function(response) {
$scope.sucesso();
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
$scope.sucesso = function() {
$scope.closeMyPopup();
$scope.iniciar();
};
$scope.closeMyPopup = function() {
$(myModal_autocomplete).modal('hide');
};
$scope.preparaInsercao = function() {
nome.value = "";
senha.value = "";
email.value = "";
$(idUsuario).val("");
$(idUsuario).hide();
$(idLabel).hide();
};
});
<!-- START MODAL -->
<div id="myModal_autocomplete" class="modal fade" role="dialog"
aria-hidden="true" style="display: none;">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true"></button>
<h4 class="modal-title">Cadastro de Usuário</h4>
</div>
<div class="modal-body form">
<form name="form" id="form_sample_2" role="form"
class="form-horizontal ng-pristine ng-valid" novalidate>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Ativo:<span
class="required" aria-required="true"> * </span></label>
<div class="col-md-9">
<div class="clearfix">
<div>
<label class="btn btn-default active"> <input
type="radio" name="ativo"
ng-model="usuariosParaAlterar.ativo" value="true">
Sim <br />
</label> <label class="btn btn-default"> <input
type="radio" name="ativo"
ng-model="usuariosParaAlterar.ativo" value="false">
Não <br />
</label>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Nome:<span
class="required" aria-required="true"> * </span></label>
<div class="col-md-9">
<input type="text" ng-model="usuariosParaAlterar.nome"
class="form-control" id="nome" maxlength="100" name="nome"
required> <span style="color: red"
ng-show="submitted && form.nome.$error.required">Campo
Nome Obrigatório.</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Senha:<span
class="required" aria-required="true"> * </span></label>
<div class="col-md-9">
<input type="password" ng-model="usuariosParaAlterar.senha"
class="form-control" maxlength="100" name="senha"
placeholder="Do E-mail De Recebimento do XML" id="senha"
required> <span style="color: red"
ng-show="submitted && form.senha.$error.required">Campo
Senha Obrigatório.</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">E-mail:<span
class="required" aria-required="true"> * </span></label>
<div class="col-md-9">
<input type="email" ng-model="usuariosParaAlterar.email"
class="form-control" id="email" maxlength="100"
name="email" required> <span style="color: red"
ng-show="submitted && form.email.$error.required">Campo
E-mail Obrigatório.</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Bloqueado:<span
class="required" aria-required="true"> * </span></label>
<div class="col-md-9">
<div class="clearfix">
<div>
<label class="btn btn-default active"> <input
type="radio" name="bloqueado"
ng-model="usuariosParaAlterar.bloqueado" value="true">
Sim <br />
</label> <label class="btn btn-default"> <input
type="radio" name="bloqueado"
ng-model="usuariosParaAlterar.bloqueado" value="false">
Não <br />
</label>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Data Validade Conta:<span
class="required" aria-required="true"> * </span></label>
<div class="col-md-9">
<input
class="form-control form-control-inline input-medium date-picker"
name="dataValidadeConta" id="dataValidadeConta"
ng-model="usuariosParaAlterar.dataValidadeConta"
size="16" type="text" value="" required/> <span
class="help-block"> Selecione a data </span>
<span style="color: red"
ng-show="submitted && form.dataValidadeConta.$error.required">Campo
Data Validade Conta Obrigatório.</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Data Validade Senha:<span
class="required" aria-required="true"> * </span></label>
<div class="col-md-9">
<input
class="form-control form-control-inline input-medium date-picker"
ng-model="usuariosParaAlterar.dataValidadeSenha"
name="dataValidadeSenha" id="dataValidadeSenha"
size="16" type="text" value="" required/> <span
class="help-block"> Selecione a data </span>
<span style="color: red"
ng-show="submitted && form.dataValidadeSenha.$error.required">Campo
Data Validade Senha Obrigatório.</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Resetar Senha:<span
class="required" aria-required="true"> * </span>
</label>
<div class="col-md-9">
<div class="clearfix">
<div>
<label class="btn btn-default active"> <input
type="radio" name="resetSenha"
ng-model="usuariosParaAlterar.resetSenha" value="true">
Sim <br />
</label> <label class="btn btn-default"> <input
type="radio" name="resetSenha"
ng-model="usuariosParaAlterar.resetSenha" value="false">
Não <br />
</label>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Perfil
Usuário:<span class="required" aria-required="true">
* </span>
</label>
<div class="col-md-9">
<div class="clearfix">
<div>
<label class="btn btn-default active"> <input
type="radio" name="perfil"
ng-model="usuariosParaAlterar.perfil" value="true">
Admin <br />
</label> <label class="btn btn-default"> <input
type="radio" name="perfil"
ng-model="usuariosParaAlterar.perfil" value="false">
Usuário <br />
</label>
</div>
</div>
</div>
</div>
<div class="form-group">
<label id="idLabel" class="control-label col-md-3">ID:<span
class="required" aria-required="true"> * </span></label>
<div class="col-md-9">
<input type="text" ng-model="usuariosParaAlterar.idUsuario"
class="form-control" id="idUsuario" maxlength="100"
name="idUsuario" required disabled> <span
style="color: red"
ng-show="submitted && form.idUsuario.$error.required">Campo
ID Obrigatório.</span>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default"
data-dismiss="modal">Cancelar</button>
<button type="submit" class="btn btn-primary"
ng-click="submitForm(form)">
<i class="fa fa-check"></i> Salvar
</button>
</div>
</div>
</div>
</div>
<!-- END MODAL -->
Controller:
package br.com.kolss.boxml.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import br.com.kolss.boxml.dto.RetornoDTO;
import br.com.kolss.boxml.dto.UsuarioDTO;
import br.com.kolss.boxml.enums.RetornoEnum;
import br.com.kolss.boxml.service.UsuarioService;
#Controller
public class CadastroUsuariosController {
#Autowired
private UsuarioService usuarioService;
#RequestMapping(value="/usuario", method=RequestMethod.GET)
public ModelAndView iniciar(ModelMap modelMap){
return new ModelAndView("usuario");
}
#RequestMapping(value="/usuario",method=RequestMethod.GET,produces={"application/json"})
public #ResponseBody List<UsuarioDTO> obterTodos(ModelMap modelMap){
return usuarioService.obterTodos();
}
#RequestMapping(value = "/usuario/salvarUsuario", method = RequestMethod.POST, produces = { "application/json" })
public #ResponseBody RetornoDTO insereOuEditaUsuario(
#RequestBody UsuarioDTO usuarioDTO) {
usuarioService.insereOuEditaUsuario(usuarioDTO);
return new RetornoDTO(RetornoEnum.SUCESSO);
}
}
The date formatting to pt_BR only applies to how it is displayed in the datepicker control. Note that you are sending back a string mm/dd/yyyy to the server, you need to be sure that it is parsed as such at the controller.
well i have got this Themeforest Template and played around with it until the website looks in a way how i imagined it. The only Problem i have is that the .js form somehow doesnt work and i dont have any idea. I dont even know where to tell the form to which Adress it should send the text. Maybe you can help me.
The Domain is: entwicklung.thechillingbull.de
This is the HTML:
<div class="container"> </div>
<div class="container"> </div>
<div class="bg-2 section" id="contact">
<div class="inner" data-topspace="50" data-bottomspace="20" data-image="flavours/coffeecream/images/demo-content/background-6.jpg">
<div class="container">
<h3 class="hdr4">Kontakt und Reservierung</h3>
<div class="easyBox full">
<div class="row nomargin">
<div class="col-md-11">
<h4 class="hdr2 special">Wenn du Uns etwas mitteilen oder Reservieren möchtest hast du hier die Chance!</h4>
<form class="simpleForm" action="form/form.php" method="post">
<fieldset>
<div class="form-group">
<label>Dein Name</label>
<input type="text" class="form-control" name="field_[]" placeholder="Schreibe deinen Namen">
</div>
<div class="form-group">
<label>Deine E-Mail-Adresse</label>
<input type="email" required class="form-control" name="email" placeholder="Schreibe deine E-Mail-Adresse">
</div>
<div class="form-group">
<label>Deine Nachricht</label>
<textarea class="form-control" rows="5" name="field_[]" placeholder="Schreibe deine Nachricht"></textarea>
</div>
<input type="hidden" name="msg_subject" value="Contact Form">
<input type="hidden" name="field_[]" value=" ">
<input class="btn btn-default" type="submit" value="Senden">
</fieldset>
</form>
<div class="successMsg" style="display:none;">Nachricht erfolgreich gesendet! </div>
<div class="errorMsg" style="display:none;"> Ups! Es ist ein Fehler unterlaufen, versuche es später erneut. </div>
</div>
<div class="col-md-2"> </div>
</div>
</div>
</div>
</div>
and this is the .js
/**
* Submitting Form
*/
jQuery(document).ready(function ($) {
var debug = false; //show system errors
var sendingMessage = 'Sending...';
$('.simpleForm').submit(function () {
var $f = $(this);
var $submit = $f.find('input[type="submit"]');
//prevent double click
if ($submit.hasClass('disabled')) {
return false;
}
$submit.attr('data-value', $submit.val()).val(sendingMessage).addClass('disabled');
$.ajax({
url: $f.attr('action'),
method: 'post',
data: $f.serialize(),
dataType: 'json',
success: function (data) {
if (data.errors) {
// error
var $errorMsg = jQuery($f).parent().find(".errorMsg");
jQuery($f).fadeOut(300,function(){
$errorMsg.fadeIn();
});
} else {
// success
var $successMsg = jQuery($f).parent().find(".successMsg");
jQuery($f).fadeOut(300,function(){
$successMsg.fadeIn();
});
}
$submit.val($submit.attr('data-value')).removeClass('disabled');
},
error: function (data) {
if (debug) {
alert(data.responseText);
}
$submit.val($submit.attr('data-value')).removeClass('disabled');
}
});
return false;
});
});
hope you can help me get this to work.
Thank you !
Change:
<form class="simpleForm" action="form/form.php" method="post">
To
<form class="simpleForm" action="/your-code-file" method="post">
where your-code-file will be the location of the file which will handle the form values.