Save Image in JSON for Rest - javascript

I am currently coding on a project for school, which should be a picture sharing website.
Spring Framework is handling the database as well as the rest interface. On the rest interface I have a RemoteImage, which represents an Image saved in the Database. I also have Getters, Setters and Cunstructors in there, but did not copied it in here.
#XmlRootElement
public class RemoteImage {
private Long id;
private String name;
private String contentType;
private byte[] content;
private Date createdAt;
private String owner;
private String camera;
private String lens;
private String aperture;
private String focalLength;
private String shutterSpeed;
private String ISO;
private String description;
private Long ownerId;
private Long categoryId;
....
In the Rest Resource I have the addImage function which converts the RemoteImage from the Rest into a Image for storing in the Database. The RemoteImage does not contain votes.
#POST
#Transactional
public void addImage(RemoteImage remoteImage) {
try {
Image image = new Image(
remoteImage.getName(),
remoteImage.getContentType(),
remoteImage.getContent(),
remoteImage.getCreatedAt(),
remoteImage.getOwner(),
remoteImage.getCamera(),
remoteImage.getLens(),
remoteImage.getAperture(),
remoteImage.getFocalLength(),
remoteImage.getFocalLength(),
remoteImage.getISO(),
remoteImage.getDescription(),
remoteImage.getOwnerId(),
remoteImage.getCategoryId()
);
service.save(image);
} catch (DataIntegrityViolationException e) {
sendError(409, "Image could not be stored. " + e.toString());
}
}
I tested this function with following Test:
#Test
public void testImageUpload() throws URISyntaxException, IOException {
login(james.getEmail(), "password");
RemoteImage image = createTestRemoteImage("test", james);
List<Image> images = r.path("image")
.header(AUTHENTICATION_HEADER, createAuthenticationHeader("kai#ima.at", "password"))
.accept(MediaType.APPLICATION_JSON)
.get(new GenericType<List<Image>>() {
});
assertThat(images.size(), is(0));
r.path("image").header(AUTHENTICATION_HEADER, createAuthenticationHeader("kai#ima.at", "password")).post(image);
List<Image> images1 = r.path("image")
.header(AUTHENTICATION_HEADER, createAuthenticationHeader("kai#ima.at", "password"))
.accept(MediaType.APPLICATION_JSON)
.get(new GenericType<List<Image>>() {
});
assertThat(images1.size(), is(1));
}
private RemoteImage createTestRemoteImage(String name, Customer customer) throws URISyntaxException, IOException {
byte[] bytes = FileUtils.readFileToByteArray(new File(getClass().getResource("/images/test.jpg").toURI()));
RemoteImage image = new RemoteImage(name, "image/jpeg", bytes, bytes, new Date(), customer.getEmail(), "Samsung NX300M", "Minolta MD 1.4", "1.4", "50", "2000", "200", "Test Image description", customer.getId(), 1L);
return image;
}
This seems to work fine so far, but in the Front End, in my case AngularJS, where I have a controller for adding an Image.
controllers.controller 'ImageAddController', ['$scope','$routeParams','$location','Image', ($scope, $routeParams, $location, Image) ->
$scope.image = {name:"",description:""}
$scope.error = null
$scope.add = ->
Image.save $scope.image,
(text,headers,context) ->
$scope.error = null
$location.path('/images/')
(request) ->
$scope.error = request.data
]
The matching view for that controller is the following
<div class="body-content">
<h1>Add Image</h1>
<div class="panel col-lg-8 col-offset-2">
<div class="panel-heading">
<h3 class="panel-title">New Image</h3>
</div>
<div class="alert alert-danger" data-ng-bind="error" data-ng-show="error"></div>
<form novalidate name="imageForm" class="css-form">
<fieldset>
<div class="form-group" >
<label for="name" class="control-label">Name</label>
<input type="text" class="form-control" id="name"
data-ng-model="image.name" required name="name"/>
</div>
<div class="form-group">
<label for="description" class="control-label">Description</label>
<input type="text" class="form-control" id="description"
data-ng-model="image.description" required name="description"/>
</div>
<div class="form-group">
<label for="category" class="control-label">Category</label>
<input type="text" class="form-control" id="category"
data-ng-model="image.categoryId" name="category"
required />
</div>
<div class="form-group">
<label for="camera" class="control-label">Camera</label>
<input type="text" class="form-control" id="camera"
data-ng-model="image.camera" name="camera"
required />
</div>
<div class="form-group">
<label for="lens" class="control-label">Lens</label>
<input type="text" class="form-control" id="lens"
data-ng-model="image.lens" name="lens"
required />
</div>
<div class="form-group">
<label for="aperture" class="control-label">Aperture</label>
<input type="text" class="form-control" id="aperture"
data-ng-model="image.aperture" name="aperture"
required />
</div>
<div class="form-group">
<label for="focalLength" class="control-label">Focal length</label>
<input type="number" class="form-control" id="focalLength"
data-ng-model="image.focalLength" name="focalLength"
required />
</div>
<div class="form-group">
<label for="shutterSpeed" class="control-label">Shutter speed</label>
<input type="text" class="form-control" id="shutterSpeed"
data-ng-model="image.shutterSpeed" name="shutterSpeed"
required />
</div>
<div class="form-group">
<label for="ISO" class="control-label">ISO</label>
<input type="number" class="form-control" id="ISO"
data-ng-model="image.ISO" name="ISO"
required />
</div>
</fieldset>
<div class="btn-toolbar">
<button class="btn btn-primary" data-ng-click="add()"
data-ng-disabled="customerForm.$invalid">Save</button>
Cancel
</div>
</form>
</div>
</div>
My question is how do let the user upload a picture to save it in the JSON (byte[] content) and how would I be able to display that image from an JSON for the user?
PS: The controller is not writen in Javascipt, it is Coffeescript. But because I guess more of you understand Javascript, you can help me in that language.

Related

ASP.NET Core MVC Select with dynamic searchig

I have a Login page, and I want to implement when an user type the username for example "Jh", because he is called Jhon, then next to the Login form there is a selectlist, and listing all the usernames from the database that contains Jh, and it should be dynamic, I mean if the input changes then update the search automatically.
Here is my view
<div class="row justify-content-center">
<div class="col-md-7">
<form asp-action="Login">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
#if (!string.IsNullOrEmpty(ViewBag.Message))
{
<span class="text-danger">
#ViewBag.Message
</span>
}
#Html.HiddenFor(x => x.ReturnUrl)
<div class="form-group">
<label asp-for="UserId" class="control-label"></label>
<input asp-for="UserId" class="form-control" />
<span asp-validation-for="UserId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Password" class="control-label"></label>
<input asp-for="Password" class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
#*<div class="form-group">
<div class="checkbox">
<label>
<input asp-for="RememberLogin" /> #Html.DisplayNameFor(model => model.RememberLogin)
</label>
</div>
</div>*#
<div class="form-group">
<input type="submit" value="Bejelentkezés" class="btn btn-primary w-100" />
</div>
</form>
</div>
<div class="col-md-5">
<div class="form-group col-md-6">
<select asp-for="UserId" asp-items="ViewBag.Users" size="6" multiple class="form-control"></select>
<span asp-validation-for="UserId" class="text-danger"></span>
</div>
</div>
</div>
<script>
$("#search_id").keyup(function () {
//call ajax method
});
</script>
Here is my controller (Im using stored procedures):
public IActionResult Login(string ReturnUrl = "/")
{
LoginModel objLoginModel = new LoginModel();
objLoginModel.ReturnUrl = ReturnUrl;
string sqlQuery = "execute GetUsers";
var result = _context.GetUsers(sqlQuery);
ViewBag.Users = new SelectList(result, "UserId", "UserId");
return View("Login");
}
I write a simple demo here without any third part plugin, It is a basic demo to show how to achieve dynamic search, You can refer and make some changes to meet the needs of your own project. I hople it is what you want.
Model
public class Student
{
public string Id { get; set; }
public string Name { get; set; }
}
View
#model Student
<input asp-for="#Model.Name" oninput="Search(this.value)"/>
<div id="result"></div>
#section Scripts
{
<script>
function Search(data) {
var value ={
"name": data
}
$.post({
url: 'https://localhost:7209/Home/Download1',
ethod: 'Post',
data: value,
success: function (data) {
result = '';
for (var i = 0;i<data.length;i++){
result = result +'<tr><td>'+data[i].id+'</td><td>'+data[i].name+'</td></tr>';
}
document.getElementById("result").innerHTML = '<table class="table table-striped table-bordered zero-configuration dataTable" role="grid">'
+'<thead><tr><th>Id</th><th>Name</th></tr></thead>'
+'<tbody>'+result+'</tbody>'
+'</table>';
}
})
}
</script>
}
Home/Download1
[HttpPost]
public IActionResult Download1(string name)
{
//For testing convenience, I just hard code here, you can change it and select data from database
var result = Students.Where(x => x.Name.Contains(name)).ToList();
return Json(result);
}
Demo

Trying to dynamically insert javascript values into asp tag helper element

#page
#model Vescoverer.Pages.Registration.LocationModel
#{
ViewData["Title"] = "Location";
}
<div class="row">
<div class="col-md-4">
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div id="long" class="form-group">
<label asp-for="User.Longitude" class="control-label"></label>
<input id="long" asp-for="User.Longitude" class="form-control" />
<span asp-validation-for="User.Longitude" class="text-danger"></span>
</div>
<div id="lat"class="form-group">
<label asp-for="User.Latitude" class="control-label"></label>
<input asp-for="User.Latitude" class="form-control" v />
<span asp-validation-for="User.Latitude" class="text-danger"></span>
</div>
<div class="form-group">
<input asp-for="User.Longitude" type="submit" value="Next" class="btn btn-primary" />
</div>
</form>
<button onclick="getLocation()">Get Location</button>
</div>
</div>
<script>
var lat = document.getElementById("lat");
var long = document.getElementById("long");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
lat.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
lat.innerHTML = position.coords.latitude;
long.innerHTML = position.coords.longitude;
$.ajax(
{
type: "POST", //HTTP POST Method
url: "Location",
data: { //Passing data
Longitude: //insert data value, //Reading text box values using Jquery
Latitude: //insert data value
}
});
}
</script>
I want the longitude and latitude results to go into the appropriate form input values to be passed into the backend when the user clicks Get Location, instead the result replaces the form values with the innerHTML string. i know the asp-for tag heper handles the server side aspect but i'm not sure how to get the javascript results to be displayed in the form value. So when the user presses next, the data is passed into the database, as you can see i'm also trying to use Ajax but i'm not too sure.
You can use the ".val(value)" method to set the value of each element in the set of matched elements.
$("input[name*='Latitud']").val(position.coords.latitude);
$("input[name*='Longitude']").val(position.coords.longitude);
Result
The following is the complete demo, you can refer to it.
Model
public class User
{
public string Longitude { get; set; }
public string Latitude { get; set; }
}
xxx.cshtml.cs
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
[BindProperty]
public new User User { get; set; }
public void OnGet()
{
}
public void OnPost()
{
}
}
xxx.cshtml
#page
#model IndexModel
#{
ViewData["Title"] = "Home page";
}
<div class="row">
<div class="col-md-4">
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div id="long" class="form-group">
<label asp-for="User.Longitude" class="control-label"></label>
<input id="long" asp-for="User.Longitude" class="form-control" />
<span asp-validation-for="User.Longitude" class="text-danger"></span>
</div>
<div id="lat" class="form-group">
<label asp-for="User.Latitude" class="control-label"></label>
<input asp-for="User.Latitude" class="form-control" v />
<span asp-validation-for="User.Latitude" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Next" class="btn btn-primary" />
</div>
<button type="button" onclick="getLocation()">Get Location</button>
</form>
</div>
</div>
#section scripts{
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
lat.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
$("input[name*='Latitud']").val(position.coords.latitude);
$("input[name*='Longitude']").val(position.coords.longitude);
}
</script>
}

