Retrieve map attribute from page to page JSP - java

i am trying to get retrieve attributes which are being put into a map. However i keep getting null when i try to debug it by putting it in an alert. Any help will be appreciated, thank you!
First jsp
<%
//Map newSurvey = new LinkedHashMap();
Map newSurvey = new HashMap();
newSurvey.put("description", request.getParameter("description"));
newSurvey.put("startDate", request.getParameter("start_datetime"));
newSurvey.put("endDate", request.getParameter("end_datetime"));
newSurvey.put("maxParticipant", request.getParameter("max_participant"));
newSurvey.put("minAge", request.getParameter("min_age"));
newSurvey.put("maxAge", request.getParameter("max_age"));
newSurvey.put("preSurveyText", request.getParameter("pre_survey_text"));
request.setAttribute("myMap", newSurvey);
%>
window.location = 'Survey_Questions.jsp';
Second jsp (to retrieve) i used a javascript to see if i am able to retrieve it
function testGet(){
<%
Map myMap = (Map)request.getParameter("myMap");
String description = (String) myMap.get("description");
%>
alert(<%=description%>
}

On first page you are using: request.setAttribute("myMap", newSurvey);.
So you must have to use request.getAttribute("myMap"); on second page.

window.location = 'Survey_Questions.jsp';
Will just redirect to a page and it will not pass your request object to other documents.
Instead you can use below lines of code:
RequestDispatcher rd = request.getRequestDispatcher("Survey_Questions.jsp");
rd.forward(request, response);
RequestDispatcher helps you to forward your request to other pages.
Also, use getAttribute instead of getParameter as you have used setAttribute to set myMap on First.jsp.

Related

send values from javascript page to servlet page at run-time

My_javascript_page
window.onload = loadResTimeData;
function loadResTimData() {
var e = window.performance.getEntriesByType("resource");
if (window.console) {
console.log("Resource Timming");
var perf_data = "";
var name, load, connection, request, fetch;
for (var i in e) {
if (e[i].name == "document") {
continue;
}
name = e[i].name.replace(/^.*\/|\.$/g, '') + ":";
load = e[i].duration;
request = e[i].responseEnd - e[i].requestStart;
fetch = e[i].responseEnd - e[i].fetchStart;
var s1={"Name": name, "CONNECTION":connection, "REQUEST":request, "LOAD":load, "FETCH":fetch};
var String1=JSON.stringify(s1);
console.log("Resource:" + name);
console.log("User Time:" + load);
console.log("Connection:" + connection);
console.log("Request Time:" + request);
console.log("Fetch Time:" + fetch);
$.ajax({
type:"POST",
url:"Final", //Final is my servlet page
data:String1,
datatype: "json"
});
}
}
}
}
This code calculates different response times when a web page is loaded and sends the data back to the servlet page.
This data i am printing on console(Console.log values), I want to send it to my servlet page in json format.
I tried doing it using jquery ajax, but the value didnot get passed to my servlet page.
Now I came accross various links where many people gave example on how to do it. But problem is
that all examples will be trigerred by clicking on the button. For that i need a form or may be some other thing
But in my application I want the data to be passed to my servlet page once the window.onload function is
trigerred; where I dont need a form or textfield. Also please let me know what exactly do i need to call at my server end(request.getparameter(???))
I am sharing the links i referred.
http://www.mysamplecode.com/2012/04/jquery-ajax-request-response-java.html
http://www.javacodegeeks.com/2014/09/jquery-ajax-servlets-integration-building-a-complete-application.html
JSP_page
<script src="http://code.jquery.com/jquery-latest.js"></script>
<title>JSP Page</title>
</head>
<body>
<script language='JavaScript'>
onclick=' window.onload';
Also I had people telling me to use cookies. I created cookies but my servlet page was not able to read it.
Someone suggested I can use hidden fields as well.
You can understand I am a mess right now. Please help as to where am I going wrong or what do i need to do now....

How to prevent client from accessing JSP page

