I have a trouble with servlet coding and I don't know how to solve it.
I was trying to track a session (using TomCat web server) using only hidden parameters.
In this example there are name, surname and email as parameters. My idea was to ask the client just one parameter per time and send it to him as hidden parameter (iteratively).
If I start just one session (since when the client sends the first parameter to when the client sends the last parameter) my servlet works fine.
The problem is when I start another session:
when i send to to server the surname (a different value from the revious session) the server gives me an url where there is two times the hidden parameter "surname" with the value of the current surname and the value of the previous one's session surname.
Here is my servlet class:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class HiddenParamServlet extends HttpServlet {
private final String[] PARAMS = { "name", "surname", "e-mail" };
private Map<String, String> hiddenParameters;
#Override
public void init() {
hiddenParameters = new HashMap<String, String>();
}
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// control the last parameter added by the client
List<String> clientParameters = Collections.list(request.getParameterNames());
// checks if the client already sent all the parameters
if(clientParameters.size() == 3) {
// start the html document
out.println("<html><head><title>Session finished</title></head>");
out.println("<body><h1>Session succesfully completed</h1></body>");
out.println("</html>");
// end the html
out.close();
hiddenParameters.clear();
}
else {
String lastParam = clientParameters.get(clientParameters.size() -1);
//memorizing the last param sent by the client
String value = request.getParameter(lastParam);
hiddenParameters.put(lastParam, value);
// starts the HTML document
out.println("<html>");
out.println("<head><title>Tracking session with hidden parameters</title></head>");
out.println("<body>");
out.println("<form method=\"get\" action=\"/DirectoryDiSaluto/HiddenParamServlet\">");
out.println("<p>");
//write the next parameter to ask to the client
out.println("<label>Insert "+PARAMS[clientParameters.size()]+":");
// write the hidden parameters of the server
for(String key : hiddenParameters.keySet()) {
out.println("<input type=\"hidden\" name=\""
+key+"\" value=\""+hiddenParameters.get(key)+"\" />");
}
out.println("<input type=\"text\" name=\""+PARAMS[clientParameters.size()]+"\" />");
out.println("<input type=\"submit\" value=\"Submit\" />");
out.println("</label>");
out.println("</p>");
out.println("</form>");
out.println("</body>");
out.println("</html>");
// end the html
out.close();
}
}
}
Here is the html page where all starts:
<html>
<head>
<title>Tracking session with hidden parameters</title>
</head>
<body>
<form method="get" action="/DirectoryDiSaluto/HiddenParamServlet">
<p>
<label>Insert name:
<input type="text" name="name"/>
<input type="submit" value="Submit" />
</label>
</p>
</form>
</body>
</html>
I can't understand where the problem is. Can you help me? Thanks so much!
hiddenParameters is guilty of this behaviour, because of its bad scope. Have a look at this answer for more explanations.
Related
Is it normal that when I log in and enter the page for login and refresh the page the session ID changes and a new session is created?
I state that I use TomCat.
From the page of index.html through a form I log in to redirect myself to this java page, once the java html page is opened it just gives me back what I ask, but if I resfresh the page on tomcat I know that it creates me a new session, is it normal? My goal is to have a session for each individual user, how do I do it?
"index.html"
<html>
<head>
<title> Inserisci nome </title>
</head>
<body>
<p> <h2>Inserisci il tuo nome </h2>
<form action="/Esercizio8/SerSal" method="post">
<input type="text" name="nome"> <strong>USERNAME</strong> <br>
<input type="password" name="pwd"> <strong>PASSWORD</strong> <br>
<br>
<input type="submit" value="Invia">
</form>
</body>
</html>
"SerSal.java"
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SerSal extends HttpServlet{
int count;
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException{
String name = request.getParameter("name");
String pwd = request.getParameter("pwd");
HttpSession session = request.getSession();
session.setAttribute("Name",name);
session.setAttribute("Password",pwd);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>HELLO!</title></head>");
out.println("<body>");
out.println("Hello " + name);
out.println("This " + (session.isNew()? "is" : "is not") + " a new session! <br>");
out.println("</body>");
out.println("</html>");
out.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException{
HttpSession session = request.getSession(false);
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Hello i have the above code
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class CarSessionServlet2 extends HttpServlet {
private String Brands[] = {
"Audi", "Ford", "Toyota"
};
private String Cars[] = {
"A3", "Fiesta", "Yaris"
};
private String screen = "name";
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // reaction
if (screen.equals("name")) { //elegxos apo poia selida kalw tin doPost. Edw apo tin BrandsSelection.html
String cookieName = request.getParameter("name"); // choice made
// will be sent
// back to
// client
String cookieBrand = request.getParameter("brands");
PrintWriter output;
HttpSession session = request.getSession(true);
session.setAttribute("name", cookieName);
session.setAttribute(cookieBrand, getCars(cookieBrand));
response.setContentType("text/html");
output = response.getWriter();
// send HTML page to client
output.println("<HTML><HEAD><meta charset='utf-8'><TITLE>");
output.println("Cookies");
output.println("</TITLE></HEAD><BODY>");
output.println("<P>Welcome Ms./Mr.: ");
// output.println( "<P>" );
output.println(cookieName);
output.println(" <BR> you have chosen ");
output.println(cookieBrand);
output.println("<BR><a href='SecondPage.html'>" + "Click here to continue..." + "</a>");
output.println("</BODY></HTML>");
output.close(); // close stream
screen = "color";
}
if (screen.equals("color")) { //elegxos apo poia selida kalw tin doPost. Edw apo tin SecondPage.html
PrintWriter output;
String color = request.getParameter("color");
HttpSession session = request.getSession(true);
session.setAttribute("color", color);
response.setContentType("text/html");
output = response.getWriter();
// send HTML page to client
output.println("<HTML><HEAD><meta charset='utf-8'><TITLE>");
output.println("Cookies");
output.println("</TITLE></HEAD><BODY>");
output.println("<FORM ACTION=\"http://localhost:8080/Askisi2Session/CarSessionServlet2\" METHOD=\"GET\">");
output.println("<STRONG>To see your selections press the button:<br> </STRONG>");
output.println("<INPUT TYPE=\"submit\" VALUE=\"Selections\">");
output.println("</FORM>");
output.println("</BODY></HTML>");
output.close(); // close stream
screen = "name";
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // reaction
// to
// the
// reception
PrintWriter output; // of
// GET
response.setContentType("text/html");
output = response.getWriter();
output.println("<HTML><HEAD><meta charset='utf-8'><TITLE>");
output.println("Cookie with your selections has been read !");
output.println("</TITLE></HEAD><BODY>");
HttpSession session = request.getSession(false); // get client's session;
output.println("<H3>Here is your saved session data:</H3>");
Enumeration e;
if (session != null) {
e = session.getAttributeNames();
} else {
e = null;
}
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
output.println(name + ": " + session.getAttribute(name) + "<BR>");
}
output.println("<a href='BrandsSelection.html'>Click here to Restart...</a>");
output.println("</BODY></HTML>");
output.close(); // close stream
}
private String getCars(String conString) {
for (int i = 0; i < Brands.length; ++i)
if (conString.equals(Brands[i])) {
return Cars[i];
}
return ""; // no matching string found
}
} // END OF CLASS CookieServlet
when i run it with tomcat 8.0.28 i get a java.lang.NullPointerException mentioning
java.lang.NullPointerException
CarSessionServlet2.getCars(CarSessionServlet2.java:155)
CarSessionServlet2.doPost(CarSessionServlet2.java:43)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Line 43 is that
session.setAttribute(cookieBrand,getCars(cookieBrand));
and line 155 is that
if (conString.equals(Brands[i])) {
First i open an html page, i fill up a textbox, make a choice on a radiobutton and then i press a submit button which calls the doPost method. Then A second html page appears. I fill up another text box and by pressing another submit button i call the doPost method again (2nd if statement, screen=color). And then..... NullPointerException. It was supposed to appear another html page with a button that calls the doGet method.
I do not know why i take that exception
Html Page 1(BrandsSelection)
<HTML>
<HEAD>
<TITLE>Cookie will be written in our disc</TITLE>
</HEAD>
<BODY>
<FORM ACTION="http://localhost:8080/Askisi2Session/CarSessionServlet2" METHOD="POST">
<STRONG>Enter Your Name:<br> </STRONG>
<PRE>
<INPUT TYPE="text" NAME="name"><br><br>
<STRONG>Select the Brand of your Desire:<br> </STRONG>
<PRE>
<INPUT TYPE="radio" NAME="brands" VALUE="Audi">check here for Audi<BR>
<INPUT TYPE="radio" NAME="brands" VALUE="Ford">check here for Ford<BR>
<INPUT TYPE="radio" NAME="brands" VALUE="Toyota" CHECKED>check here for Toyota<BR>
</PRE>
<INPUT TYPE="submit" VALUE="Submit">
<INPUT TYPE="reset"> </P>
</FORM>
</BODY>
</HTML>
HTML PAGE 2(SeondPage)
<HTML>
<HEAD>
<TITLE>Cookie taken into Account</TITLE>
</HEAD>
<BODY>
<FORM ACTION="http://localhost:8080/Askisi2Session/CarSessionServlet2" METHOD="POST">
<STRONG>What is your favorite color?<br> </STRONG>
<PRE>
<INPUT TYPE="text" NAME="color"><br>
</PRE>
<INPUT TYPE="submit" VALUE="Submit">
</FORM>
</BODY>
</HTML>
This method getCars(...) return "" because the condition if(conString.equals(Brands[i])) doesn't match of any string:
private String getCars(String conString) {
for (int i = 0; i < Brands.length; ++i)
if (conString.equals(Brands[i])) {
return Cars[i];
}
return "";
}
I have created two forms in my jsp. 1st one is an upload functionality and other is the submit page functionality. My requirement is to upload the file using upload functionality. and if upload is successful . The pass the file name back to jsp and on submit button pass the file name along with other details to other page.
My code:
MyJsp.jsp
</tr>
<tr>
<td colspan="2" rowspan="2" align="center"> <form action="UploadDownloadFileServlet" method="post"
enctype="multipart/form-data" class="CSSTableGenerator">
Select the Raw Data Sheet of Customer : <input type="file"
name="fileName" class="button"> <input type="submit" value="Upload"
class="button">
</form>
<form action="DataController" method="post" >
<input type="submit" name="listUser" value="Confirm Selection"
class="button" align="middle">
</form>
</td>
</tr>
</table>
My Controller (Servlet):
UploadDownloadFileServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(!ServletFileUpload.isMultipartContent(request)){
throw new ServletException("Content type is not multipart/form-data");
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.write("<html><head></head><body>");
try {
List<FileItem> fileItemsList = uploader.parseRequest(request);
Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
while(fileItemsIterator.hasNext()){
FileItem fileItem = fileItemsIterator.next();
System.out.println("FieldName="+fileItem.getFieldName());
System.out.println("FileName="+fileItem.getName());
System.out.println("ContentType="+fileItem.getContentType());
System.out.println("Size in bytes="+fileItem.getSize());
String fileName = fileItem.getName().substring(fileItem.getName().lastIndexOf("\\") + 1);
System.out.println("FILE NAME>>>>"+fileName);
File file = new File(request.getServletContext().getAttribute("FILES_DIR")+File.separator+fileName);
System.out.println("Absolute Path at server="+file.getAbsolutePath());
fileItem.write(file);
HttpSession session = request.getSession();
session.setAttribute("Success", "Success");
getServletContext().getRequestDispatcher("/Welcome.jsp").forward(request, response);
/*out.write("File "+fileName+ " uploaded successfully.");
out.write("<br>");
out.write("Download "+fileName+"");*/
}
} catch (FileUploadException e) {
out.write("Exception in uploading file.");
HttpSession session = request.getSession();
session.setAttribute("Failed", "Failed");
getServletContext().getRequestDispatcher("/Welcome.jsp").forward(request, response);
} catch (Exception e) {
out.write("Exception in uploading file.");
HttpSession session = request.getSession();
session.setAttribute("Failed", "Failed");
getServletContext().getRequestDispatcher("/Welcome.jsp").forward(request, response);
}
out.write("</body></html>");/**/
}
}
My Next Contoller for submit button which needs value:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String upload = (String)request.getAttribute("Success");
if(upload.equalsIgnoreCase("Success")){
System.out.println("SERVLET DOPOST");
String action = (String) request.getAttribute("DownLoadToExcel");
System.out.println(action);
String[] kpi = request.getParameterValues("kpi");
how is it possible in jsp to know that upload was successful and submit should go forward else give an error.
Awaiting reply.
Thanks,
MS
First, after UploadDownloadFileServlet successfully receives and process the upload, you should make it go back to the JSP. You need to "redirect it" to "MyJsp.jsp".
HttpServletResponse.sendRedirect("MyJsp.jsp?fileName2="+fileName);
//- you can also call sendRedirect from a PrintWriter -
Then, in the 2nd form in the JSP you could use something (javascript, scriptlets, a tag library, a custom tag, etc) to detect the parameter "fileName2" and set a hidden input with the name of the file.
Keep in mind you don't sendRedirect() and forward() for the same response.
You can pass as many parameters as you want together with the file name.
i'm new to jsp , i have already a servlet that works , it sends parametres in the url (url/servletname?name=test&msg=test2), but i want to make a jsp file that transform that to be visual, i don't know how to start , here's is my servlet :
package mypackage;
import java.io.IOException;
import javax.servlet.http.*;
import java.util.*;
//import ma.cloud.ParticipantDao;
public class infoservlet extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/plain");
String p_name=req.getParameter("name");
String p_msg=req.getParameter("message");
String p_resp_text="";
if (p_id !=null && p_response !=null){
try {
Demand_aide_dao dao=new MemeCache_Demande_aide();
dao.respond_demande_aide_by_id(p_id, p_response);
p_resp_text="Hi Mr." + p_name + " }";
} catch (Exception e) {
// TODO: handle exception
p_resp_text="message : error" + e.getMessage()+ " }";
}
}
resp.getWriter().println(p_resp_text);
}
}
i just need an idea on how to start, and how to turn it from a parametres in url to values that i can type it . please i'm stuck for 5 days now
Params to type, ' transform that to be visual'
Do you mean a form ?
In a text file type :
<html>
<body>
<form action=/path/to/your/servlet/infoservlet method=post name=f1>
<input type=text name="name">
<input type=text name=" message">
<input type=submit value="Go">
</form>
Save this as start.html or start.jsp (at this point there is no difference as the jsp does not have any jsp specific code, but later can add other elements to it).
In folder where your web content goes (depends what app container you are using for Jboss 5 free version can put it in :
jbossMain\server\default\deploy\ROOT.war\
And start jboss with default :
jbossMain/bin/run.sh -c default
Open this jsp in browser, type values press Go, by default jboss would start with port 8080 make sure no other service us running on same port before.
http://localhost:8080/start.jsp
You need to go thru a tutorial on starting web apps and java jsps.
See
* https://www.google.com/search?q=java+jsp+tutorial
* http://www.jsptut.com/
* http://www.tutorialspoint.com/jsp/
I'm experimenting with sending data from a jsp form and calling a servlet and showing that data in the servlet.
I would like to use setAttribute and getAttribute.
In this jsp file I'm using setAttribute:
<HTML>
<HEAD>
<TITLE>
Multi Processor
</TITLE>
</HEAD>
<BODY>
<h4>This is a form submitted via POST:</h4>
<FORM action = "/MyWebArchive/MulitProcessorServlet" method = "POST">
Enter your name: <INPUT type="TEXT" name="name"/>
<BR/>
<INPUT type="submit"/>
</FORM>
<BR/>
<h4>This is a form submitted via GET:</h4>
<FORM action = "/Week05WebArchive/MulitProcessorServlet">
Enter your name: <INPUT type="TEXT" name="name"/>
<BR/>
<INPUT type="submit"/>
</FORM>
</BODY>
<%
String strMasjidLocation = "Selimiyie Masjid Methuen";
session.setAttribute("MasjidLocation", strMasjidLocation);
%>
</HTML>
This is the servlet I would like to use getAttribute but I don't know how to use GetAttribute. Can you show me what additional code I need to add to the servlet so I can capture the value from the setAttribute?
package temp22;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Locale;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class MulitProcessorServlet
*/
public class MulitProcessorServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
doPost(req, res);
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
String name = req.getParameter("name");
StringBuffer page = new StringBuffer();
String methodWhoMadeTheCall = req.getMethod();
String localeUsed = req.getLocale().toString();
String strMasjidLocation = null;
//strMasjidLocation = this is where I would like to capture the value from the jsp that called this servlet.
page.append("<HTML><HEAD><TITLE>Multi Form</TITLE></HEAD>");
page.append("<BODY>");
page.append("Hello " + name + "!");
page.append("<BR>");
page.append("The method who called me is: " + methodWhoMadeTheCall);
page.append("<BR>");
page.append("The language used is: " + localeUsed);
page.append("<BR>");
page.append("I am at this location: " + strMasjidLocation);
page.append("</BODY></HTML>");
res.setContentType("text/html");
PrintWriter writer = res.getWriter();
writer.println(page.toString());
writer.close();
}
}
This should work:
String value = (String) req.getSession(false).getAttribute("MasjidLocation")
Don't use scriptlets; that's 1999 style. Learn JSTL and write your JSPs using that.
Your servlets should never, ever have embedded HTML in them. Just validate and bind parameters, pass them off to services for processing, and put the response objects in request or session scope for the JSP to display.
I agree with duffymo that you should learn on newer technology (if this is applicable, maybe your client cannot allow that...). Anyway, to get the value of the attribute you owuld do:
strMasjidLocation = (String)req.getSession().getAttribute("MasjidLocation");
Also, I notice you have two different paths for your servlets in your HTML < form> tags:
MyWebArchive/MulitProcessorServlet
and
Week05WebArchive/MulitProcessorServlet
Is it expected?
You used Session not Request.
you may need to get Session from request.
String strMasjidLocation = request.getSession().getAttribute("MasjidLocation");