How to submit asp.net core razor pages form without reloading page

I have tried everything I have Googled to get this to work without success. I am working with a single page layout that has a contact form. The code seems to fire correctly and sends the form values to the page model but then it reloads the page. The expected outcome should be, submit the form values to the page model without reloading. Can someone show me how to do this?
Page Model
public class IndexModel : PageModel
{
[BindProperty]
public ContactModel Contact { get; set; }
public void OnGet()
{
}
public void OnPostSendEmail()
{
if (ModelState.IsValid == false)
{
}
else
{
}
}
}
Form
<form method="post" role="form" class="email-form">
<div class="form-row">
<div class="form-group col-md-6">
<label for="name">Your Name</label>
<input type="text" asp-for="Contact.Name" value="Gekko" name="name" class="form-control" id="name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validate"></div>
</div>
<div class="form-group col-md-6">
<label for="name">Your Email</label>
<input type="email" asp-for="Contact.Email" value="someone#email.com" class="form-control" name="email" id="email" data-rule="email" data-msg="Please enter a valid email" />
<div class="validate"></div>
</div>
</div>
<div class="form-group">
<label for="name">Subject</label>
<input type="text" asp-for="Contact.Subject" value="Work" class="form-control" name="subject" id="subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validate"></div>
</div>
<div class="form-group">
<label for="name">Message</label>
<textarea class="form-control" asp-for="Contact.Message" name="message" rows="10" data-rule="required" data-msg="Please write something for us"></textarea>
<div class="validate"></div>
</div>
<div class="mb-3">
<div class="loading">Loading</div>
<div class="error-message"></div>
<div class="sent-message">Your message has been sent. Thank you!</div>
</div>
<div class="text-center"><button id="submit">Send Message</button></div>
</form>
Javascript
$('form.email-form').submit(function (e) {
e.preventDefault();
...some form validation
$.ajax({
type: "POST",
url: '/index?handler=SendEmail',
data: str,
success: function(msg) {
if (msg == 'OK') {
this_form.find('.loading').slideUp();
this_form.find('.sent-message').slideDown();
this_form.find("input:not(input[type=submit]), textarea").val('');
} else {
this_form.find('.loading').slideUp();
this_form.find('.error-message').slideDown().html(msg);
}
}
});
Razor Pages are designed to be automatically protected from cross-site request forgery (CSRF/XSRF) attacks. So the first thing is to modify your ajax to include token in header:
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
And configure the antiforgery service to look for the X-CSRF-TOKEN header :
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
Below article is for your reference :
Handle Ajax Requests in ASP.NET Core Razor Pages
And OnPostSendEmail is void type so no value returned, if you want to return something from server side and fill html in success function of ajax , you can return JsonResult in OnPostSendEmail method.

How to take screenshot of a div and insert the value to model's property ASP .NET Core

I'm trying to make a banner creator. User changes the photos and captions dynamically, but i have to store all the texts and pictures in a SQL table so i created a model for it. When i click the save button, I want the banner div to be saved as jpeg file in my projects img folder, then it has to be passed to my models "Photo" property to be stored.
My View
#model HPBanner1ViewModel
<div class="row" id="canvas1">
My Picture Here
</div>
<form enctype="multipart/form-data" asp-controller="HPBannerType1" asp-action="Create" method="post">
<div class="form-group row">
<label asp-for="PromosyonMetin" class="col-sm-2 col-form-label">Metin</label>
<div class="col-sm-10">
<textarea asp-for="PromosyonMetin" type"="text" class="form-control" id="metinsrc" placeholder="Bol kabaklı mücver menüsü..." onKeyPress="copyText()"></textarea>
</div>
</div>
<div class="form-group row">
<label asp-for="Fiyat" class="col-sm-2 col-form-label">Fiyat</label>
<div class="col-sm-10">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">₺</span>
<span class="input-group-text">0.00</span>
</div>
<input asp-for="Fiyat" type="text" class="form-control" id="fiyatsrc" aria-label="Amount (to the nearest lira)">
</div>
</div>
</div>
<div class="form-group row">
<p><b>Banner Resmi</b></p>
<div class="input-group mb-3">
<div class="custom-file">
<input asp-for="BannerPicture" type="file" class="custom-file-input" id="inputGroupFile01">
<label asp-for="BannerPicture" class="custom-file-label" for="inputGroupFile01"></label>
</div>
</div>
</div>
<input asp-for="LogoURL" type="hidden" value="#Model.LogoURL">
<input asp-for="RestaurantName" type="hidden" value="#Model.RestaurantName">
<input asp-for="RestaurantID" type="hidden" value="#Model.RestaurantID">
<input asp-for="CreationDate" type="hidden" value="#DateTime.Now">
<div class="row">
<div class="form-group row">
<div class="col-sm-10">
<a id="savebutton" class="btn btn-primary">Oluştur</a>
</div>
</div>
</div>
</form>
I use this code below to download the image but i couldn't find how to save it to my projects img folder and take the path to my model property . How can i do this ?
$('#savebutton').click(function () {
html2canvas($("#canvas1").get(0)).then(function (canvas) {
;
var aw = document.createElement('a');
var image = canvas.toDataURL("image/jpeg").replace("image/jpeg", "image/octet-stream");
aw.href = image;
aw.download = '#Guid.NewGuid()-#Model.RestaurantName-#DateTime.Now-HP1MOB.jpg';
aw.click();
});
});
You could use ajax to pass the image and imageName to controller where you could upload files and save path to database.
Javascript:
$('#savebutton').click(function () {
html2canvas($("#canvas1").get(0)).then(function (canvas) {
var image = canvas.toDataURL("image/jpeg");
var data = {
imageData: image,
imageName: '#Guid.NewGuid()-#Model.RestaurantName-#DateTime.Now-HP1MOB.jpg'
};
$.ajax({
type: 'POST',
url: '/Home/SaveImage',
data: data,
success: function (msg) {
alert('Image saved successfully !');
}
});
});
});
HomeController:
public class HomeController : Controller
{
private readonly IHostingEnvironment _hostingEnv;
private readonly ApplicationDbContext _context;
public HomeController(IHostingEnvironment hostingEnv,ApplicationDbContext context)
{
_hostingEnv = hostingEnv;
_context = context;
}
[HttpPost]
public void SaveImage(string imageData,string imageName)
{
//save to Myapp/images folders
//replace filepath with your own path to store files
var filePath = Path.Combine(_hostingEnv.ContentRootPath, "images", imageName);
using (FileStream fs = new FileStream(filePath, FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
imageData = imageData.Replace("data:image/jpeg;base64,", "");
byte[] data = Convert.FromBase64String(imageData);
bw.Write(data);
bw.Close();
}
//...
//save path into database
}
}

Trouble with Ajax/json and spring mvc

--edit--
What is happening is I can see with console/sout items that I am getting the object from the DB, and currentyly I am getting a 500 internal server error, every fix I have tried one error goes away (400 has been very popular) and then I get another, i fix it then I get another.
I am getting the data, but it the call keeps failing and I can't do anything with the information, I am seeing that data, but I can't figure out how to catch it properly.
What I am trying to do is search for a customer, if that customer exists populate that information in the next page form, if not just insert the search criteria into the corresponding fields in the next page form.
Here is javascript, I can't figure out the load function because it doesn't seem to work right (not sure how to catch the data correctly it seems).
$('#search-customer').click(function (event) {
var testdata = document.getElementById('searchCustomerForm');
// var isvalid = checkForm(form);
// if (isvalid === false) {
// event.preventDefault();
// alert('is valid===false');
// } else {
alert('hit search customer ajaxcall');
$.ajax({
type: 'GET',
url: 'customerLookup/?firstName=' + $('#search_first_Name').val() + '&lastName=' + $('#search_last_Name').val() + '&compId=' + companyId,
data: JSON.stringify({
firstName: $('#search-first_name').val(),
lastName: $('#search-last_name').val(),
// dob: $('#search_birthdate').val(),
// license: $('#search_license_number').val()
// dob: $('#search_birthdate').val(),
compId: $('#search_companyId').val(companyId)
}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
'dataType': 'json'
}).done(function (data, status) {
if (data !== null) {
window.location = "/app/ticketStepOneTwoAddCustomer";
loadCustomerInputForm(data, status);
alert('customer found, moving to confirm');
}
else if (data === null) {
window.location = "/app/ticketStepOneTwoAddCustomer";
addSearchInfoToInputCustomerForm();
alert('no customer of that name found, moving to add customer');
}
}).fail(function () {
alert('not a success');
// window.location = "/app/ticketStepOneTwoAddCustomer";
});
});
function loadinputcustomerform(data, status) {
alert('hit loadinputcustomerform function');
console.log(cust.customer.getCustomerFirstName());
console.log(data.customer.getCustomerMiddleName());
console.log(customer.getCustomerLastName());
Here is the Controller
#RequestMapping(value = {"/customerLookup"}, method = RequestMethod.GET)
#ResponseBody
public Customer getCustomerByCriteria(
#RequestParam(value = "compId", required = false) int compId,
#RequestParam(value = "firstName", required = false) String fName,
#RequestParam(value = "lastName", required = false) String lName) {
System.out.println("here: " + compId + " -- " + fName);
Customer cust = customerService.searchCustomer(fName, lName, compId);
//System.out.println(cust.getCustomerLicense());
return cust;
}
On the java side the customer is just an object, in the DB the companyID is the FK, everything requires the compID, I was thinking They should have made a customer hashmap or list but not my area and it is what I have to work with.
here is the html
<form id="inputCustomerForm">
<div class="form-group">
<label for="firstName">First Name</label>
<input type="text" class="form-control" id="input_first_Name" style="text-transform:uppercase;" onkeyup="this.value = this.value.toUpperCase()" placeholder="First Name">
</div>
<div class="form-group">
<label for="middleName">Middle Name</label>
<input type="text" class="form-control" id="input_middle_Name" style="text-transform:uppercase;" onkeyup="this.value = this.value.toUpperCase()" placeholder="Middle Name">
</div>
<div class="form-group">
<label for="lastName">Last Name</label>
<input type="text" class="form-control" id="input_last_Name" style="text-transform:uppercase;" onkeyup="this.value = this.value.toUpperCase()" placeholder="Last Name">
</div>
<div class="form-group">
<label for="dob">D.O.B. YYYYMMDD</label>
<input type="text" class="form-control" id="input_birthdate" style="text-transform:uppercase;" onkeyup="this.value = this.value.toUpperCase()" placeholder="YYYYMMDD">
</div>
<div class="form-group">
<label for="addressone">Address</label>
<input type="text" class="form-control" id="input_addressone" style="text-transform:uppercase;" onkeyup="this.value = this.value.toUpperCase()" placeholder="123 street">
</div>
<div class="form-group">
<label for="addresstwo">Address</label>
<input type="text" class="form-control" id="input_addresstwo" style="text-transform:uppercase;" onkeyup="this.value = this.value.toUpperCase()" placeholder="po 1111">
</div>
<div class="form-group">
<label for="city">City</label>
<input type="text" class="form-control" id="input_city" style="text-transform:uppercase;" onkeyup="this.value = this.value.toUpperCase()" placeholder="Columbus">
</div>
<div class="form-group">
<label for="state">State</label>
<input type="text" class="form-control" id="input_state" style="text-transform:uppercase;" onkeyup="this.value = this.value.toUpperCase()" placeholder="OH">
</div>
<div class="form-group">
<label for="zip">ZipCode</label>
<input type="text" class="form-control" id="input_zip" style="text-transform:uppercase;" onkeyup="this.value = this.value.toUpperCase()" placeholder="43026">
</div>
<div class="form-group">
<label for="licenseNumber">License Number</label>
<input type="text" class="form-control" id="input_license_number" style="text-transform:uppercase;" onkeyup="this.value = this.value.toUpperCase()" placeholder="License Number">
</div>
<div class="form-group">
<label for="licenseInputFile">File input</label>
<input type="file" id="licensePhoto">
<p class="help-block">License Photo</p>
</div>
<div class="form-group">
<label for="customerPhotoInputFile">File input</label>
<input type="file" id="customerPhoto">
<p class="help-block">Customer Photo</p>
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Check me out
</label>
</div>
<button type="reset" class="btn btn-default">Clear</button>
<button type="submit" id="input-customer" class="btn btn-default" >Submit</button>
</form>
here is the response
HTTP Status 500 - Could not write JSON: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: com.REMOVED.DTO.Customer["company"]->com.REMOVED.DTO.Company_$$_jvstf68_6["handler"]); nested exception is org.codehaus.jackson.map.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: com.REMOVED.DTO.Customer["company"]->com.REMOVED.DTO.Company_$$_jvstf68_6["handler"])
type Exception report
message Could not write JSON: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: com.REMOVED.DTO.Customer["company"]->com.REMOVED.DTO.Company_$$_jvstf68_6["handler"]); nested exception is org.codehaus.jackson.map.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: com.REMOVED.DTO.Customer["company"]->com.REMOVED.DTO.Company_$$_jvstf68_6["handler"])
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: com.REMOVED.DTO.Customer["company"]->com.REMOVED.DTO.Company_$$_jvstf68_6["handler"]); nested exception is org.codehaus.jackson.map.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: com.REMOVED.DTO.Customer["company"]->com.REMOVED.DTO.Company_$$_jvstf68_6["handler"])
org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.writeInternal(MappingJacksonHttpMessageConverter.java:212)
org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:207)
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:148)
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:90)
org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:193)
org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:71)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:122)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
root cause
org.codehaus.jackson.map.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: com.REMOVED.DTO.Customer["company"]->com.REMOVED.DTO.Company_$$_jvstf68_6["handler"])
org.codehaus.jackson.map.ser.impl.UnknownSerializer.failForEmpty(UnknownSerializer.java:52)
org.codehaus.jackson.map.ser.impl.UnknownSerializer.serialize(UnknownSerializer.java:25)
org.codehaus.jackson.map.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:446)
org.codehaus.jackson.map.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:150)
org.codehaus.jackson.map.ser.BeanSerializer.serialize(BeanSerializer.java:112)
org.codehaus.jackson.map.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:446)
org.codehaus.jackson.map.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:150)
org.codehaus.jackson.map.ser.BeanSerializer.serialize(BeanSerializer.java:112)
org.codehaus.jackson.map.ser.StdSerializerProvider._serializeValue(StdSerializerProvider.java:610)
org.codehaus.jackson.map.ser.StdSerializerProvider.serializeValue(StdSerializerProvider.java:256)
org.codehaus.jackson.map.ObjectMapper.writeValue(ObjectMapper.java:1613)
org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.writeInternal(MappingJacksonHttpMessageConverter.java:209)
org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:207)
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:148)
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:90)
org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:193)
org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:71)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:122)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
note The full stack trace of the root cause is available in the Apache Tomcat/8.0.15 logs.
I was thinking that the customer properties being private was an issue but with public getters and setters i thought it would still work.

Categories

Resources