I wrote a session code to track a session in eclipse. Instead of displaying in the web page the session id gets save as a file in my computer and every time the code is run the dialogue box to save file keeps appearing
i don't really know what is the issue. gooogled it but can't find anything related
here is my code:
import java.io.*;
import javax.servlet.http.*;
/**
* Servlet implementation class SessionTrack
*/
public class SessionTrack extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("html/text");
try {
PrintWriter pw = response.getWriter();
HttpSession session = request.getSession();
pw.println("<html><body>");
pw.println(session.getId());
session.setMaxInactiveInterval(2*60);
if(session.isNew()) {
pw.println("Welcome new user");
//System.out.println("asd");
}
else {
pw.println("Welcome back user");
pw.println("</html></body>");
pw.close();
}
}
catch(Exception e) {
System.out.println(e);
}
}
}
I have a java class where i have a method which is returning me a json i want to call that method into my servlet doGet method so that i can make a AJAX call later
but while calling the java class method (Outlet.Outlet) it asks for a parameter to pass i dont know what to pass there
please have a look into my code
this is my java class
public class Outlet {
static Connection con = null;
static Statement statement = null;
ResultSet resultSet = null;
public static String Outlet(String idDB) throws ClassNotFoundException, SQLException {
List<String> list = new ArrayList<String>();
con = DBConnection.createConnection();
statement = con.createStatement();
String sql="select CUSTOMERDESCRIPTOR as OUTLETNAME from ecustomer where CUSTOMERIDENTIFIER in(select CUSTOMERIDENTIFIER from mt_distributrol where mt_distributr_vcdistributrcode = '"+idDB+"')";
System.out.println("iddb :"+idDB);
try {
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
list.add(resultSet.getString("OUTLETNAME"));
}
} catch (SQLException e) {
e.printStackTrace();
}
String json = new Gson().toJson(list);
System.out.println("Json Outlet :"+json);
return json;
}
}
In the above java class i am returning a Json and i want to call that method into my servlet doGost
my doGet is
try {
String json = Outlet.Outlet(); //what should i pass here as a parameter
response.setContentType("application/json");
response.getWriter().write(json);
System.out.println("dheeraj"+json);
}
catch (Exception e) {
e.printStackTrace();
}
}
if i am passing idDB then it throws error.please anybody having any knowledge help me out
Please read OWASP - SQL Injection and learn about PreparedStatements
First, methods should not start with capital letter, so rather you could name it like Outlet.findById rather than Outlet.Outlet (the method should not be the same as the class; it is really confusing to read), and you can get parameters from the request
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
String s = Outlet.findById(id);
When calling the API, you add ?id=value
Or you can get the final part of the path from request, assuming your API is setup like /path/ids/value - Refer What's the difference between getRequestURI and getPathInfo methods in HttpServletRequest? for options with this
Before doing this, of course you should double-check that query you are running actually returns data when querying the database directly.
I am new to Android. Got a few question regarding the pass back data from Servlet to Android.
So here is my code at servlet:
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
JSONArray jsonArray = new JSONArray();
PrintWriter out = response.getWriter();
String action = request.getParameter("action");
if (action.equalsIgnoreCase("GetAllGame")) {
try {
PreparedStatement statement = db
.getStatement("SELECT * FROM game");
ResultSet result = statement.executeQuery();
while (result.next()) {
JSONObject gameInfo = new JSONObject();
gameInfo.put("gameID", result.getString("gameID"));
gameInfo.put("gameVenue", result.getString("venueID"));
gameInfo.put("gameDate", result.getString("date"));
gameInfo.put("gameCapacity",
result.getString("gameCapacity"));
gameInfo.put("gameCredit",
result.getString("gameCredit"));
gameInfo.put("gameBy", result.getString("gameBy"));
gameInfo.put("gameStart", result.getString("gameStart"));
gameInfo.put("gameEnd", result.getString("gameEnd"));
jsonArray.put(gameInfo);
}
}
catch (JSONException je) {
System.out.println(je.getMessage());
} catch (Exception exc) {
System.out.println(exc.getMessage());
}
out.println(jsonArray.toString());
System.out.println(jsonArray.toString());
out.write(jsonArray.toString());
out.flush();
}
When I launch the servlet, it pop out a website with texts like:
TODO write content
Click here to go My Servlet
Sorry as I am still new and unable to post picture. And when I execute the URL on computer such as http://localhost:8080/WebService/MyServlet?action=GetAllGame , at the console of GlassFish server tab, it did actually print out all the data but nothing is showing on the pop out website.
However, when I ping my phone to my computer and trying to grab the data from my phone, the same thing happens, the data is showing at the console but not on the website in phone. I thought it should be shown on with some json formatted data?
So I thought it was okay until when I implement it into my Android apps, and it is stating that the json passing back from servlet is empty. Any ideas?
What I meant is the data is just printing out from my computer but not actually return back to Android.
I have a technical problem and I am not sure about the correct way to solve:
In a web page I am developing, I have to store the current user name from session (the person who is logged in) to "stamp" an action. (For instance, "The user created this file on "). My algorithm retrieves the user name from session but it obviously changes for each user. Therefore, the is always been the one of the user logged in, and not the creator name.
Any hint anyone?
Thanks!
So logically these are the steps you want?
User1 logs in
User1's name gets stored in Http session
User1 creates File42
System stores in database that User1 created File42 on Timestamp257
User1 logs out
User 2 logs in
User2's name gets stored in Http session
User2 views information about File42
System reads from database that User1 created File42 on Timestamp257
System displays information to User2
I think you might be missing the part where the system stores stuff (e.g. in a database).
EDIT: If you don't need persistence you could store shared data in the ServletContext. Note this is not a serious solution but could be used for a quick prototype or demo. Don't even think about doing this in production, it's got issues.
In your servlet do:
private static Map<String, FileData> fileAccess;
private class FileData {
String userName;
Date timeStamp = new Date();;
String fileName;
FileData(String userName, String fileName) {
this.userName = userName;
this.fileName= fileName;
}
}
public void init(ServletConfig config) {
String attributeKey = "fileAccess";
fileAccess = config.getServletContext().getAttribute(attributeKey);
if (fileAccess == null) {
fileAccess = new HashMap<String, FileData>();
config.getServletContext().setAttribute(attributeKey, fileAccess);
}
}
// in this example a POST means a user accesses a file
public void doPost(HttpServletRequest req, HttpServletResponse resp) {
// get the user name from the current session
String userName = req.getSession().getAttribute("userName");
// get the file name from the request (posted from the file access form)
String fileName = req.getParameter("fileName");
// check if we have the necessary data
if (userName == null || fileName == null) {
resp.getWriter().write("Invalid file access request");
resp.getWriter().flush();
return;
}
// create and fill file data wrapper
FileData fileData = new FileData(userName, fileName);
// store the file data in the shared fileAccess map.
// synchronized to block simultaneous acccess from different threads
synchronized (fileAccess) {
// note: any previously stored FileData object gets replaced
fileAccess.put(fileName, fileData);
}
// display the result to the user
display(fileData, resp);
}
// in this example a GET means a user views a file
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
// get the file name parameter from the request (sent as part of the view-file request)
String fileName = req.getParameter("fileName");
// check if we have the necessary data
if (fileName == null) {
resp.getWriter().write("Invalid view file request.");
resp.getWriter().flush();
return;
}
// get the file data from the shared fileAccess map.
// synchronized to block simultaneous acccess from different threads
synchronized (fileAccess) {
FileData fileData = fileAccess.get(fileName);
// display the result to the user
display(fileData, resp);
}
}
private void display(FileData fileData, HttpServletResponse resp) {
resp.getWriter().write("File accessed:");
resp.getWriter().write("User: " + fileData.userName);
resp.getWriter().write("File: " + fileData.fileName);
resp.getWriter().write("Timestamp: " + fileData.timeStamp);
resp.getWriter().flush();
}
I was doing a simple web project (you can see the code below). As far as I know, session attributes are related to one session. When I opened two tabs of the same browser and run type the URL, only one session ID is created, but two different objects of the same session attribute are running (i.e I don't want to run two quizzes at the same time. But, when I changed the question in one of the tab, it doesn't affect the session attributes of the other tab). Can you explain me why it happened like that? How can I change my code to make the session variables shared so that when I changed one of the session attributes in one of the tabs, I wanted the other tab's session variables to be affected to?
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.quizServlet;
import QuizApp.Quiz;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* #author Mati
*/
#WebServlet(name = "QuizServlet", urlPatterns = {"/Quiz"})
public class QuizServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
} catch (Exception ex) {
out.write("<font style='color:red'><b>" + ex.getMessage() + "</b></font>");
} finally {
out.close();
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
if (request.getSession().getAttribute("QuizzObject") == null) {
Quiz quiz = new Quiz();
quiz.addQuestion(new int[]{1, 2, 3, 4});
quiz.addQuestion(new int[]{1, 1, 2, 3, 5, 8});
quiz.addQuestion(new int[]{0, 5, 10, 15, 20, 25});
request.getSession().setAttribute("QuizzObject", quiz);
}
if (request.getSession().getAttribute("questionsLeft") == null) {
request.getSession().setAttribute("questionsLeft", true);
}
Quiz qq = (Quiz) request.getSession().getAttribute("QuizzObject");
qq.reset();
StringBuilder SB = new StringBuilder();
SB.append("<form name='myform' method='post'>");
SB.append("<h3>Have fun with NumberQuiz!</h3>");
SB.append("<p><input type='submit' name='btnNext' value='Start quiz' /></p>");
SB.append("</form>");
out.print(SB.toString());
} catch (Exception ex) {
out.write("<font style='color:red'><b>" + ex.getMessage() + "</b></font>");
} finally {
out.close();
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
try {
StringBuilder SB = new StringBuilder();
String msg="";
SB.append("<html><head></head><body>");
Quiz qq = (Quiz) request.getSession().getAttribute("QuizzObject");
SB.append(request.getSession().getId());
boolean questionsLeft = (Boolean) request.getSession().getAttribute("questionsLeft");
if (questionsLeft) {
qq.addAttempts();
if (request.getParameter("txtAnswer") != null) {
if (qq.isCorrect(Integer.parseInt(request.getParameter("txtAnswer")))) {
qq.scoreAnswer();
} else {
msg="<p><font style='color:red'>Wrong Answer .. Try Again</font></p>";
}
}
if (qq.getCurrentQuestion() == null) {
request.getSession().setAttribute("questionsLeft", false);
SB.append("Congratulations, you have completed the quiz!");
SB.append("<br>Your final score is:" + qq.getScore());
SB.append("<br>Total attempts:" + qq.getAttempt());
qq.reset();
request.getSession().setAttribute("questionsLeft",null);
} else {
SB.append("<form name='myform' method='post'>");
//SB.append("<h3>Have fun with NumberQuiz!</h3>");
SB.append("<p>Your current score is " + qq.getScore() + ".</p>");
SB.append("<p>Guess the next number in the sequence!</p>");
SB.append("<p>" + qq.getCurrentQuestion().toString().replaceAll("\\?", "<font style='color:red'><b>?</b></font>") + "</p>");
SB.append("<p>Your answer:<input type='text' id='txtAnswer' name='txtAnswer' value='' /></p>");
SB.append("<p><input type='submit' name='btnNext' value='Next' onclick='return validate()' />");
SB.append("<input type='Reset' name='btnStart' value='Restart!' onclick=\"document.location.href='/QuizzWeb/Quiz';return false;\" /></p>");
SB.append(msg);
SB.append("</form>");
SB.append("<script type='text/javascript'>function validate(){if(document.getElementById('txtAnswer').value==''){alert('You should write an answer');return false;}return true;}</script>");
}
SB.append("</body></html>");
out.print(SB.toString());
}
} catch (Exception ex) {
out.print("<font style='color:red'><b>" + ex.getMessage() + "</b></font>");
} finally {
out.close();
}
}
#Override
public String getServletInfo() {
return "Short description";
}
}
I think you may have a few concepts muddled a bit, hopefully this explanation will make sense and help you sort things out.
A session lives on your application server. When created, it is communicated to your browser through use of a cookie (often named JSESSIONID). When your browser supplies that cookie to the webserver as part of a request, the server can retrieve the session and associated objects (should be serializable, see other SO questions) that had already been attached to that session (provided that this session has not expired).
As these session variables live only on the server, they are used by the server to build the response given to the client. But in order to have a response, your client needs to make a request. You made a request and changed the state of the first tab, but because the second tab didn't make a request of its own, it's state hasn't updated. (Because these tabs are in the same browser, they share a session cookie, and retrieve the same session to fufill their requests). With some more building out, you could make use of some client side technologies such as AJAX to perodically make small requests about the session state and refresh the display of your browser windows. (You could distinguish such requests by having them call a different resource, or different accept types on the request).
Now with the design of your code... I didn't look at it in too much depth, but you may want to work through your flow a bit more. It seems a GET will always reset your quiz and a post continues it? (This feels somewhat odd to me, but I can't put my finger on why... I'd recommend reading up on REST and designs driven from such. JAX-RS & Jersey is pretty sweet :) ).
Edit: Here's a much simpler servlet that you could use to play with. Plop it into a war, and open 2 tabs, one just to the servlet itself, and another appending the query string ?checkOnly=true. Play with refreshing each tab independently and see what happens to the count.
package test.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Counting servlet counts the number of requests to it.
* #author Charlie Huggard-Lee
*/
#SuppressWarnings("nls")
public class CountingServlet extends HttpServlet {
/**
* The serialVersionUID.
*/
private static final long serialVersionUID = 4279853716717632192L;
/**
* {#inheritDoc}
*/
#Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
final HttpSession session = req.getSession();
AtomicInteger counter = (AtomicInteger) session.getAttribute("Count");
if (counter == null) {
counter = new AtomicInteger();
session.setAttribute("Count", counter);
}
final boolean checkOnly = Boolean.parseBoolean(req.getParameter("checkOnly"));
final int thisCount;
if (checkOnly) {
thisCount = counter.get();
} else {
thisCount = counter.getAndIncrement() + 1;
}
resp.setStatus(200);
resp.setHeader("Content-Type", "text/plain"); //$NON-NLS-1$ //$NON-NLS-2$
resp.setCharacterEncoding("UTF-8"); //$NON-NLS-1$
final PrintWriter writer = resp.getWriter();
if (session.isNew()) {
writer.append("Hey new user!\n");
} else {
writer.append("Welcome Back!\n");
}
writer.append("Session ID: ");
writer.append(session.getId());
writer.append("\n");
if (checkOnly) {
writer.append("(checking) ");
}
writer.append("Count: ");
writer.append(Integer.toString(thisCount));
}
}
When session is established server sends cookie to your browser. The same cookie is sent back everytime an URL matches cookie scope, which (most of the time) is defined by domain & path attributes of a cookie. So it doesn't matter if you have 2, 10 or 50 open tabs in your browser. As long as there's a match between URL you're accessing and your session cookie scope, you will get the same session. As far as browser is concerned, there is no such thing as session, so don't assume that your browser is aware of it. It just simply sends cookies. That's all.
And there are no "two different objects of the same session atribute". Session guarantees that there is only one entry for a given name. You just overwrite it everytime you do a request from other tab.