how to insert JSON array into MySQL using mvc spring - mysql

Hi I am new in spring And developing a module of POST.
How to insert JSON array in db.
can you please give me the idea how to solve this issue.
I have also an example to show you this.
link:- http://hello-angularjs.appspot.com/angularjs-http-service-ajax-post-json-data-code-example
Here the controller code
#RequestMapping(value = "/create1", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody
BillingModel addbillingmodel(#RequestBody BillingModel billingmodel) {
try {
billingmodel.getItemid();
billingmodel.getQuantity();
dataServices.addEntity(billingmodel);
return billingmodel;
} catch (Exception e) {
e.printStackTrace();
return billingmodel;
}
}
}
Here is my html page with JSON.
<!DOCTYPE html>
<html data-ng-app="serviceModule">
<head>
<meta charset="ISO-8859-1">
<title>AngularJS POST Spring MVC</title>
<script
src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js">
</script>
<script type="text/javascript">
var serviceModule = angular.module('serviceModule', []);
serviceModule.controller("AngularJSPostController", function($scope, $http) {
$scope.variable = "AngularJS POST Spring MVC Example:";
var dataObj = {
"itemid" : "11",
"quantity" : "22",
};
var response =
$http.post('/CRUDWebAppMavenized/billing_bakery/create1', dataObj);
response.success(function(data, status, headers, config) {
$scope.responseData = data;
});
response.error(function(data, status, headers, config) {
alert( "Exception details: " + JSON.stringify({data: data}));
});
});
</script>
</head>
<body data-ng-controller="AngularJSPostController">
<div>
<h4>{{variable}}</h4>
<b>You had sent below data through post:</b>
<p>Response: {{responseData}}</p>
</div>
</body>
</html>
I have to multiple data in a row.

1.In your BillingModel class create following methods -
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public String toJson() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(this);
return json;
}
2.You should have blob types of columns to store JSON
3.And in Your DAO class when you call addEntity , do something like this -
final MapSqlParameterSource sqlParams = new MapSqlParameterSource()
.addValue("item_json",billingModel.toJson().getBytes("UTF-8"));
You can also refer.
Converting Java objects to JSON with Jackson

Related

java angularjs spring file upload

