Java Servlet & jQuery AJAX - unable to retrieve object from session - java

Not sure how to solve this, need some help here.
Ajax call brings user information to servlet, I save user object in HttpSession and control goes back to Ajax from where i redirect control to next JSP page via controller servlet. However, if i try to retrieve object from HttpSession it is null .. not sure how to solve this issue.
here is my code for firstservlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// get values from http request
// persist "user" object to database
HttpSession session = request.getSession(); //
session.setAttribute("user", user); //setting session variable
Gson gson = new Gson();
JsonElement jsonElement = null;
jsonElement = gson.toJsonTree("/nextservlet");
response.setContentType("text/plain");
PrintWriter out=response.getWriter();
}
here is my Javascript / AJAX code to redirect request to nextservlet
$.ajax({
type: 'POST',
url: ‘firstservlet’,
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(quiz),
success: function(result) {
//result = /nextservlet
window.location.href = result;
},
error:function(data,status,er) {
console.log("Error:",er);
}
});
and finally control comes to nextservlet - where i would like to process data and then show new JSP page.
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
HttpSession session = request.getSession();
User user = session.getAttribute(“user”); //<--- this is NULL
LOG.warning("User id is : " + user.getId()); //<--- hence error here
RequestDispatcher dispatcher = request.getRequestDispatcher
("/anotherpage.jsp");
dispatcher.forward(request, response);
}
is issue because i am using -> window.location.href = result to send request to nextservlet .. and it goes to doGet??

I am not sure it but I see in Ajax
url: ‘firstservlet’,
type: 'POST'
and control goes to doGet method of nextservlet. It should be nextservlet of post method so use method doPost.

18.12.22
i'm not sure... but try it
success: function(result) {
// result = /nextservlet
var form = document.createElement('form');
form.action = result;
form.method = 'GET'
form.submit();
}
18.12.26
Javascript
$.ajax({
type: 'POST',
url: '/firstservlet',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringfy(quiz),
success: function(result) {
console.info(result);
var form = document.createElement('form');
form.action = result;
form.method = 'GET';
document.body.appendChild(form);
form.submit();
},
error: function(data, status, err) {
console.log("Error: ", err);
}
});
Servlet
HttpSession session = request.getSession();
session.setAttribute("test", "test");
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree("/nextservlet");
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.print(gson.toJson(jsonElement));
It can read session attribute in doGet Method try it.

Related

Unable to get Json object in servlet?

I am trying to read a json object that I sent from my ajax to servlet but then I keep receiving null as the value. I tried to log the json object that I am sending from my ajax and it looks fine to me. Can someone tell me what could be my error?
$(document).on("click", "#check", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
event.preventDefault();
var data = $("#register").serialize().split("&");
var obj={};
for(var key in data)
{
console.log(data[key]);
obj[data[key].split("=")[0]] = data[key].split("=")[1];
}
console.log(obj);
$.ajax({
type: "POST",
url: "HomeServlet",
dataType:'json',
data:JSON.stringify(obj),
success: function(data){
console.log(data);
},
error:function(){
console.log("error");
},
});
});
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json");
PrintWriter out= response.getWriter();
String data = request.getParameter("obj");//this is what I get as null
String n = request.getParameter("apiname");
String p = request.getParameter("apiendpoint");
String e = request.getParameter("apiversion");
}
The json object that I am sending
{
"apiname": "jdjdj",
"apiendpoint": "sdjsdj",
"apiversion": "djdjd",
"source": "internet"
}

How to return JSON object to AngularJS using Java Servlet

