How to update session attribute - java

I have some session attributes being saved. I have a jsp page on which a call to a servlet is made through. This servlet updates one of the session variable but I am not able to see the reflection of these changes in my jsp.Pls help.
In My servlet
List<DriverList> abc = dao.getABC();
request.getSession().removeAttribute("abc");
request.getSession().setAttribute("abc", abc);
In my jsp
function update()
{
var url = "updateServlet";
var req = $.ajax({
type: 'GET',
url: url,
cache: false,
type: "GET",
success: function()
{
latlng = [];
latlng = [<c:forEach var="test" items="${abc}">
[<c:out value="${test.latitude}"/>,<c:out value="${test.longitude}"/>,"<c:out value= "${test.name}" />",<c:out value="${test.cellNo}"/>],
</c:forEach> ];
},
error: function (status) {
}
});
}
The value of ${abc} is same as before. How to get the new value ?
The exact flow -
when login servlet is called abc value as sessionAttribute is set.
Now this redirects to base.jsp. I use abc for the first time. Now after every 30 seconds this update() function is called. This update function calls a servlet through ajax where the session attribute abc is updated.
In the success function of ajax request I want to use this new abc value but getting the old one again.

To access the abc variable in the JSP try:
${sessionScope.abc}
Also note that removing before setting is usually redundant. So:
request.getSession().removeAttribute("abc");
request.getSession().setAttribute("abc", abc);
Can simply become:
request.getSession().setAttribute("abc", abc);

I had similar problem.
It turned out that when you use
HttpSession
object in your controller, it shouldn't be annotated using
#SessionAttributes

Related

Ajax call returns string for Highcharts series but result is wrong (parsing error?)