I am trying to upload a file to a server using angularjs and Spring (to Amazon AWS).
I checked a couple of posts on uploading with the first one and the latter but I still can't get the both to work together.
File Upload using AngularJS
How to upload a file with AngularJS?
Checked also youtube for tutorials, found Black Cloud, Brent Aureli's channel and I just cannot figure it out.
You have to be authenticated in my webapp to send post requests, but I am getting errors also when I'm logged in.
Would be extremely grateful for some help.
This is my html form:
<form>
<input type="file" file-model="file">
<button ng-click="submit()" type="submit">Click</button>
</form>
Directive for the file-model:
.directive('fileModel', ['$parse', function($parse){
return {
restrict: 'A',
link: function(scope, element,attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function() {
scope.$apply(function() {
modelSetter(scope, element[0].files[0]);
})
})
}
}
}])
Controller:
.controller('UploadController', ['$scope', 'multipartForm', function($scope, multipartForm) {
$scope.file = {};
$scope.submit = function() {
var uploadUrl = '/uploadtest';
multipartForm.post(uploadUrl, $scope.file);
}
}])
Service for multipartForm:
.service('multipartForm', ['$http', function($http){
this.post = function(uploadUrl, data) {
var fd = new FormData();
for(var key in data) {
fd.append(key, data[key]);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
}
}])
Spring Endpoint:
#RestController
#RequestMapping("/storage/")
public class BucketController {
private AmazonClient amazonClient;
#Autowired
public BucketController(AmazonClient amazonClient) {
this.amazonClient = amazonClient;
}
#RequestMapping(value = "/uploadtest", method = RequestMethod.POST)
public String uploadFile(#RequestParam(value = "file") MultipartFile file) {
System.out.println("Uploading file!!!!!!!!!!!!");
return this.amazonClient.uploadFile(file);
}
}
Error that I'm getting in the browser:
angular.js:15018 Possibly unhandled rejection:
{"data":{"timestamp":1537033312586,"status":400,"error":"Bad Request","exception":"org.springframework.web.multipart.support.MissingServletRequestPartException","message":"Required request part 'file' is not present","path":"/uploadtest"},
"status":400,
"config":{"method":"POST","transformResponse":[null],
"jsonpCallbackParam":"callback",
"headers":{"Accept":"application/json,
text/plain, /",
"X-Requested-With":"XMLHttpRequest",
"Authorization":
"Basic c3p5bW9uc3R1c3pla0BnbWFpbC5jb206dGVzdA==",
"X-XSRF-TOKEN":"395d1e27-a6ee-4948-b673-39d31902e1ae"},
"url":"/uploadtest","data":{}},
"statusText":"","xhrStatus":"complete"}
The exception occurred due the missing query param 'file' which is not presented.
And in spring endpoint you should not receive a file request in Request param!
#RequestMapping(value="/uploadtest", consumes = "multipart/form-data",method = RequestMethod.POST, produces = "application/json")
public String uploadFile(MultipartHttpServletRequest request) throws Exception{
try {
MultipartFile multipartFile1 = request.getFile("file");
if (multipartFile1 != null) {
String file1 = multipartFile1.getOriginalFilename();
InputStream inputStream = multipartFile1.getInputStream();
// do whatever
}
} catch (IOException e) {
logger.error(e.getMessage());
}
return null;
}
And in Service for multipartForm change the headers content-type to : multipart/form-data
Hope this would Help!!

HTTP Native Plugin (IONIC 3)

I'm trying to make a post request using the HTTP cordova plugin. However, for some reason, the JSON data consumed by the Server side is not being formatted correctly (json brakets). Could anyone help me please?
The import:
import { HTTP } from '#ionic-native/http';
The request implementation:
public sendData(sufix, json) {
return new Promise((resolve, reject) => {
this.http.post(URL+sufix, JSON.stringify(json), {'Content-Type': 'application/json'}).then(result => {
resolve(result.data);
}).catch(error => {
reject(error);
});
});
}
The json sended:
{name: 'Test'}
The content received by the server:
=%7B%22name%22%3A%22Test%22%7D
The server implementation:
#Path("/register")
public class RegisterEndPoint {
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response registerUser(UserDTO userDTO) {
// Create DAO for persistence
FactoryDAO factory = new FactoryDAO();
UserDAO userDAO = factory.getUserDAO();
// Create user to be persisted
if (!userDAO.userExist(userDTO.getEmail())) {
User user = new User();
user.setPassword(userDTO.getPassword());
user.setEmail(userDTO.getEmail());
user.setName(userDTO.getName());
userDAO.persist(user);
userDAO.commit();
return Response.status(200).build();
}
return Response.status(405).entity(new ErrorDTO("User already registered!")).build();
}
}
The problem seems to be in Native Plugin, so I've changed to the angular http solution, and it works fine. Follow below the solution which I've perform. Thanks everyone who helped me.
The imports required:
import { Http, Headers, RequestOptions, Response } from '#angular/http';
import { Observable } from 'rxjs/Rx'
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/timeout';
AuthProvider:
public sendRequest(sufix, json) {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(URL+sufix, json, options)
.timeout(TIMEOUT_REQUEST*1000)
.do(this.logResponse)
.map(this.extractData)
.catch(this.handleError)
}
private logResponse(res: Response) {
console.log(res);
}
private extractData(res: Response) {
return res.json();
}
private handleError(res: Response | any) {
return Observable.throw(res.json().error || 'Fail to connect to the server');
}
Calling the AuthProvider:
this.authProvider.sendRequest('register', this.signup).subscribe((data) => {
console.log('Success!');
}, (error) => {
console.log(error);
});
Providers included in app.module.ts
import { HttpModule, JsonpModule } from '#angular/http';
can you please try sending the body without making it a string. you can send the JSON Object without stringify. Give it a try :)
**UPDATE
After sending this
{name: 'Test'}
If you are getting name = "test"
Why dont you try like this
var data = JSON.stringify(data);
var obj = {data:data};
//send the obj Object
So it will show as data = "{name:test}"
Now Parse it from the server. Try and let me know :)
if you are trying to make post request using HTTP then try sending request in this format.
let body = new FormData();
body.append('name', 'Test');
this.http.post(<url>,body);
Try and lemme know if it works for you.
Just add this.http.setDataSerializer(‘json’) before do the post

Extjs4 / Spring MVC and response.responseText

In extjs4 controller i call
form.submit({
url: '/bookstore/api/books/add',
waitMsg: 'Uploading your file...',
success: this.onAddBookSuccess,
failure: function(response, opts){
var data = Ext.decode(response.responseText);
Ext.MessageBox.alert('Error', 'Some problem occurred' + data);
}
});
My spring mvc controller code for '/bookstore/api/books/add'
#RequestMapping(value = "/api/books/add", method = RequestMethod.POST)
public
#ResponseBody
Map<String, ? extends Object> addUser(BookUploadBean bean, BindingResult result) {
Map<String, Object> data = new HashMap<String, Object>();
if (bean.getTitle().compareTo("1") == 0) {
data.put("success", Boolean.FALSE);
data.put("errors", "asdasdasd");
return data;
}
Book book = new Book();
book.setTitle(bean.getTitle());
book.setAuthor(bean.getAuthor());
book.setYear(bean.getYear());
book.setPrice(bean.getPrice());
book.setDescription(bean.getDescription());
book = userRepository.save(book);
data.put("success", Boolean.TRUE);
return data;
}
I get from '/bookstore/api/books/add' 2 variants of json response:
Error json : {"errors":"asdasdasd","success":false}
Success json {"success":true}
And server really returned this values
But if i try get response.responseText, i get undefined value. How I can get "errors" values in my failure function?
When u submit a form you get the response still decoded into the property "result" of the second parameter of the callback.
So in your example:
form.submit({
url: '/bookstore/api/books/add',
waitMsg: 'Uploading your file...',
success: this.onAddBookSuccess,
failure: function(form, action){
Ext.MessageBox.alert('Error', 'Some problem occurred' + action.result.errors);
}
});
Hope this help :)

