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 am a complete new t servlet can someone plz tell me what is wrong with my code;i am trying to name input from user in a textbox and then display welcome :"text entered by user in textbox"
here is my code
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class myprogramme extends HttpServlet {
public void service(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException {
res.setContentType("text/html");
PrintWritter out=res.getWritter();
String name=req.getParameter("txtname");
out.println("<b>< font size=8 color="red">" +"welcome:"+ </font> "</b>"+name);
}
}
name of the textbox is txtname which i am storing in name variable
To answer your specific question, you need to escape your String literal (the double quotes surrounding red) and you didn't quote the font close tag (but you could collapse it to a single HTML String) like -
out.println("<b><font size=8 color=\"red\">Welcome:</font></b>" + name);
That being said, this is not a good way to write Java Servlet today. Because it uses presentation in the Servlet.
Edit It's getWriter(), change this
PrintWritter out=res.getWritter();
to
PrintWriter out=res.getWriter();
True, it is not the best way to do it, but I would suggest you to do like below for you to learn it easily:
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String name = req.getParameter("txtname");
StringBuilder sb = null;
try {
sb = new StringBuilder();
sb.append("<b>< font size='8' color='red'>");
sb.append(" Welcome : " + name + " </font></b>");
out.println(sb.toString())
} catch (Exception e) {
e.printStackTrace();
}
}
I haven't test it, hope you can get an idea..
I've tried this question before with little success but that's probably my fault so I'll be as specific as possible!
Part A)
I have a compiled java class which returns a hello world string. The source code for this file is below. After configuring the web.xml setting I am able to get good results from a browser pointing at localhost. This is working exactly as planned.
Part B)
I have an HTML landing page with a single link in it which, when pressed will read a local text file and replace content within it. This is also working exactly as planned.
Part A means I am able to have a client call a server-side java class file and get outputs. Part B means I am able to replace one part of a webpage after a button has been pressed.
My question, from this point is quite straight forward. I would like to merge the two concepts so that when the link from part B is pressed the text updated will reflect the 'hello world' result set from Part A.
Thanks in advance.
Part A Code:
package mypkg;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet {
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
out.println("<!DOCTYPE html>");
out.println("<html><head>");
out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
out.println("<title>Hello, World</title></head>");
out.println("<body>");
out.println("<h1>Hello, world!</h1>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
}
Part B Code
<p id="mySentence">
Click here to update the page.
When you click the link, this content will be replaced.</p>
<script type="text/javascript">
var http = createRequestObject();
function createRequestObject() {
var objAjax;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
objAjax = new ActiveXObject("Microsoft.XMLHTTP");
}else{
objAjax = new XMLHttpRequest();
}
return objAjax;
}
function getNewContent(){
http.open('get','newcontent.txt');
http.onreadystatechange = updateNewContent;
http.send(null);
return false;
}
function updateNewContent(){
if(http.readyState == 4){
document.getElementById('mySentence').innerHTML = http.responseText;
}
}
</script>
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.
This is my download code. It just starts downloading the file without asking user. I've searched multiple forums and nothing seems to work. This is code is in a backing bean attached to a commandButton.
public void doDownloadFile() {
PrintWriter out = null;
try {
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment;filename=test.csv");
out = response.getWriter();
CSVWriter writer = new CSVWriter(out);
List<String[]> stringList = new ArrayList<String[]>();
for (User user : userList) {
String[] string = {user.getEmail(), user.getName(), user.getPassword()};
stringList.add(string);
}
writer.writeAll(stringList);
out.flush();
} catch (IOException ex) {
Logger.getLogger(ViewLines.class.getName()).log(Level.SEVERE, null, ex);
} finally {
out.close();
}
}
This is most likely due to the fact your browser is configured to download files of these types without prompt. The code has nothing to do with it.
The behavior of what to do with a download is 100% local, meaning it's the browser, not you, that determines what to do in that case. Whether the user's browser just dumps the file in a download folder or allows him to save it to a particular spot is entirely up to the browser.
Not much to be done.