In my web application, I use the .load() function in JQuery, to load some JSP pages inside a DIV.
$("#myDiv").load("chat.jsp");
In chat.jsp, no Java codes is executed unless this client has Logged in, means, I check the session.
String sessionId = session.getAttribute("SessionId");
if(sessionId.equals("100")){
//execute codes
}else{
//redirect to log in page
}
Those java codes that will be executed, they will out.println(); some HTML elements.
I don't want the client to write /chat.jsp in the browser to access this page, as it will look bad, and the other stuff in the main page won't be there, and this could do a harm to the web app security.
How can I restrict someone from accessing chat.jsp directly, but yet keep it accessible via .load() ?
UPDATE:
JavaDB is a class that I made, it connects me to the Database.
This is chat.jsp
<body>
<%
String userId = session.getAttribute("SessionId").toString();
if (userId != null) {
String roomId = request.getParameter("roomId");
String lastMessageId = request.getParameter("lastMessageId");
JavaDB myJavaDB = new JavaDB();
myJavaDB.Connect("Chat", "chat", "chat");
Connection conn = myJavaDB.getMyConnection();
Statement stmt = conn.createStatement();
String lastId = "";
int fi = 0;
ResultSet rset = stmt.executeQuery("select message,message_id,first_name,last_name from users u,messages m where u.user_id=m.user_id and m.message_id>" + lastMessageId + " and room_id=" + roomId + " order by m.message_id asc");
while (rset.next()) {
fi = 1;
lastId = rset.getString(2);
%>
<div class="message">
<div class="messageSender">
<%=rset.getString(3) + " " + rset.getString(4)%>
</div>
<div class="messageContents">
<%=rset.getString(1)%>
</div>
</div>
<% }
%>
<div class="lastId">
<% if (fi == 1) {%>
<%=lastId%>
<% } else {%>
<%=lastMessageId%>
<% }%></div>
<% if (fi == 1) {%>
<div class="messages">
</div>
<% }
} else {
response.sendRedirect("index.jsp");
}%>
</body>
Guys I don't know what Filter means.
UPDATE
If I decided to send a parameter that tells me that this request came from Jquery.
.load("chat.jsp", { jquery : "yes" });
And then check it in chat.jsp
String yesOrNo = request.getParameter("jquery");
Then they can simply hack this by using this URL.
/chat.jsp?jquery=yes
or something like that..
UPDATE
I tried Maksim's advice, I got this when I tried to access chat.jsp.
Is this the desired effect?
In order to achieve this in my application I check for X-Requested-With field in http header the client sends to my page in its request. If its value is XMLHttpRequest, then it's very likely that it came from an ajax request (jQuery appends this header to its requests), otherwise I don't serve the page. Regular (direct) browser requests will leave this header field blank.
In ASP.Net it looks like this, you will have to change your code slightly for JSP:
if (Request.Headers["X-Requested-With"] != "XMLHttpRequest")
{
Response.Write("AJAX Request only.");
Response.End();
return;
}
UPD: After quick googling your code will probably be something like this
if(!request.getHeader("X-Requested-With").equals("XMLHttpRequest")){
out.println("AJAX Request only.");
out.flush();
out.close();
return;
}
UPD2: Looks like request.getHeader("X-Requested-With") returns null in your case change the condition to something like this:
String ajaxRequest = request.getHeader("X-Requested-With");
if(ajaxRequest == null || !ajaxRequest.equals("XMLHttpRequest")){
...
}
Is your code snippet a servlet? If that's so, use a security framework (such as Spring Security) or a javax.servlet.Filter for applying security, then you can apply security to JSPs too.
you should use Filter. Check session in filter code and redirect to login.
according to http://www.c-sharpcorner.com/blogs/2918/how-to-set-a-request-header-in-a-jquery-ajax-call.aspx
JQuery gives you the tools you need to create a request and retrieve a response through it's ajax library. The raw $.ajax call gives you all kinds of callbacks to manipulate http messages.
So you can add a custom request header in your Ajaxa call like this
$.ajax({
type:"POST",
beforeSend: function (request)
{
request.setRequestHeader("Authority", "AJAXREQUEST");
},
...........
And then in your servlet check to see if the request has the header Authority equals to AJAXREQUEST. This is how you read request headers http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Request-Headers.html

Remember me in jsp login page [duplicate]

This question already has answers here:
How do I keep a user logged into my site for months?
(2 answers)
Closed 5 years ago.
I have a login screen and i am authenticating users by checking credentials from database. But how can i implement Remember me check box? Like in gmail remember me(stay signed in) is present. I am using sign.jsp and Auth servlet (doPost) and oracle 10g ee for authentication.
You can use cookies for this purpose.
In your servlet response handler (doPost, doGet etc.) create a cookie in the following way -
if(remember_me_is_checked)
{
Cookie c = new Cookie("userid", userId.toString());
c.setMaxAge(24*60*60);
response.addCookie(c); // response is an instance of type HttpServletReponse
}
To read them, you can use something like this -
Cookie[] cookies = request.getCookies(); // request is an instance of type
//HttpServletRequest
boolean foundCookie = false;
for(int i = 0; i < cookies.length; i++)
{
Cookie c = cookies[i];
if (c.getName().equals("userid"))
{
string userId= c.getValue();
foundCookie = true;
}
}
Here is the official documentation for the Cookie class.
You can use cookies to help with your implementation. Something like this .
String userIdendificationKey="UserName";
Cookie cookie = new Cookie ("userIdendificationKey",userIdendificationKey);
// Set the age of the cokkie
cookie.setMaxAge(365 * 24 * 60 * 60);
//Then add the cookies to the response
response.addCookie(cookie);
and then check against the particular value later .
I don't know whether it is secure or not,but this is what i did.
In login.jsp head tag
<script type="text/javascript">
var isLoggedIn = "${isLoggedIn}";
if(isLoggedIn === true)
window.location.href="Home.jsp";
</script>
in body tag i added a check box for Remember Me as below
<input type="checkbox" id="RememberMe" name="rememberMe">
<label for="RememberMe">Remember Me</label>
In servlet doPost method i added the code below
if(userdetails are verified)
{
if(request.getParameter("rememberMe")!=null){
request.getSession().setAttribute("isLoggedIn", true);
}
RequestDispatcher rs = request.getRequestDispatcher("Home.jsp");
rs.forward(request, response);
}
else
{
RequestDispatcher rs = request.getRequestDispatcher("fail.jsp");
rs.include(request, response);
}
using this it will ask for the credentials at first time login,and it will store the login info in session parameters,if you try to access the site second time it will automatically goes to "Home.jsp" instead of "login.jsp"
please comment whether this method is good practice,any other modifications can be done.
Suggestions are welcome.
Take a look at Spring SecurityIt
It is a powerful and highly customizable authentication and access-control framework.
You can also check the code from Rose India, this will be more helpful to you.

Input values to textfields, stream back to website

I connected to a website, used JSoup to find the "textfield" ID's, input the values, now i need to stream it out.
Can someone please help me with the correct coding to stream the "modified" doc back to the website?
if (source == enter2)
{
String URL = "http://www.clubvip.co.za/Login.aspx";
Element number;
Element pass;
Element keyword;
try {
Document doc = Jsoup.connect(URL).get();
number = doc.getElementById("ctl00_ContentPlaceHolder1_CellNumberRadText").attr("value", "number");
System.out.println(number);
pass = doc.getElementById("ctl00_ContentPlaceHolder1_PasswordRadText").attr("value", "password");
System.out.println(pass);
keyword = doc.getElementById("ctl00_ContentPlaceHolder1_KeyWordRadText").attr("value", "keyword");
System.out.println(keyword);
Why are you doing it like this?
If you need to login to that webpage, simply take arguments and send them via HTTP POST request to page where <form> points to
which is <form method="post" action="login.aspx">
Instead of what you are doing:
Jsoup.connect("http://www.clubvip.co.za/Login.aspx")//
.data("ctl00_ContentPlaceHolder1_CellNumberRadText", "number",
"ctl00_ContentPlaceHolder1_PasswordRadText", "password",
"ctl00_ContentPlaceHolder1_KeyWordRadText", "password").post();
not tested, so possibly not 100% correct...

passing values between two jsp files

<% if(empRecNum != null && !(empRecNum.equals("")))
{
empSelected=true;
}
boolean canModify = UTIL.hasSecurity("PFTMODFY") && empSelected;
%>
<script type="text/javascript">
function add(){
alert('hello');
df('ADD');
}
</script>
On the click of add button, i need to pass the boolean value to another jsp and then go on with the df servlet function.
pass in URL like
second.jsp?param=value
access param from second jsp
request.getParameter("param");
OR:
Store it in cookie
OR:
Persist it in DB
I found this, which may help:
http://www.exampledepot.com/egs/javax.servlet.jsp/caller.jsp.html

Categories