I'm developing a Java Spring-Hibernate application that uses Highcharts. I've got a JavaScript function that, when called, it makes an Ajax call to get the chart data (series) and creates the chart with it:
<!-- Stacked bar chart -->
<script type="text/javascript">
//Function that plots the highcharts chart
function plot(park) {
$.ajax({
type: "get",
url: "MainView/report/datagaps/" + park,
dataType: "text",
error: function (error) {
console.log(error);
alert('Error while requesting datagaps for ' + park + ' : ' + error);
},
success: function (result) {
$("#chart" + park).highcharts({
chart: {
type: 'column'
},
series: result
});
}
});
}//END_FUNCTION
</script>
I've removed most of the plot options code, so you see the most relevant code above. There is a model method that deals with this request:
#RequestMapping(value = "/datagaps/{parkName}", method = RequestMethod.GET)
public #ResponseBody String datagaps(#PathVariable String parkName, Map model, HttpSession session) {
LOGGER.debug("Successfully called datagaps for '" + parkName + "'");
LOGGER.debug((String) session.getAttribute("chartData"+parkName));
return (String) session.getAttribute("chartData"+parkName);
}//END_METHOD
The method is quite simple: a session string variable is returned, which is the one that should be used in series: result.
The thing is that this generates an unexpected result:
However, if I set a model variable session.setAttribute("chartData" + park, rrdao.getParkData().get(park)); before loading the form and I use it instead of the result like series: ${chartDataAA}, it works:
This is quite weird, since the data used is exactly the same: both ajax call and model variable come from the same place, and they are logged before beign send, which allows me to be sure data is good. This data has a format like [{name:'AA01', data: [[1412114400000,0],[1412200800000,0],[1412287200000,0],[1412373600000,0],[1412460000000,0],[1412546400000,0],[1412632800000,0]}]
I bet is some kind of string parsing problem when it is returned from the ajax call, perhaps due to the single quotations, but I don't know how to deal with it.
Please help!
Maybe it is misspelling, but your single serie which you have as missing bracket in data array. It should be: [{name:'AA01', data: [[1412114400000,0],[1412200800000,0],[1412287200000,0],[1412373600000,0],[141246‌​0000000,0],[1412546400000,0],[1412632800000,0]] }]
Change: dataType: "text" to dataType: "json"
Then in the controller if you use jackson json just return a List

Call 2 Ajax calls in one using Jquery Ajax

I have a problem in posting the selected values to the database with mismatching values.Here is the scenario where the ajax call maps to the respective Java function. The problem is, I am not getting correct selected values in the DB when the user logs in for the first time. Kindly provide a solution....
Here is my Jquery Ajax
if(selectedproductIds != '')
{
$.ajax({
url : "selectedProducts",
data : "selectedproducts="+selectedproductIds,
type : "POST",
success : function(data) {
}
});
$.ajax({
url : "<c:out value= "${saveDemoURL}"/>",
data : request,
type : "POST",
success : function(data) {
showNotification({
message : "",
type : "success",
autoClose : true,
duration : 5
});
resetForm();
alert("Demo Request Saved Successfully");
}
});
The first ajax call maps to this java function
#RequestMapping(value = "/selectedProducts")
public #ResponseBody
String getSelectedProducts(
#RequestParam(value = "selectedproducts") String[] selectedproducts,
Map<Object, Object> map) {
List<Product> selectedProd = new ArrayList<Product>();
for (String prod : selectedproducts) {
Product product = new Product();
product.setId(Integer.parseInt(prod));
selectedProd.add(product);
}
if (!Util.isEmpty(selectedProd)) {
map.put("selectedproducts", selectedProd);
}
for (Product product: selectedProd) {
LOGGER.info("Demo ID:"+ " List of selected products:"+product.getId());
}
selectedProdList = selectedProd;
return "success";
}
The second Ajax call maps to this java function
#RequestMapping(value = "/saveDemo")
public #ResponseBody
Map<Object, Object> saveDemo(#ModelAttribute("demoBean") DemoBean demoBean,
Model model, Map<Object, Object> map) {
Map<Object, Object> output = null;
Demo demo = new Demo();
try{
......
}
catch{.....}
return output;
}
Change your code to this format: $.ajax().ajax;:
if(selectedproductIds != '')
{
$.ajax({
url : "selectedProducts",
data : "selectedproducts="+selectedproductIds,
async: false,
type : "POST",
success : function(data) {
}
}).ajax({
url : "<c:out value= "${saveDemoURL}"/>",
data : request,
async: false,
type : "POST",
success : function(data) {
showNotification({
message : "",
type : "success",
autoClose : true,
duration : 5
});
resetForm();
alert("Demo Request Saved Successfully");
}
});
I'm not 100% certain I understand what your two functions are doing, but if I'm right and you're trying to perform something which would normally be wrapped in a transaction then you do not want to coordinate that from the front-end at all. A classic example of a transaction is taking money out of one person's account and putting it into another. If that process gets interrupted in the middle due to power failure, laptop reboot, network problems, etc. then the whole thing needs to go back to its original state, otherwise money can just disappear from one account and never go anywhere.
I want to refer you to this question: jQuery deferred chaining problems
It's a little different because the author has already figured out that promises may be a key to getting things to happen together. But notice that I answer it twice. The second time is to specifically to explain that transactions should never be coordinated from the front-end. If you have two database operations that must always complete together then you must have only one API call which receives all the data needed for both calls and you do them together on the back-end. Technically, even then you should use something like database transactions on the back-end to wrap them so a power failure back there won't leave you with half an operation completed. But failures in the middle of your multi-step processes are 1000% more likely if you try to execute them across the network between a browser and a server. Get that logic into the server where it belongs.

Passing name from input to servlet

I have an input:
Now this is one input from a div with several different inputs, there is a button called add exp which generates a new div with those inputs by calling href="#" and then jquery does the rest, only the name changes to for example institutionName0, institutionName1 etc so the fields get distinct. In my servlet I want to be able to get the actual input name like institutionName0 so I can check how much of the same fields are generated and that I can put in different values in those different fields.
You can send your form values to Servlet as a jSon object using ajax.
//Example
function onSubmit(divName){
document.forms["formName"]["formName_currentAction"].value = divName;
var theForm = $("form[name=formName]");
var params = theForm.serialize();
$.ajax({
type:"POST",
url:actionURL,
cache: false,
data:params,
success:function(data, textStatus, XMLHttpRequest){
//do something here
},
error:function(XMLHttpRequest, textStatus, errorThrown){
}
});

Is it possible to pass multiple parameters for javascript JSON AJAX POST to Spring MVC controller?

I have the already working javascript AJAX POST like this:
Client side:
<script language="JavaScript" type="text/javascript">
var column = "test1";
var filterType = 1;
var values = [];
var filter = { "column" : column, "filterType" : filterType, "values": values};
var filter2 = { "column" : column, "filterType" : filterType, "values": values};
filter2.column = "test2";
var filters = new Array();
filters[0] = filter;
filters[1] = filter2;
$.ajax({
url: "${pageContext.request.contextPath}/api/user_administration/get",
data: JSON.stringify(filters),
type: "POST",
beforeSend: function(xhr)
{
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(user)
{
}
});
</script>
Server side:
#RequestMapping(value = "user_administration/get", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public List<User> get(#RequestBody ColumnFilter[] filters)
{
//do something
return userService.getAll();
}
Now I want to pass two or more parameters. Something like this:
#RequestMapping(value = "user_administration/get", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public List<User> get(#RequestBody ColumnFilter[] filters, #RequestBody ColumnSorter[] sorters)
{
//do something
return userService.getAll();
}
Is it possible to achieve this? How?
(I already am aware that I can just encapsulate them into another object/class/entity)
In your AJAX call you have the line
data: JSON.stringify(filters),
Change or extend this line to add additional parameters to the request. And if you're not clear what's going on or need to log/diagnose/debug it, you can always use an intermediate variable..
You can either pass data as a Javascript key-value object (giving named parameters), a String, or -- as the existing code does -- by JSON encoding an object.
Since you appear to want to pass more fields/parameters & are using JSON encoding already, it probably makes most sense to built these into a larger 'payload' object before JSON encoding.
var paramData = {filter:filters, sorters: mySortersOrWhatever};
console.log('some administration AJAX request', paramData);
$.ajax({
...
data: JSON.stringify(paramData)
See how this interfaces with Spring's request-parsing -- to decode two separate parameters on the Spring side you'll either need names (not just the request-body), decode them from named parameters, or else (simplest) just accept one big JSON object as the parameter.
This should be reasonably straight-forward -- as always, follow basic software-engineering principles (log it, diagnose it, fix it until it works) so you can build the required working functionality.
Spring documentation says:
The #RequestBody method parameter annotation indicates that a method
parameter should be bound to the value of the HTTP request body.
This assumes that HTTP request body is not divisible. Hence all you need to do is to follow the workaround.Here you can see exactly the same question Spring REST multiple #RequestBody parameters, possible?

Calling a java method with parameter value set from dropdown select in jsp

My task is to select a value in one dropdown, and with that value as a parameter, invoke a java method.
I tried setting a hidden input when via onChange, a javascript function is called, but could not use that value for passing as a parameter. (I have a bean, that has the method which i need to invoke from jsp after selecting value from dropdown)
You can make Ajax call to the servlet with XMLHttpRequest object in JavaScript.
You can make a successful call to servlet as:
<script>
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4) {
var data = req.responseText;
//HANDLE RESPONSE HERE;
}
}
req.open('GET', 'servletName', true);
req.send(null);
</script>
In servlet, handle the parameter passed from dropdown in request and accordingly, call java method and send response text as:
String responseData = "Output for your selection is : " + XXXX + "!";
response.setContentType("text/plain");
response.getWriter().write(responseData);
Test crossbrowser compatibility before using it.

Categories