how to write hibernate spatial query? - spring

This is homePage.jsp code :
<button id="bilgial" onclick="getVector(id)">Get Vector</button>
<input type="text" id="hs">
and this is getVector(id) function :
var id = document.getElementById("hs").value;
function getVector(id) {
ajax({
type: "GET",
path: "/getGeoJson",
data: {id: id},
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function (data) {
var parser = new OpenLayers.Format.GeoJSON();
var feature = parser.read(data.data);
if (feature.length != 0) {
feature[0].attributes.id = data.id;
}
vectors.addFeatures(feature);
}
});
}
this is my controller get method :
#Controller
public class HSpatialController {
SavegeojsonManager add = new SavegeojsonManager();
#RequestMapping(value = "/getGeoJson", method = RequestMethod.GET)
#ResponseBody
public GeoJSON getGeoJson( final HttpServletRequest request,#RequestParam("id") final String vectorId) {
return add.get(vectorId);
}
}
and this is SavegeojsonManager class and get method :
public GeoJSON get(String id) {
GeoJSON geoJson = new GeoJSON();
EntityManager em = HibernateSpatialJPA.createEntityManager();
em.getTransaction().begin();
Query query = em.createQuery("select e from SavegeojsonEntity ????")
query.setParameter("", ??);
return geoJson;
}
or how can I do otherwise ?
I want to was eat with the number that was in the database that you want to take the data from the TextBox equally with data GetData ?

So code should be like this:
public GeoJSON get(String id) {
GeoJSON geoJson = new GeoJSON();
EntityManager em = HibernateSpatialJPA.createEntityManager();
em.getTransaction().begin();
Query query = em.createQuery("from SavegeojsonEntity s where s.id = :id")
query.setParameter("id", Integer.valueOf(id));
List entityList = query.getResultList();
if(entityList != null && !entityList.isEmpty()){
SavegeojsonEntity entity = (SavegeojsonEntity)entityList.get(0);
geoJson.setType(entity.getVectorType());
if(entity.getVectorType().equals("Point")){
geoJson.setData(entity.getPoint());//or entity.getXXX() since you need to get point data,
} else if(...){
//same for Polygon/MultiPolygon/StringLine and so on
}
}
em.getTransaction().close();
return geoJson;
}

Related

Post ajax values to MVC Action Result

Ok, so I have the following Ajax get request going to a [HttpPost] controller method in an ASP.NET MVC 5 application.
The javascript function shown here successfully posts the values to the server side:
<script>
function get_row() {
var one = document.getElementById("data_table").rows[1].cells[0].innerHTML;
var two = document.getElementById("data_table").rows[1].cells[1].innerHTML;
var result = one + "," + two;
//var result = {};
//result.one = document.getElementById("data_table").rows[1].cells[0].innerHTML;
//result.two = document.getElementById("data_table").rows[1].cells[1].innerHTML;
if (result != null) {
$.ajax({
type: 'get',
url: "/Manage/CreateGroupRoleRestriction",
//url: '#Url.RouteUrl(new{ action= "CreateGroupRoleRestriction", controller= "Manage", one = "one", two = "two"})',,
data: { one, two },
//params: { one, two }
/*dataType: String,*/
//success: alert(result)
});
}
else {
alert("Error");
}
}
</script>
However, the issue is that the string values will not post to the Action Result, see below.
The values "one" and "two" are null.
[Authorize(Roles = "Admin")]
[HttpPost]
[Route("/Manage/CreateGroupRoleRestriction?{one,two}")]
[ValidateAntiForgeryToken]
public ActionResult CreateGroupRoleRestriction(FormCollection formCollection, string message2, string one, string two)
{
UserDataBusinessLayer userDataBusinessLayer = new UserDataBusinessLayer();
userDataBusinessLayer.Restrict1(message2);
UserDataBusinessLayer userDataBusinessLayer2 = new UserDataBusinessLayer();
userDataBusinessLayer2.Restrict2();
try
{
UserData userData = new UserData();
TryUpdateModel(userData);
if (ModelState.IsValid)
{
userData.RoleName = formCollection["RoleName"];
UserDataBusinessLayer userDataBusinessLayer3 = new UserDataBusinessLayer();
userDataBusinessLayer3.CreateGroupRestriction(userData, message2, one.ToString(), two.ToString());
return RedirectToAction("CreateGroupRoleRestriction");
}
else
{
userData.RoleName = formCollection["RoleName"];
UserDataBusinessLayer userDataBusinessLayer4 = new UserDataBusinessLayer();
userDataBusinessLayer4.CreateGroupRestriction(userData, message2, one.ToString(), two.ToString());
return RedirectToAction("CreateGroupRoleRestriction");
}
}
catch (Exception ex)
{
Logger.Log(ex);
return RedirectToAction("CreateGroupRoleRestriction");
}
}
Please try changing 'type' in ajax to 'post'.
type: 'post'