I have to write a controller in my project using servlets. I've done it before but I've never worked with AngularJS, so I did it via request.setAttribute() and request.getParameter() and put Java code inside of a JSP page. But now frontend developer used AngularJS and I have to return him a JSON object. And I have no idea how to do it. Here's the code of abTestCtrl.js:
app.controller("abTestCtrl", function($scope, $location, $http) {
$scope.title = "no title";
$scope.description = "no description";
$scope.getParam = $location.search()['id'];
if($scope.getParam === undefined)$scope.getParam = 0;
//$scope.getParam=2;
//path: localhost8080/UIUM.../servlet-name.java
//with two ids
//web.xml: serverlet mapping for the path
if($scope.getParam==='0'||$scope.getParam === 0){
var saveButton = document.getElementById("saveButton");
saveButton.classList.remove("hidden");
}
else{
$http.get('http://localhost:8080/UIUM_IMT4003/ABTestController', {command:'getTestCaseInfo', testcaseID:$scope.getParam}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log('request succesful');
console.log(data);
console.log(status);
console.log(headers);
console.log(config);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log('request not succesful');
});
}
and my processRequest() code from the servlet:
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, ClassNotFoundException {
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/json; charset=UTF-8");
//PrintWriter printout = response.getWriter();
JSONObject jObject = null;
RequestDispatcher view = null;
TestcaseRepository testcaseRepo = new TestcaseRepository();
String command = request.getParameter("command");
if(command == null)
{
view = request.getRequestDispatcher("/testcases.jsp");
view.forward(request, response);
}
if(command.equals("getTestCaseInfo")){
String testcaseId = request.getParameter("testcaseID");
Testcase testcase = testcaseRepo.getTestcaseById(testcaseId);
jObject = new JSONObject();
jObject.put("id", testcaseId);
jObject.put("title", testcase.getTestcaseName());
jObject.put("testscenario", testcase.getTestcaseDescription());
// printout.print(jObject);
// printout.flush();
jObject.write(response.getWriter());
}
Can you please help me to process this request and finally return this poor JSON!
BTW, Servlet doesn't recognize command parameter. It gets null. But there is such parameter in AngularJS function.
Try using the javax.json.JsonObject as follow:
JsonObject jo=Json.createObjectBuilder()
.add("id", testcaseId)
.add("title", testcase.getTestcaseName())
.add("testscenario", testcase.getTestcaseDescription()).build();
Then set the response content type to json and send your json object in the response:
response.setContentType("application/json");// set content to json
PrintWriter out = response.getWriter();
out.print(jo);
out.flush();

Ajax call to jsp and jsp redirecting to further jsp

I am having an ajax call to a jsp page which in turn is redirecting depending on the value of a flag variable being calculated in that jsp file.
ajax call is something like this :
$.ajax({
url: 'uploadwebcamimage.jsp',
type: "POST",
data: {
encodeimg: dataUrl,
OwnerId: document.Clickpictures.OwnerId.value,
OwnerPhone: document.Clickpictures.OwnerPhone.value,
mobilepass: document.Clickpictures.mobilepass.value,
emailpass: document.Clickpictures.emailpass.value,
mypassword: document.Clickpictures.mypassword.value,
mygroupuserid: document.Clickpictures.mygroupuserid.value
},
error : function(){
alert('Error');
},
success: function(msg){
//alert((msg));
if(msg.indexOf("true")>=0)
{
//how to get grouplist
location.href="site_index_groupadmin.jsp?res1="+grouplist;
}
else{
alert("UNSUCCESSFUL");
}
}
});
And in jsp i did something like this :
<%
ArrayList<String> list = new ArrayList<String>();
String query="Select GNAME from tbGroup";
ps1 = con.prepareStatement(query);
rs1=ps1.executeQuery();
while(rs1.next()){
list.add(rs1.getString("GNAME"));
}
//How can i send this list also to my ajax call.Please help
if(flag==true){
out.println(flag);
}
else if(flag==false){
out.println(flag);
}%>
But its not redirecting to other page.Please help
When you call a jsp via AJAX, you stay on the same page by definition, regardless of the headers sent by the server.
If you want to change the page, you must do it with javascript, in the success handler function for the $.ajax(..) call.
You can read the Location response header and set the window.location.href to that value. See here for other options.
Get PrintWriter object by calling HttpServletResponse#getWriter and write your String.
response.getWriter().write("{isSuccess: true}");
now in jsp check isSuccess is true or false and use window.location.href
How can i send this list also to my ajax call.
use Gson or any other json library to write json response do like:
<%# page language="java" contentType="application/json; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
//after generating your list
Gson gson = new Gson();
JsonObject root = new JsonObject();
root.addProperty("flag", flag); //add flag
root.addProperty("list", gson.toJson(list)); //add list
out.println(gson.toJson(root));
out.flush();
%>
and render list in ajax like:
$.ajax({
url: 'uploadwebcamimage.jsp',
type: "POST",
dataType: 'json', //set dataType as json i.e. response data format
data: {
encodeimg: dataUrl,
OwnerId: document.Clickpictures.OwnerId.value,
OwnerPhone: document.Clickpictures.OwnerPhone.value,
mobilepass: document.Clickpictures.mobilepass.value,
emailpass: document.Clickpictures.emailpass.value,
mypassword: document.Clickpictures.mypassword.value,
mygroupuserid: document.Clickpictures.mygroupuserid.value
},
error : function(jqXHR, textStatus, errorThrown){
alert(textStatus+' : '+ errorThrown);
},
success: function(response){
alert(response.flag);
$.each(response.list, function(key,value){
alert(value);
});
}
});
Edit:
As per your comment:
create a servlet instead of writing java code in jsp, and move java codes to servlets like:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ArrayList<String> list = new ArrayList<String>();
String query="Select GNAME from tbGroup";
ps1 = con.prepareStatement(query);
rs1=ps1.executeQuery();
while(rs1.next()){
list.add(rs1.getString("GNAME"));
}
//set flag
boolean flag = true;
Gson gson = new Gson();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.write(gson.toJson(new ResponseResult(flag, list)));
out.flush();
}
and ResponseResult class looks like:
public class ResponseResult {
private boolean flag;
private List<String> list;
public ResponseResult(){}
public ResponseResult(boolean flag, List<String> list) {
super();
this.flag = flag;
this.list = list;
}
//getters and setters
}
if you want to send list to any other jsp, then in servlet do like:
using request if you do forward:
request.setAttribute("list", list);
RequestDispatcher dispatcher = request.getRequestDispatcher("pagename.jsp");
dispatcher.forward(request, response);
or alternate is using session if you do redirect then like:
//add list to session
request.getSession().setAttribute("list",list);
//get it back in another page like
List<String>myListObject=(List<String>) request.getSession().getAttribute("list");

AJAX error [object,Object]

this is java code ;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String,Object> hsssmap= new HashMap<String,Object>();
hsssmap.put("a","true");
hsssmap.put("b","true");
write(response,hsssmap);
}
private void write(HttpServletResponse response, Map<String,Object> hsssmap) throws IOException {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
Gson gson = new Gson();
String json = gson.toJson(hsssmap);
response.getWriter().write(json);
}
Here is js code ;
$(document).ready(function(){
$.ajax({
url: 'uri',
type: 'POST',
dataType: 'json',
data: data,
success: function(data){
$.each (data, function (key,value) {
alert(key+" "+value);
});
},
error: function (e) {
alert("error : " + e);
}
});
return false;
});
success event doesnt work. how to fix it ?
Try to check if the page return some values or not...
try to add alert in success to check it..
try the following
$.post( "uri", function(data) {
alert( "success" + data.a + data.b );
})
if this return you data then your server side servlet working

