how to recieve all the parameters from XMLHttpRequest request on server side? - java

I am using XMLHttpRequest to create a simple form submit and pass 2 parameters. On the server side I am receiving both the parameters but how to get them in different variables?
Here is the Servlet
PrintWriter out = response.getWriter();
response.setContentType("text/plain");
paramMap=request.getParameterMap();
if (paramMap == null)
throw new ServletException(
"getParameterMap returned null in: " + getClass().getName());
iterator=paramMap.entrySet().iterator();
System.out.println(paramMap.size());
String str="";
while(iterator.hasNext())
{
Map.Entry me=(Map.Entry)iterator.next();
String[] arr=(String[])me.getValue();
configId=arr[0];
System.out.println(me.getKey()+" > "+configId);
}
/***Above println** i get "name > Abhishek,filename=a.txt*/
rand=new Random();
randomInt=rand.nextInt(1000000);
configId=randomInt+configId;
System.out.println(configId);
out.println(configId);
/*creates a new session if a session does not exist already*/
session=request.getSession();
session.setAttribute("cid", configId);
out.close();
/*I also need to check a session name `uid` i.e., already created before calling this servlet and then only get both the parameters in parameterMap and store all the params in session. so i'd like to do something like this */
session=request.getSession(false);
if(session!=null) //then get all the parameters here and store them into session
{
uid=session.getAttribute("uid").toString();
/*get nameFromTheParameterMap and fileNameFromTheParameterMap from paramt
session.setAttribute("name", nameFromTheParameterMap);
session.setAttribute("filename", fileNameFromTheParameterMap);
}
Is this the correct approach? Also how will I get parameters from dataString to parameterMap
here is the saveConfig function
function saveConfig()
{
var url_action="/temp/SaveConfig";
var client;
var dataString;
if (window.XMLHttpRequest){ // IE7+, Firefox, Chrome, Opera, Safari
client=new XMLHttpRequest();
} else { // IE6, IE5
client=new ActiveXObject("Microsoft.XMLHTTP");
}
client.onreadystatechange=function(){
if(client.readyState==4&&client.status==200)
{
alert(client.responseText);
}
};
dataString="name="+document.getElementById("name").value+",filename="+document.getElementById("tfile").value;
client.open("POST",url_action,true);
client.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
client.send(dataString);
}

You are wrongly encoding the form-data, you have to seperate the fields by & and not by ,.
See Wikipedia for a summary:
This is a format for encoding key-value pairs with possibly
duplicate keys. Each key-value pair is
separated by an '&' character, and
each key is separated from its value
by an '=' character.
BTW, your Java-Code looks verbose, you could simplify by using for-each-loops.

Related

Cannot get angular $http to work

I'm trying to get a simple angularjs login screen to work.
The angular app sends the login details via http get method to a java servlet and anticipates a json response with success/fail. The java servlet is running on Tomcat 8.0.
Unfortunately, the angular app doesn't seem to be able to receive data from the servlet (it does send the data to the servlet) - the errorCallback method of "then" is called everytime.
Also, accessing the servlet's url directly from the browser works fine (the browser shows the response string).
Can you help me to find the problem?
This is the div element in the html page:
<div ng-controller = "loginCtrl">
<input type="text" ng-model = "userName" placeholder="Username"></input><br>
<input type = "text" ng-model = "userPass" placeholder="Password"></input><br>
<button type = "button" ng-click = "login()">Login</button><br>
{{message}}
</div>
This is the js code:
var expenseApp = angular.module("expenseApp",[]);
expenseApp.controller('loginCtrl',['$scope','$http',function($scope,$http) {
$scope.userName = "";
$scope.userPass = "";
$scope.message = "type in your credentials";
$scope.login = function() {
var address = "http://localhost:8080/ExpenseSystemServer/LoginServlet?userName=" + $scope.userName + "&userPass=" + $scope.userPass;
$http({method:'get',
url:address})
.then(function(data, status, headers, config) {
$scope.message = "http success";
},
function(data, status, headers, config) {
$scope.message = "http error";
});
};
}]);
And this is the servlet doGet method in java (the servlet's class name is LoginServlet):
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
String userName = request.getParameter("userName");
String userPass = request.getParameter("userPass");
System.out.print("Login attempt with " + userName + "; " + userPass + ": ");
if (userName == null || userPass == null || !userName.equals("admin") || !userPass.equals("pass")){
response.getWriter().write("{'success':false,'message':'wrong details'}");
System.out.println("failed.");
}
else {
response.getWriter().write("{'success':true, 'user':{'name':'admin'},'message':'Hi admin!'}");
System.out.println("succeeded.");
}
}
Can you help me here?
Thanks.
You're sending invalid JSON from the servlet. JSON keys and string values must be in double quotes, not single quotes. Use JSONLint to validate your JSON. Or better, create a Java object, and a marshaller like Jackson to transform the object to valid JSON.
Also, instead of sending back a successful response (with code 200), with an object property "success" set to false, you should return an error response (400 if the required credentials are not there at all, 401 if they're not valid). Doing that not only shows respect for the HTTP protocol, but allows using http promises as intended:
http(...).then(successCallback, errorCallback)
instead of
http(...).then(successButActuallyMaybeErrorCallback, anotherErrorCallback)
Your JSON is invalid using single quotes that should be double
It's a really bad practice to create your own when most languages can encode it for you from native arrays and objects. I don't know best way using java but it needs to look like:
response.getWriter().write('{"success":false,"message":"wrong details"}');
note switch of single and double quotes

How to get session token form url?

Lets say..
if i hit google with https://www.google.com it will create a session, for the responce it
will create url with session tokn like..
https://www.google.co.in/?gfe_rd=cr&ei=oFBjVJSvLqnM8gft5YDwAQ&gws_rd=ssl.
My question is
am connecting to google with the code:
URL url = new URL(test);
URLConnection conn = url.openConnection();
this will connect to google.
for this google creates a session.
then how would i get a session token back to my code?
You can get the session token from the cookie of the browser. You can, find the cookie settings->advanced settings->privacy->content settings->allcookie and site data then search www.google.com and select sid and copy the content .
You can extract any cookie, not only the one containing the session with the following approach:
Since a server may set multiple cookies in a single request, we will need to loop through the response headers, looking for all headers named "Set-Cookie".
String headerName=null;
for (int i=1; (headerName = uc.getHeaderFieldKey(i))!=null; i++) {
if (headerName.equals("Set-Cookie")) {
String cookie = urlConn.getHeaderField(i);
The string returned by the getHeaderField(int index) method is a series of name=value separated by semi-colons (;). The first name/value pairing is actual data string we are interested in (i.e. "sessionId=0949eeee22222rtg"), the subsequent name/value pairings are meta-information that we would use to manage the storage of the cookie (when it expires, etc.).
cookie = cookie.substring(0, cookie.indexOf(";"));
String cookieName = cookie.substring(0, cookie.indexOf("="));
String cookieValue = cookie.substring(cookie.indexOf("=") + 1, cookie.length());
This is basically it. We now have the cookie name (cookieName) and the cookie value (cookieValue).
the above explanation was based on example provided in http://www.hccp.org/java-net-cookie-how-to.html#retrieving_cookies
A more sophisticated approach is to use CookieAccessor class:
public void getCookieUsingCookieHandler() {
try {
// Instantiate CookieManager;
// make sure to set CookiePolicy
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
// get content from URLConnection;
// cookies are set by web site
URL url = new URL("http://host.example.com");
URLConnection connection = url.openConnection();
connection.getContent();
// get cookies from underlying
// CookieStore
CookieStore cookieJar = manager.getCookieStore();
List <HttpCookie> cookies =
cookieJar.getCookies();
for (HttpCookie cookie: cookies) {
System.out.println("CookieHandler retrieved cookie: " + cookie);
}
} catch(Exception e) {
System.out.println("Unable to get cookie using CookieHandler");
e.printStackTrace();
}
}
In any approach you follow you need to know what is the name of the cookie holding the session id, so that you can get the value from it. E.g a java web application usually creates a cookie with name "JSESSIOINID"

Java : How to handle POST request without form?

I'm sending a http post request from javascript, with some json data.
Javascript
var data = {text : "I neeed to store this string in database"}
var xhr= new XMLHttpRequest();
xhr.open("POST","http://localhost:9000/postJson" , true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.send(data);
xhr.setRequestHeader("Connection", "close");
//Also, I've tried a jquery POST
//$.post('postJson', {'data=' : JSON.stringify(data)});
//But this doesn't make a request at all. What am I messing up here?
Route
POST /postJson controllers.Application.postJson()
Controller
public static Result postJson(){
//What should I write here to get the data
//I've tried the below but values is showing null
RequestBody rb=request().body();
final Map<String,String[]> values=rb.asFormUrlEncoded();
}
What is the way to parse the POST request body?
Much thanks!
Retreive the request body directly as JSON... no need to complicate your life.
public static Result postJson() {
JsonNode rb = request().body().asJson();
//manipulate the result
String textForDBInsertion = rb.get("text").asText(); //retreives the value for the text key as String
Logger.debug("text for insertion: " + textForDBInsertion
+ "JSON from request: " + rb);
return ok(rb);
}
Also, I recommend you use the AdvancedRestClient Chrome plugin for testing. This way you can eliminate from the equation client-side code errors.
Cheers!

Setting cookie in JSP and retrieving from non servlet class

I have a situation where i need to set cookie in JSP and i need to get those cookie in normal java class.
The JSP:
CookieManager manager = new CookieManager();
CookieHandler.setDefault(manager);
CookieStore cookieJar = manager.getCookieStore();
// create cookie
HttpCookie cookie = new HttpCookie("UserName", "John Doe");
// add cookie to CookieStore for a
// particular URL
URL url = new URL("http://localhost:8080");
url.openConnection().connect();
cookieJar.add(url.toURI(), cookie);
System.out.println("Added cookie using cookie handler");
%>
Below is the Java class [not a servlet class] and this class is running in the server and this is invoked not after the JSP call but somewhere in the application only if any event occurs. below is the code where i wrote to capture cookies.
URL url = new URL("http://localhost:8080");
URLConnection conn = url.openConnection();
conn.getContent();
CookieManager cm = new CookieManager();
CookieHandler.setDefault(cm);
cm.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieStore cs = cm.getCookieStore();
List <HttpCookie> cookies = cs.getCookies();
for (HttpCookie cookie: cookies) {
System.out.println("CookieHandler retrieved cookie: " + cookie);
}
would this scenario works if i want to retrieve the cookies in non servlet class?
The output of the above code will return empty list.
However if i write a servet class with request.getCookie("UserName") I will see the cookie value.
Here i need to understand how would i get the cookie value without using request object.
Because request object is not always passed in multiple invocation of java class. And i am not using session.
please let me know if you have any better approach.
Thanks-
Instead Use the getHeaderFields() method from the connection Object to get the full list of Name-Value pairs representing the header fields of the specific connection
Cookie information(if present)should be under the “Set-Cookie” header field.
Map<String, List<String>> headerFields = conn.getHeaderFields();
Set<String> headerFieldsSet = headerFields.keySet();
Iterator<String> hearerFieldsIter = headerFieldsSet.iterator();
Then iterate over the Set and check if the cookie is present. If it is present print it out.
while (hearerFieldsIter.hasNext()) {
String headerFieldKey = hearerFieldsIter.next();
if ("Set-Cookie".equalsIgnoreCase(headerFieldKey)) {
List<String> headerFieldValue = headerFields.get(headerFieldKey);
for (String headerValue : headerFieldValue) {
System.out.println("Cookie Found...");
String[] fields = headerValue.split(";\s*");
String cookieValue = fields[0];
System.out.println("cookieValue:" + cookieValue);
}
}
}
Y0u can refer this examle

storing cookies in client js and reading in java

I have stored a js array(key value pair) in cookie using JSON.stringify...
Ex:
var a={"aaa":"111","bbb":222};
document.cookie="mycookie="+JSON.stringify(a);
When I'm reading the cookie from js it returns the value for mycookie as a string {"aaa":"111","bbb":222} so I can parse it again using JSON.parse() and it works fine for me.
My need is to get the same cookie from java.. so I used HttpServletRequest's request.getCookie() method. It returns an array of cookies.. while iterating in to that, it does not have the cookie as "mycookie" instead of that it contains the following cookie list
cookie[0]= aaa:
cookie[1]= bbb:
why it does not return a value as
cookie[0]= mycookie:{"aaa":"111","bbb":222}
how does the getcookie method parses a single cookie in this mannar..
JS:
var dateOfVisiting=new Date().getTime().toString();
var mycookie = {‘page’:’example.com’,‘date’:dateOfVisiting};
var expiryDate = new Date();
expiryDate.setTime(expiryDate.getTime()+(30*24*60*60*1000));
var expires = "; expires="+expiryDate.toGMTString();
document.cookie="mycookie="+JSON.stringify(mycookie)+expires+"; path=/;"
Java
Cookie[] cookies = request.getCookies();
String myData = null;
for(Cookie cookie : cookies){
System.out.println(cookie.getName()+“:”+cookie.getValue());
if(“mycookie”.equals(cookie.getName())){
myData = cookie.getValue();
}
}
The result is
page:
date:
And its not getting inside the if condition

Categories