how to send json output through Servlet using JACKSON Streaming api

I am trying to call the servlet which suppose sends the data in jSON format as response. I am using JACKSON libraries for this, i can write the output to a file using jfactory.createJsonGenerator(file); if i use other than that i cannot get output. Let me know if i am missing something here.
doGet method from servlet
JsonFactory jfactory = new JsonFactory();
/*** write to file ***/
try {
out = response.getWriter();
JsonGenerator jGenerator = jfactory.createJsonGenerator(out);
jGenerator.writeStartObject(); // {
jGenerator.writeStringField("title", title); // "title" : title
jGenerator.writeStringField("Description", desc); // "desc" : Description
jGenerator.writeFieldName("images");
jGenerator.writeStartArray(); // [
for(String img: imageArray){
jGenerator.writeString(img); // "msg 1"
}
jGenerator.writeEndArray(); // ]
jGenerator.writeEndObject(); // }
//jGenerator.close();
out.flush();
System.out.println(jGenerator.getOutputContext().toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HTML page
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.getJSON("http://localhost:8080/JsoupPrj/JasonGen",function(data){
$("#content").html(data);
$('.log').html('it is called');
});
});
</script>
</head>
<body>
<div id="content"></div>
<div class="log"></div>
this may be late. but i thought i will share my experiences in case it helps someone.
here is a sample of my pom.xml:
<dependency>
<groupId> org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.12</version>
</dependency>
here is what i have in my servlet:
List<String> ooErrors = new ArrayList<String>();
//serialize the errors object.
ObjectMapper mapper = new ObjectMapper();
String errorsJson = mapper.writeValueAsString(ooErrors);
response.setContentType("application/json");
response.getOutputStream().print(errorsJson);
hopefully, this helps someone.

Example on consuming JSON in Play Framework views

I am trying to make the switch in a controller from sending JPA retrieved items as a List to the template engine to now send these as JSON.
I would prefer to use the flexJSON library for the task.
What I have is a Application controller with the method:
public static Result index() {
... Processing ...
flash("success", "Items have been processed");
return ok(index.render(Item.all()));
}
and a view index.scala.html like this one:
#(items: List[Item])
#import helper._
#main("Item list") {
<h1>#items.size() items(s)</h1>
<ul>
#for(item <- items) {
<li>
#item.title
</li>
}
</ul>
}
These to perfectly show an unnumbered list of all the processed items.
Now, if I changed the controller to using flexJSON like so:
public static Result getItems() {
List<Item> items = Item.all();
String s = new JSONSerializer().exclude("*.class", "description").serialize(items);
flash("success", "Messages have been processed");
return ok(index.render(s));
}
How would i program my template in order to consume that json string of items?
i tried to follow this blog on the matter, http://www.jamesward.com/2011/12/11/tutorial-play-framework-jpa-json-jquery-heroku, but fall short on how to consume the json in my template views... any code example would be greatly appreciated.
Just Sample it may help you.
application.conf
db.default.driver=org.h2.Driver
db.default.url="jdbc:h2:mem:play"
ebean.default="models.*"
routes
GET / controllers.Application.index()
GET /cities controllers.Application.all()
Controller => Application.java
package controllers;
import play.*;
import play.mvc.*;
import models.City;
import play.libs.Json;
import views.html.*;
public class Application extends Controller {
public static Result index() {
return ok(index.render());
}
public static Result all(){
City pune=new City();
pune.name="pune";
pune.save();
City mumbai=new City();
mumbai.name="mumbai";
mumbai.save();
return ok(Json.toJson(City.all()));
}
}
Template => index.scala.html
<!DOCTYPE html>
<html>
<head>
<title>Sample</title>
<script src="#routes.Assets.at("javascripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
</head>
<body>
<div id="content"></div>
<script type="text/javascript">
$(function(){
get_cities();
});
var get_cities = function() {
$.ajax({
url: '#routes.Application.all()',
processData:false,
type: 'GET',
beforeSend:function(jqXHR, settings){
jqXHR.setRequestHeader("Content-Type", "application/json");
},
success: function(data, textStatus, jqXHR){
process_cities(data);
},
error: function(jqXHR, textStatus, errorThrown){
},
complete: function(jqXHR,textStatus){
}
});
};
var process_cities = function(cities){
var contentDiv=$("div#content");
contentDiv.append("<ul>");
$.each(cities,function(i,city){
contentDiv.append("<li>" + city.name + "</li>");
});
contentDiv.append("</ul>");
};
</script>
</body>
</html>