I have some JSP code I'm trying to modify.
I have a user object that holds and generates a CSRF values. Currently, this value is set at the start of the application and remains constant throughout the application. I have to change this such that it resets each time a new page is accessed.
The code currently is
<script type='text/javascript'>
var csrfTokenName = 'csrfValue';
var csrfTokenValue = '${user.csrfValue}'; //user is the object, which also contains a setCsrfValue() method that generates the CSRF value
var csrfParam = {csrfValue : csrfTokenValue};
function csrfUrl(url) {
if (url.indexOf('?') == -1) {
//setCSRF code here
return url+'?'+csrfTokenName+'='+csrfTokenValue;
} else {
//setCSRF code here
return url+'&'+csrfTokenName+'='+csrfTokenValue;
}
}
</script>
I tried adding this
<%
User user = (User) session.getAttribute('user'); //fixed typo
%>
In the script but the page won't load (on that note, is there a tool/setting for debugging JSP, using STS with Tomcat and Firefox)
How do I reference this object correctly so that I can call setCsrfValue();
I tried the following but the page didn't load
<%
User user = (User) session.getAttribute('user'); //fixed typo
user.setCsrfValue();
%>
Related
On the html page of a custom built shopping cart, I need to be able to send a post back to our server to tell it whether or not cookies are enabled.
I have the appropriate javascript on the page to detect cookies enabled/disabled (via navigator.cookieEnabled), which does nothing if it detects cookies enabled, and posts a message if they’re not enabled. I need to go beyond just posting a message.
I don’t want the user to be able to click the purchase button, the html for which (along with the cart itself, and all the items the cart contains) is generated by our database software on our server (using associated cookie ID to generate the cart on the website).
I can not figure out how to get the boolean value (enabled/true or disabled/false) out of the javascript and post that info (true or false) back to our server, where I can detect an incoming connection from the website.
Very much a novice where it comes to JS, so go easy on me!
Thanks in advance for any input you can give me, or point me in a direction…
Here is followup based on answers received:
On the cart page (which is displayed when user hits a “Buy This” button elsewhere on the site, to purchase something) is this JS:
<div id="demo"></div>
<script>
var xyz = "";
xyz = "Cookies Enabled: " + navigator.cookieEnabled;
document.getElementById("demo").innerHTML = xyz;
if (navigator.cookieEnabled) {
xyz = "";
} else {
xyz = "Cookies seem to be disabled in your browser.";
}
document.getElementById("demo").innerHTML = xyz;
</script>
So, there is a true/false value generated within the JS. Then, to build the cart, as the html page loads, I send a call to our web server, via this (which is part of the html code on the same page as the above JS):
"4DHTML vCart"
(this is enclosed within comment tags, although it is not a comment. I couldn't put it within comment tags in this edit, because it got ignored). It is picked up by a method called “On Web Connection” in our web server software, which is written in 4th Dimension (it’s basically 4D code embedded in the html, and the comment tags are part of the protocol).
The 4D code then builds the cart and sends it (the cart page) back to the website as an html file.
So… when the call is picked up by the OWC method, I can detect incoming vars from the html cart page, which come in in arrays, and can parse those values. The problem is, the boolean values I want are in the JS and I don’t know how to represent them outside of the JS.
Thank you for your time and consideration on this.
It sounds like you are trying to do an AJAX post back to the server. Try something like this:
<script>
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if(request.readyState === XMLHttpRequest.DONE) {
if(request.status === 200) {
//PERFORM ANY ADDITIONAL ACTIONS AFTER A SUCCESSFUL POST HERE...
} else {
alert('An error occurred. Please try again.');
}
}
}
var xyz = "";
xyz = "Cookies Enabled: " + navigator.cookieEnabled;
document.getElementById("demo").innerHTML = xyz;
if (navigator.cookieEnabled) {
xyz = "";
request.open('POST', 'http://yourpostbackurl.com/enabled');
request.send();
} else {
request.open('POST', 'http://yourpostbackurl.com/disabled');
request.send();
xyz = "Cookies seem to be disabled in your browser.";
}
document.getElementById("demo").innerHTML = xyz;
</script>
I am beginner in Javascript. I am currentlyworking on a Phonegap app with it. I am stuck in between as I have 4 html pages for signup process, and I have to pass all the html pages input value to single js file as in final all data must be POSTed to server URL and also I have read on many sites that they have recommended using same js file for all the pages of your site to speed up the site. So I have two problems to solve. I searched on many sites but could not find the accurate answer.
I need to pass 4 html page's input value to single js file.
I have to make single js file for both sign-in and sign-up.
My codes for JS page is:
var firstName="";
var lastName="";
var email="";
var password="";
var retypePassword="";
var gender="";
var DOB="";
var institute="";
var course="";
var branch="";
var semester="";
var teachers = [];
function signUpStarting() {
alert(firstName + " "+lastName+" "+email+" "+password+" "+retypePassword+" "+gender+" "+DOB+" "+institute+" "+course+" "+branch+" "+semester+" "+teachers.join(","));
}
function signUp1() {
firstName[0] = $("#first_name").val().trim();
firstName[1] = $("#last_name").val().trim();
email = $("#email").val().trim();
password = $("#password").val();
retypePassword = $("#retype_password").val();
alert(firstName + " "+lastName+" "+email+" "+password+" "+retypePassword);
}
function signUp2() {
gender = $('#gender').find(":selected").text();
DOB = $('#DOB').val();
alert(gender+" "+DOB);
}
function signUp3() {
institute = $('#institute').find(":selected").text();
course = $('#course').find(":selected").text();
branch = $('#branch').find(":selected").text();
semester = $('#semester').find(":selected").text();
alert(institute+" "+course+" "+branch+" "+semester);
}
function signUp4() {
$(":checkbox" ).map(function() {
if($(this).is(':checked')){
teachers.push($('label[for="' + this.id + '"]').text());
}
});
signUpStarting();
}
In html pages I am calling JS functions for each pages:
On first page:
<a onclick="signUp1()" href="register-two.html">continue</a>
On second page:
<a onclick="signUp2()" href="register-three.html">continue</a>
On third page:
<a onclick="signUp3()" href="register-four.html">continue</a>
On fourth page:
<a onclick="signUp4()">continue</a>
On each transaction from one page to next I have set alert in JS, and I am getting alert with accurate values also. But after clicking the continue button from fourth page of html, I transferred the code to main signup function. I tried to see alert in signUpStarting() function but there I am getting response of just fourth page values and other values are showing nothing as the variables are null.
I am not getting how to save variable values for always without using localStorage or cookies and POSTing all data to server.And I think this would have been easier if I would know to code for all html pages for my site to single JS file.
Please help me !
I am not getting how to save variable values for always without using localStorage or cookies and POSTing all data to server.And I think this would have been easier if I would know to code for all html pages for my site to single JS file.
This is exactly right. You cannot store data in memory between page loads in a web browser environment because all javascript variables are naturally destroyed when the browser navigates away from the page to a new page (even if they use the same javascript on both pages). Thus, you have to save it somewhere with more permanence: localStorage, cookies, or on the server via POST or GET.
What I would recommend is scrapping the four different html pages and simply using one html page that changes dynamically as the user fills in data. This way the browser will not eliminate data before you are ready to POST it to the server.
I want to set a session variable in JavaScript and call page reload. And at this point I want the aspx.cs file to recognize the change in session variable and make appropriate changes to the webpage. I've tried using :
Assigning the ASP.NET Session Variable using Javascript:
function SetUserName()
{
var userName = "Shekhar Shete";
'<%Session["UserName"] = "' + userName + '"; %>';
alert('<%=Session["UserName"] %>');
}
</script>
Accessing ASP.NET Session variable using Javascript:
<script type="text/javascript">
function GetUserName()
{
var username = '<%= Session["UserName"] %>';
alert(username );
}
</script>
Although the session variable is set. And if I reload the page the JS field recognizes the new data for the session variable. It's not being recognized in the aspx.cs file.
Basically I'm trying to send data to my aspx.cs file based on user actions on the webpage.
Any help is greatly appreciated.
In the example you provide the ASP code (the code enclosed in <% %>) is processed before the page goes to the browser, the Javascript is processed a the browser.
If you want to pass back a value to the server there are a number of options, but one easy way would be to use a hidden input (example) inside a form, and submit back to server, and then when you get the post back on the server you add it to the session.
void Page_Load() {
//Don't blindly trust input from the client, validate first!
Session["Username"] = Request.Params["Username"];
}
So, I'm making a super basic (and also not secure, because I'm just playing around right now) login system that displays different values for premade graphs based on who you are. I'm accessing the data for the graphs from a JSON with an array of objects that contain things like username, password, number of students, number of students that are boys, girls, etc. I want to have an ID variable that is set in my login page when the person logs in with credentials that match one of the objects' username and password in my JSON file. (the ID would be the index of whatever object the credentials matched). When I make the graphs in my HTML file using chart js, I'm opening the JSON file and accessing one of its objects by that ID and accessing its contents that way. I'm struggling to find a way to reference this ID that is in my JavaScript file in my HTML code "scriptlet", if that's what it is called. Also, I DID try to include the JavaScript file in my html file, but I keep getting errors when I try to reference it in the html how I have in my snippet. Here's a sample of my code:
var objectID; //this is the ID I'm talking about in my question
function clickedLoginButton(){
var script = document.createElement('script');
script.src = 'jquery-2.1.4.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
var user = document.getElementById('username'); //inputted username
var pass = document.getElementById('password'); //inputted password
var passed = false;
$.getJSON('data.json', function(data){
console.log("Length: " + data.length)
i = 0;
do{
console.log(data[i].login);
if(user.value == data[i].login && pass.value == data[i].pass){
objectID = i;
window.open("http://localhost/loggedIn.html", "_self", true);
console.log("pass");
return;
}
i++;
}
while(i != data.length);
if(passed == false){
window.open("http://localhost/loginFailed.html", "_self", true);
objectID = 999999999;
console.log("failed");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script> //This is where I want to use the object ID
var numPlayed;
var numLazy;
$.getJSON('data.json', function(data){
var chartData = [
{
value: data[objectID].numStudents-data[objectID].numStudentsPlayed,
color: "dimgray",
highlight: "gray",
label: "lazy"
},
{
value: data[objectID].numStudentsPlayed,
color: "skyblue",
highlight: "powderblue",
label: "played"
}
];
var ctx = document.getElementById("pieCanvas").getContext("2d");
var piechart = new Chart(ctx).Pie(chartData);
});
</script>
I figured it out! You have to use cookies to access the ID for the user, and here's a tutorial for that:
http://www.w3schools.com/js/js_cookies.asp
The problem is that once you set the objectID variable, you navigate away from the page. Once you navigated away from the page, you can no longer access JS variables defined in the previous page.
To go around this problem, you can store the value of the objectID so that the next page can access it again. You can do this using several methods.
Using query parameters of the next page.
When redirecting to the logged in page, you can specify the objectID.
window.open("http://localhost/loggedIn.html?objectId="+objectID, "_self", true);
Then, in the script in the loggedIn page, you can access the objectID using window.location.search
console.log(window.location.search); // outputs ?objectId=2343
Using localStorage
You can use localStorage to store the value of objectID. localStorage.setItem('objectID', objectID) then extract it in the logged in page using localStorage.getItem('objectID').
Using Cookies
As you mentioned above, you can use cookies to store and extract the value of objectID. The disadvantage of this is that it is sent in all subsequent requests to the server.
I have a JSP page in which third party sign-in plugin is used, which is JS. After sign-in is successful, the user-id obtained in JS has to be used in JSP to maintain session by storing that value.
For this, I tried 'manipulating' jQuery but that works only if the JS value is a literal or is pre-known. But here in this case, value is fetched at runtime as per sign in.
Also tried <% String s = "<script>document.writeln(var)</script>"; %>
But again the above problem. works only when value is known before hand.
document.getElementById("ppurl").innerHTML = ppurl; prints the value. But I want to store it.
So, how to achieve the purpose of passing a variable's value in JS to JSP?
Assuming your third party sign-in plugin is client-side JavaScript:
Remember that the JavaScript runs when the page reaches the client. The JSP code has long since completed and so is no longer in the picture.
You have three options that I can immediately see:
Send the data to the server using Ajax or similar.
Refresh the page (sending the login data to the server as part of the refresh).
Update whatever it is on the page that you want to have this value in it via the DOM.
#1 and #2 should be fairly self-explanatory.
For #3: Say you have various forms on the page and you want to make sure that the login token or whatever it is you get from the client-side plugin gets sent with the form using a hidden field in the form with the name tokenField. You could do this:
function putTokenOnForms(token) {
var forms, index, form;
forms = document.getElementsByTagName("form");
for (index = 0; index < forms.length; ++index) {
form = forms[index];
if (form.tokenField) {
form.tokenField.value = token;
}
}
}
You can do much the same with links in a elements (adding to the href property of each link that goes back to your server), etc.
The page outputting the JavaScript to the client cannot read data back from that JavaScript.
You need to initiate a new HTTP request (e.g. using XMLHttpRequest or setting location.href) that passes the data back to the server and then read it in (e.g. from the query string or POST data).
Store it in a cookie using JS. Read it back in JSP.
In your JS, after you get the userID, you can do:
document.cookie = 'myuserid='+userID;
In your JSP, you can read it back like:
Cookie[] cookies = request.getCookies();
String userID;
for(int i = 0; i < cookies.length; i++) {
Cookie c = cookies[i];
if (c.getName().equals("myuserid")) {
userID = c.getValue(); // c.getValue() will return the userID
break;
}
}