How return a empty JSON in Spring MVC?

I'm using ajax with GET method, I'm waiting receive a JSON but sometime the response is null and get the error:
SyntaxError: Unexpected end of JSON input
ajax:
$(document).ready(function() {
$("#form_data").submit(function(e) {
e.preventDefault()
var expediente = $('#expediente').val();
$.ajax({
url : 'buscarPaciente' + '?expediente=' + expediente,
dataType : "json",
type : "GET",
contentType : 'application/json',
mimeType : 'application/json',
success : function(data) {
console.log(data.nombre);
},
error : function(xhr, status, error) {
console.log(error)
}
});
})
});
in the controller:
#RequestMapping(value="/buscarPaciente", method = RequestMethod.GET)
public #ResponseBody MntPaciente
buscarPaciente(#RequestParam("expediente") String expediente) {
MntPaciente mntPaciente = servicePx.findByexpediente(expediente);
if (mntPaciente!= null) {
return mntPaciente;
}
return null; // Should I return an empty json? how?
}
There are several ways to do it. The first is to configure the JSON library that used to serialise JSON .In case of Jackson , you can use #JsonInclude to exclude all the empty properties not to serialise and just return an empty MntPaciente :
#JsonInclude(Include.NON_EMPTY)
public class MntPaciente {
}
public #ResponseBody MntPaciente buscarPaciente(#RequestParam("expediente") String expediente) {
....
return new MntPaciente();
}
To apply globally rather to configure for each object , you could use
ObjectMapper om = new ObjectMapper();
om.setSerializationInclusion(Include.NON_EMPTY);
The other way is to change the controller method to return ResponseEntity and directly return a empty JSON string :
public #ResponseBody ResponseEntity buscarPaciente(#RequestParam("expediente") String expediente) {
if (mntPaciente!= null) {
return ResponseEntity.of(mntPaciente);
}else{
return ResponseEntity.of("{}");
}
}

send data from ajax to spring controller