Jquery ajax call is not hitting servlet

I am trying to make a simple ajax call. No matter what I do, it always executes the error block. I have a sysout in the doPost that is never hit. Someone please tell me what I am doing wrong. Here is my code.
javascript----
$.ajax({
url: "GetBulletAjax",
dataType: 'json',
success: function(data) {
alert("success");
},
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR+" - "+textStatus+" - "+errorThrown);
}
});
Java----
public class GetBulletAjax extends HttpServlet {
private static final long serialVersionUID = 1L;
public GetBulletAjax() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("made it to servlet");
PrintWriter out = response.getWriter();
User user = (User) request.getSession().getAttribute("user");
int userId = user.getId();
List<Bullet> bullets;
BulletDAO bulletdao = new BulletDAOImpl();
try {
bullets = bulletdao.findBulletsByUser(userId);
Gson gson = new Gson();
String json = gson.toJson(bullets);
System.out.println(json);
out.println(json);
out.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
web.xml----
<servlet>
<servlet-name>GetBulletAjax</servlet-name>
<servlet-class>bulletAjax.GetBulletAjax</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetBulletAjax</servlet-name>
<url-pattern>/GetBulletAjax</url-pattern>
</servlet-mapping>
What's the URL for your client? Your URL is going to be relative -- so if your page's URL is <server>/foo/bar.html, your ajax request is going to go to <server>/foo/GetBulletAjax. But your servlet definition is <server>/GetBulletAjax.
Change your url in your ajax request to /GetBulletAjax. You need the leading forward slash to tell the browser the resource is located off the root of the site.
in Jquery documentation
http://api.jquery.com/jQuery.ajax/
type (default: 'GET')
Type: String
The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.
seems that you miss the type attribute which needs to be POST. default is GET as mentioned by documentation. You dont have a doGet in your servlet to support that.
$.ajax({
url: "GetBulletAjax",
dataType: 'json',
type:POST,
success: function(data) {
alert("success");
},
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR+" - "+textStatus+" - "+errorThrown);
}
});

Categories