First time post here, I hope its a valid question. I've been building a basic Java servlet which accepts 3 name/value pairs from a form on a page, sets those as 1. request attributes 2. session attributes and 3. cookie attributes. Cookies are then added to the response, and then the view (AccountSettings.jsp) is forwarded. The AccountSettings page is then supposed to use request.getCookies() to dump them into an array, then read the values from the array. All of this is supposed to happen every time I use this form.
My problem is that the cookie values are only correct the first time I use the form, then every time I use the form again, the cookies display the last value that was entered on page load. If I refresh the page, however, the cookies values will display correctly. I tried manually deleting the cookies in the Logout servlet (setMaxAge(0) then re-add to response) but this only produced a constant ArrayOutOfBoundsException at index 1, so I commented that portion out and leave the cookies alone.
I checked cookies associated with localhost in Chrome after the page is displayed, and the values are set correctly, so it seems to me like the JSP is drawn before the cookies are actually set correctly.
Any help on how to fix this would be appreciated. Here's my code.
Servlet:
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
public Login() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
login(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
login(request, response);
}
private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
// get a new or existing session
HttpSession session = request.getSession();
// Instantiate user and populate values
User user = new User();
user.setUser(request.getParameter("user"));
user.setPass(request.getParameter("pass"));
// Get last page
String referringUrl = request.getParameter("referringPage");
session.setAttribute("user", user.getUser());
session.setAttribute("pass", user.getPass());
session.setAttribute("lastPage", referringUrl);
Cookie cookie1 = new Cookie("user", user.getUser());
Cookie cookie2 = new Cookie("pass", user.getPass());
Cookie cookie3 = new Cookie("lastPage", referringUrl);
response.addCookie(cookie1);
response.addCookie(cookie2);
response.addCookie(cookie3);
request.setAttribute("user", user.getUser());
request.setAttribute("pass", user.getPass());
request.setAttribute("lastPage", referringUrl);
try{
if (user.authorize()){
session.setAttribute("name", user.getName());
session.setAttribute("authorized", "1");
}else{
session.setAttribute("authorized", "0");
}
}
catch(Exception e){
e.printStackTrace();
}
RequestDispatcher view = request.getRequestDispatcher("AccountSettings.jsp");
view.forward(request, response);
user.destroy();
}
}
View:
<div id="content">
<div class="padding">
<%
if (!loggedIn){
out.print(
"Oops! I'm not sure how you got here..."
);
}else{
Cookie[] cookies = request.getCookies();
out.print(
"<h2>Account Settings</h2><br><br>" +
"<table>" +
"<tr>" +
"<th>Source</th>" +
"<th>Username</th>" +
"<th>Password</th>" +
"<th>Last Page Visted</th>" +
"</tr>" +
"<tr>" +
"<th>Request</th>" +
"<td>" + request.getAttribute("user") + "</td>" +
"<td>" + request.getAttribute("pass") + "</td>" +
"<td>" + request.getAttribute("lastPage") + "</td>" +
"</tr>" +
"<tr>" +
"<th>Session</th>" +
"<td>" + session.getAttribute("user") + "</td>" +
"<td>" + session.getAttribute("pass") + "</td>" +
"<td>" + session.getAttribute("lastPage") + "</td>" +
"</tr>" +
"<tr>" +
"<th>Cookies</th>" +
"<td>" + cookies[1].getValue() + "</td>" +
"<td>" + cookies[2].getValue() + "</td>" +
"<td>" + cookies[3].getValue() + "</td>" +
"</tr>" +
"</table>"
);
}
%>
</div>
</div>
so it seems to me like the JSP is drawn before the cookies are actually set correctly
That's correct. You're adding new cookies to the response (so they're only available in subsequent requests on the same domain and path), but your JSP is attempting to read cookies from the current request.
You need either to send a redirect instead of a forward by replacing
RequestDispatcher view = request.getRequestDispatcher("AccountSettings.jsp");
view.forward(request, response);
by
response.sendRedirect("AccountSettings.jsp");
or to copy cookie values as request attributes, so that JSP can get them as request attributes (you already know how to do that).
Unrelated to the concrete problem, passing around the password in a cookie is a very bad idea. That's a huge security hole. For your concrete functional requirement, you're better off storing the logged-in user as a session attribute instead.
Related
Using Java servlets only, I'm trying to get something similar tosomething in my doGet(), but I need it to pass the parameter to the doPost(). Here is some of my code.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List < Folder > listFolders = (List < Folder > ) getServletContext().getAttribute("listFolders");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
for (int i = 1; i < listFolders.size(); i++) {
out.println("<a name=" + listFolders.get(i).getName() + " href='#' > " + listFolders.get(i).getName() + " </a>" + "<br/>");
`
Using request.getParameter() how would I know/get whatever the user clicks? This assignment requires it to look like links and needs to be clickable. I've seen some other examples using .jsp but I am only limited to servlets for this assignment.
out.println("<a href='File?id=" + listFolders.get(i).getId() + "'>" + listFolders.get(i).getName()
+ "</a><br/>");
Here, File is my java file name (File.java). To get the parameter in the doPost(), I use
Integer id = Integer.valueOf(request.getParameter("id"));
Edit: You dont need the java file name in the href, so it could be just
This question already has answers here:
How can I upload files to a server using JSP/Servlet and Ajax?
(4 answers)
Closed 6 years ago.
I am trying send an bitmap and some string fields to server, and I have checked thoroughly no parameter is empty. This is my ajax code
var URL = "ProfileUpdater";
var username = $("#cp-setup-username").val();
var email = $("#cp-setup-email").val();
var birthday = $("#cp-setup-birthday").val();
var aboutYou = $("#cp-setup-about-you").val();
var intrests = $("#cp-setup-intrests").val();
var phoneNumber = $("#cp-setup-phone-number").val();
var sessionid = $.cookie('WhitePages_SessionID');
var session_username = $.cookie('WhitePages_Username');
var legal = emptyCheck(username,email,birthday,aboutYou,intrests,phoneNumber);
alert(username +" " + email + " " + birthday +" " + aboutYou + " " +intrests + " " + phoneNumber +" "+ sessionid +" " + session_username);
alert(result);
if(legal){
alert(sessionid + " " + session_username) ;
alert("about call server");
$.ajax({
type:'POST',
url : URL,
processData:'false',
contentType:'false',
data:{Username:username,Email:email,Birthday:birthday,AboutYou:aboutYou,Intrests:intrests,PhoneNumber:phoneNumber,sessionid:sessionid,username:session_username,Image:result,FieldsChanged:fieldsChanged,isMultiPart:isMultiPart},
success:function(data){
alert("success");
alert(data);
}
});
}
and this is my servlet code:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ProfileUpdater extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String user = request.getParameter("Username");
String sessionid = request.getParameter("sessionid");
String username = request.getParameter("username");
//sessionid and username is null
PrintWriter out = response.getWriter();
out.println(sessionid +" " + username + " " + user);
System.out.println("hello " + username + "your session id is " +sessionid + " " + user );
}
}
I have put alerts in my script and they are not empty but on response it's null. I mean I think it's sending null to server. Can someone please tell me where I am going wrong ??? Thankyou.
You can't use getParameter() with a multipart post. It just returns null as you discovered. Depending on which servlet spec you are coding to, you can either use the #MultipartConfig annotation (spec 3.0+), or the Apache Commons FileUpload library. The annotation method is built-in, but requires a bit more work; the FileUpload library is easier to use IMO, but obviously requires including another library. I'm not sure which is more efficient in terms of resources or speed. Interestingly if you're using Tomcat it uses FileUpload to handle things in the background anyway.
This question already has answers here:
Generate an HTML Response in a Java Servlet
(3 answers)
doGet and doPost in Servlets
(5 answers)
Closed 1 year ago.
I'm new to JSP/Servlet based web programming. I am currently following some tutorials of servlet and JSP but I found some of the example given doesn't make too much sense for me, for example, in one of the examples of servlet chapter, a servlet look like this:
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloForm extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Using GET Method to Read Form Data";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>First Name</b>: "
+ request.getParameter("first_name") + "\n" +
" <li><b>Last Name</b>: "
+ request.getParameter("last_name") + "\n" +
"</ul>\n" +
"</body></html>");
}
}
To me, the way of displaying the html content is ugly. So I am wondering whether there is a way to make servlet return an object (or a primitive data type) as response, and the front-end part (jsp) use this object to render html content on the browser. I did some research and found out using
request.setAttribute();
is one of implementation of sending an object as response back to client. So I wrote the following servlet, I just paste a snippet of it:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Driver manager and DB url:
final String jdbcDriver = "com.mysql.jdbc.Driver";
final String DBUrl = "jdbc:mysql://localhost/zoo";
// DB credentials:
final String userName = "username";
final String password = "password";
//DB Query:
final String sql = "SELECT name FROM pet WHERE age=10;";
//Response ArrayList:
ArrayList<String> nameList = new ArrayList<String>();
try {
// Register a DB Driver:
System.out.println("Registering Driver.......");
Class.forName(jdbcDriver).newInstance();
// Open a connection:
System.out.println("Openning conncetion.......");
Connection conn = DriverManager.getConnection(DBUrl, userName, password);
// Execute a query:
System.out.println("Executing query.......");
Statement stmt = conn.createStatement();
// Store the result in ResultSet:
System.out.println("Loading the result......");
ResultSet rs = stmt.executeQuery(sql);
// Extract data from ResultSet:
System.out.println("Extracting data.......");
while (rs.next()) {
nameList.add(rs.getString("name"));
}
} ...some catch statement
request.setAttribute("nameList", nameList);
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
So basically this is JDBC is to extract all the pets' names whose age is 10, then store names in a ArrayList of String. I used setAttribute to store this ArrayList and make the index.jsp to handle this response. The index.jsp looks like this:
<%# page import="java.io.*,java.util.*"%>
<html>
<body>
<jsp:include page = "/GetPet" flush = "true" />
<%
ArrayList<String> nameList = request.getAttribute("nameList");
for (String name : nameList) {
out.write("<p>" + name + "</p");
}
%>
</body>
</html>
However, I got an error:
An error occurred at line: 6 in the jsp file: /index.jsp
Type mismatch: cannot convert from Object to ArrayList
So I'm wondering does anyone know:
What's going wrong on this specific error.
What is the best way to make JSP and servlet interact with each other? How the response from servlet be like? How JSP should handle this response?I don't want to write all the html markup in the servlet apparently.
Any hint/article/code example/blog will be greatly appreciated.
I'm facing quite funny problem, the problem is--
In my application there is a functionality to add products into the shopping-cart, I've implemented this functionality using AJAX. When I add different items (e.g. Item-1, Item-2,..., Item-n) it works fine, but when I add same item again (e.g. Item-1, Item-1 OR Item-1, Item-2,..., Item-n, Item-1) it gets failed
following is my AJAX Code--
var xmlHttp;
//FUNCTION TO CREATE BROWSER COMPATIBLE OBJECT.
function createBrowserObject()
{
if (typeof XMLHttpRequest != "undefined") //Object for Netscape 5+, Firefox, Opera, Safari,and Internet Explorer 7
{
//alert("Obj created");
xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) //Version for Internet Explorer 5 and 6.
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlHttp == null) //Fails on older and nonstandard browsers
{
alert("Browser does not support XMLHTTP Request");
}
}
function addToCartChange()
{
if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") //Check whether Server response came back with no errors.
{
document.getElementById("cart_div").innerHTML = xmlHttp.responseText;
}
}
function addToCart(titleId)
{
var lastIndex=cartID.substring(parseInt(cartID.lastIndexOf("_"))+1);
var titleId="product_title_"+lastIndex;
var priceId="product_price_"+lastIndex;
var productTitle=document.getElementById(titleId).innerHTML;
var productPrice=document.getElementById(priceId).innerHTML;
productPrice=productPrice.substring(parseInt(productPrice.lastIndexOf(";"))+1);
createBrowserObject();//CREATE BROWSER COMPATIBLE OBJECT.//
var url = "../AddToCartServlet"; // URL of server-side resource.//CALL TO THE SERVLET//
url += "?productTitle=" + productTitle + "&productPrice=" + productPrice;
xmlHttp.onreadystatechange =addToCartChange; //ASSIGN RESPONSE HANDLER FUNCTION NAME TO ONREADYSTATECHANGE//.
xmlHttp.open("GET", url, true); //INITIATE GET or POST REQUEST. (Here GET)
xmlHttp.send(null); // SEND DATA. (Always null in case of GET.)
}
My AddToCartServlet code is--
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// TODO Auto-generated method stub
System.out.println("inside AddToCartServlet ");
String strProductTitle=request.getParameter("productTitle");// TO STORE THE VALUE IN productTitle VARIABLE.//
String strProductPrice=request.getParameter("productPrice");// TO STORE THE VALUE IN productPrice VARIABLE.//
AuthenticateServlet.strListItemName.add(strProductTitle);
AuthenticateServlet.strListItemPrice.add(strProductPrice);
String strBuffur="<table width='100%' border='0' cellspacing='0' cellpadding='0' class='cart_table'>";
float floatTotal=0;
for(int i=0; i < AuthenticateServlet.strListItemName.size(); i++)
{
System.out.println("inside loop strListItemName("+i+")= "+AuthenticateServlet.strListItemName.get(i));
strBuffur=strBuffur + "<tr id='item_"+i+"'>" + "<td width='58%' align='left' valign='middle'><strong><span class='prod_name'>"+AuthenticateServlet.strListItemName.get(i)+"</span></strong></td>"
+ "<td width='19%' align='center' valign='middle'>"
+ "<form id='form1' name='form1' method='post' action=''><label>"
+ "<input type='text' value='1' name='textfield' id='itemQty_"+i+"' class='cart_input' />"
+ "</label></form></td>"
+ "<td width='23%' align='left' valign='middle'><strong>Rs. "+AuthenticateServlet.strListItemPrice.get(i)+"</strong></td></tr>";
floatTotal=floatTotal+Float.parseFloat(AuthenticateServlet.strListItemPrice.get(i));
}
// System.out.println("Exit for.....");
strBuffur=strBuffur + "<tr class='total_td'>"
+ "<td colspan='2' align='right' valign='middle'><strong>Total:</strong></td>"
+ "<td align='left' valign='middle'><strong>Rs. "+floatTotal+"</strong></td></tr>"
+ "<tr> <td colspan='3' align='center' valign='middle'> <input name='' type='button' value='Check Out' class='add_cart' onclick='gotoCheckOut()'/></td></tr>"
+ "</table>";
response.getWriter().println(strBuffur);
}
In short, call to AddToCartServlet gets failed when I add Same item again. Please help.. Thanks..!
If the Collection You are using for adding item name ie AuthenticateServlet.strListItemName is a Set then this can be a reason for failure
I am using RestfbApi to fetch my friends' names and display on a web page. I also want a corresponding checkbox to each friend, since from the use of table tag , I have friend's name as well as corresponding checkbox.
As I generated checkboxes dynamically , how to make sure which checkboxes are checked when my app runs. The scenario is if I checked five friends and press post to wall button, a wall should be post to all five friends. I know how to post a wall just want to know how to map user selected friends(checked ones) to java code.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException
{
User user = facebookClient.fetchObject("me", User.class);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n";
out.println(docType +
"<HTML>\n" +
"<HEAD><TITLE>Hello</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1></H1>\n" +
"</BODY></HTML>");
JsonObject accounts = facebookClient.fetchObject("me/friends",JsonObject.class);
JsonArray data = accounts.getJsonArray("data");
for(int i = 0; i < data.length(); i++)
{
String id = data.getJsonObject(i).getString("id");
Double int1 = Double.parseDouble(id);
String strName = data.getJsonObject(i).getString("name");
out.println("<table>");
out.println("<tr><td> <input type='checkbox' name='wahtevername' value='"+int1 +"'>"+strName+" </td></tr>");
out.println("</table>" );
}
}
out.println(docType +"<form method=\"GET\">"+"<input type=\"submit\" value=\"Post to wall\" name=\"option\">"+"</form>");
Use request.gatParameterValues("whatevername") to get an array of the values of selected checkboxes.
(Btw, it would be better to place the html code in JSP. Set the list as request attribute and then use JSTL's <c:forEach> to iterate)