var form_data = {
itemid: globalSourceItem.substr(globalSourceItem.indexOf("-") + 1),
columnName: jqInputs[0].value,
displayName: jqInputs[1].value,
format: jqInputs[2].value,
KBE: jqInputs[3].value,
dgroup: jqInputs[4].value,
dupkey: jqInputs[5].value ,
measurement: jqInputs[6].value ,
times: new Date().getTime()
};
// console.log(form_data);
// console.log($("#tourl").html());
$.ajax({
url: $("#tourl").html(),
type: 'POST',
datatype: 'json',
data: form_data,
success: function(message) {
var j_obj = $.parseJSON(message);
// console.log(j_obj);return false;
if (j_obj.hasOwnProperty('success')) {
toastr.info('Item updated successfully');
setTimeout(function(){
window.location.reload();
},1000);
} else {
toastr.info('There was a problem.');
}
},
error: function(xhr, textStatus, errorThrown)
{
toastr.info('There seems to be a network problem. Please try again in some time.');
}
});
}
Hii friends , this code is working for php and i need to send the same data to the spring mvc through the ajax , can anyone please help me with the exact solution where to make changes as Iam struckup with the same doubt for like 2 weeks...
public class TestController {
#RequestMapping(value = "url", method = RequestMethod.POST)
public ModelAndView action(#RequestBody FormData formData) {
...
}
}
public class FormData {
private String itemid;
public String getItemid() {
return itemid;
}
public void setItemid(String itemid) {
this.itemid = itemid;
}
//...
}
Try sth like this. You should be able to map JSON Object to Java Object.
Maybe you could use annotation #ResponseBody and convert JSONObject to String:
#RequestMapping(value = "/ajax", method = RequestMethod.POST, produces="application/json")
#ResponseBody
public String ajax(#RequestBody ListDataDefinition listDataDefinition) {
System.out.println("id="+listDataDefinition.getItemid());
int i=SchemaDAOI.updateldd(listDataDefinition);
String message="success";
JSONObject obj = new JSONObject();
try {
obj.put("success", "success");
}
catch (JSONException e) {
e.printStackTrace();
}
if(i==1){
System.out.println("success");
}
else{
System.out.println("failure");
}
return obj.toString();
}
}
If you send String to View as ResponseBody and set produces as JSON it should be treated as pure JSON RQ.

Spring 4 Jackson Hashmap to Json losing ordering of keys

I am using Spring 4 and Jackson. I am trying to return a LinkedHashMap from controller to Ajax Response.
However when Jackson is converting it to JSON the order of keys in the LinkedHashMap is getting lost.
How can I maintain the order of records.
Controller code:
#ResponseBody
#RequestMapping(value = "/getLevel2", method = RequestMethod.POST)
public LinkedHashMap<String, String> getLevel2(HttpServletRequest request)
{
System.out.println("In getLevel2"+request.getParameterNames());
String catId=request.getParameter("catId");
String fkey=request.getParameter("key");
LinkedHashMap<String, String> h=categoryService.getCategoryLevel2Map(2100,fkey);
System.out.println(h);
return h;
}
Ajax call:
var jqxhr = $.ajax({
type: "POST",
url:"/a2bNext/getLevel2",
cache: false,
data:'catId='+ catId+'&key='+selectedValue
} )
.done(function(data) {
$("#level2").empty();
for (var key in data) {
value=data[key];
isLeaf=value.split('::')[1];
value=value.split('::')[0];
if(isLeaf==1)
{
option = $('<option></option>').attr("value", key).text(value);
$("#level2").append(option);
}
else
{
option = $('<option></option>').attr("value", key).attr("class","subdivide").text(value);
$("#level2").append(option);
}
}
$("#level2").show();
})
.fail(function() {
alert( "error1" );
})
.always(function() {
//alert( "complete" );
});
});
Could anyone suggest how can I get the keys in ajax response in the same order as in LinkedHashMap.

Dynamically Populate Drop down List In Spring MVC

I am new to Spring MVC. I have two Dropdown Lists in Jsp.One for country and Other for State. As soon as i select country from list State list should be populated with respective lists.
My ajax Program:
$("select#country").change(function() {
var val=$("#country").val();
alert(val);
$.ajax({
url : 'getstates',
method : 'get',
contentType: 'application/json',
data :{
country : val
},
success: function (data) {
alert("Success Response"+ data);
},
error :function()
{
alert("error");
}
});
My Controller Program:
public #ResponseBody HashMap<String, String>
showstates(#RequestParam(required = false, value = "")
String country,#Valid #ModelAttribute("employee")Login employee,
BindingResult result, ModelMap model) {
HashMap<String,String> statelist = new HashMap<String,String>();
List<States> statelist = new ArrayList<States>();
if (country.equals("UnitedStates")) {
statelist.put("Al","Alaska");
statelist.put("Tl","Texas");
} else if (country.equals("India")) {
statelist.put("Mh","Maharashtra");
statelist.put("WB","West Bengal");
statelist.put("KR","Karnataka");
statelist.put("AP","Andhra Pradesh");
statelist.put("TN","Tamil Nadu");
}
return statelist;
}
I am not getting the response from controller. How to access the hasmap in jsp. Please Help me. Thanks.
I think you should change your method like below.
#RequestMapping(value = "/getstates", method = RequestMethod.GET)
public #ResponseBody HashMap<String, String> showstates(#RequestParam(required = false, value = "")
String country,#Valid #ModelAttribute("employee")Login employee,
BindingResult result, ModelMap model) {
HashMap<String,String> stateMap = new HashMap<String,String>();
//put your logic to add state on basis of country
return stateMap;
}
Then on JSP you can simply iterate this map,like below.
<c:forEach items="${state.stateMap}" var="data" varStatus="status">
<tr>
<td>${data.value}</td>
</tr>
</c:forEach>
shearing my solution. because i was stuck in same condition.
html page
$(document).ready(function() { // for client name
$('#example').change(function(event) {
var country = $("select#example").val(); // country = define value of selected option
$.getJSON('ajaxAction0', {
ptype : country
}, function(data) {
var select = $('#clientname');
select.find('option').remove();
$.each(data, function(key, value) {
$('<option>').val(key).text(value).appendTo(select);
});
});
});
});
<div>
<select class="form-control" name="example" id="example">
<option value="0">ALL</option>
<option th:each="dropdown : ${dropdown}" th:value="${dropdown.id}"
th:text="${dropdown.tagName}"></option>
</select> <select class="form-control" name="clientname" id="clientname">
<option value="0">ALL</option>
<option th:each="dropd : ${drpdwn}" th:value="${dropd.id}"
th:text="${dropd.tagName}"></option>
</select>
<button id="w-button-search" type="button">Search</button>
</div>
controller code for first drop down
#RequestMapping(value = "/dropdown", method = RequestMethod.GET)
public String dropDown(Model model) {
List<Tag> data = new ArrayList<>();
data.add(new Tag(1, "ruby"));
data.add(new Tag(2, "rails"));
data.add(new Tag(3, "c / c++"));
data.add(new Tag(4, ".net"));
data.add(new Tag(5, "python"));
data.add(new Tag(6, "java"));
data.add(new Tag(7, "javascript"));
data.add(new Tag(8, "jscript"));
model.addAttribute("dropdown", data);
return "dropDown";
}
second drop down code is
Map <\string, string> udata = null;
#RequestMapping(value = "ajaxAction0", method = RequestMethod.GET)
public #ResponseBody Map<String, String> findAllAgencies(
#RequestParam(value = "ptype", required = true) String ptype) {
udata = new HashMap<>();
EntityManager em = entityManagerFactory.createEntityManager();
em.getTransaction().begin();
List<UserRecord> user = em
.createNativeQuery("Select id, name, email from user_Record where id = :uid", UserRecord.class)
.setParameter("uid", ptype).getResultList();
for(UserRecord ur:user) {
udata.put(ur.getEmail(), ur.getName());
}
return udata; }
hope it will help.
You can obtain a list of states based on the country:
#Autowired
StateService stateService;
#GetMapping("/states")
public #ResponseBody List<State> getStates(#RequestParam String country) {
return stateService.getStates(country) ;
}
your State class will contain code and name;
$("select#country").change(function() {
var countryVal = $("#country").val();
$.ajax({
url : '/states?country='+countryVal,
method : 'GET',
},
success: function (states) {
var stateSelect = $('#state'); // the state select element
stateSelect.find('option').remove();
for (i = 0; i < states.length; i++) {
stateSelect.append("<option value=" + states[i].code + " >" + states[i].name + "</option>")
}
},
error :function()
{
alert("error");
}
});

Resources