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 "";
}
Related
Below is the login page:
index.html
<div class="container " >
<h2 align="center" >Account Login</h2><br>
<form action="servlet1" method="post">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input type="text" class="form-control" name="userName" placeholder="Username">
</div> <br>
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
<input type="password" class="form-control" name="userPass" placeholder="Password">
</div>
<div class="form-group">
<br>
<span id="spanbut"><input type="submit" value="Login" class="btn btn-primary" /> </span>
</div>
</form>
</div>
Below is the servlet which checks if username and password match. Username and password is hard coded. If they match, user is navigated to welcome page.
Login.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
#WebServlet("/servlet1")
public class Login extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
String[][] arr = new String [4][4];
arr[0][0] = "ABC";
arr[0][1] = "Password123";
arr[1][0] = "XYZ";
arr[1][1] = "servlet";
arr[2][0] = "PQR";
arr[2][1] = "Outlook123";
arr[3][0] = "TUV";
arr[3][1] = "Hello123";
boolean flag=false;
for (int i = 0; i < arr.length; i++)
{
if(n.equals(arr[i][0]))
{
if(p.equals(arr[i][1]))
{
RequestDispatcher rd=request.getRequestDispatcher("/servlet2");
rd.forward(request, response);
flag =true;
}
}
}
if(flag==false)
{
//out.print("Sorry UserName or Password Error!");
RequestDispatcher rd=request.getRequestDispatcher("incorrect.html");
rd.include(request, response);
}
}}
I must get the username value to the welcome page through html.
Below is the servlet which is getting called for the welcome page.
Do I need a servlet for this?
WelcomeServlet.java
#WebServlet("/servlet2")
public class WelcomeServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
}
}
You can get username by using request.getAttribute() & request.setAttribute() . Like below :
if(n.equals(arr[i][0]))
{
if(p.equals(arr[i][1]))
{
//get username if password and username matched
String username1=a[i][0];
//set username1 in request
request.setAttribute("username", username1);
RequestDispatcher rd=request.getRequestDispatcher("/servlet2");
rd.forward(request, response);
flag =true;
}
}
And then in your WelcomeServlet do like below :
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//getting value got from Login servlet
String n=(String)request.getAttribute("username");
out.print("Welcome "+n);
}
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);
}
}
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.
I am trying to print checked values of checkbox list from a JSP page but nothing appears even if some selections are there.
<form action="process" method="POST">
<c:forEach var="item" items="${list.items}">
<input type="checkbox" name="chkSkills" value="${$item.Id}">${item.name}
</c:forEach>
<input type="submit" name="Getvalue" value="Get value" />
</form>
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String[] Answers = request.getParameterValues("chkSkills");
PrintWriter out = response.getWriter();
String ButClicked = request.getParameter("Getvalue");
if (ButClicked != null) {
for (String Answer : Answers) {
out.print(Answer + "<br>");
}
}
//processRequest(request, response);
}
Correct your value attribute to
value="${item.Id}"
Notice, there's no need to put a $ inside the {} again.
The following servlet handles uploading of a photo and a caption for that photo. The servlet was working fine (uploading the photos to the requested directory) until the logic to handle the text-field of the same from was added. Now it neither uploads the photo nor submits the caption to the database. The form has the enctype of multipart/form-data.
HTML
<form method="post" action="UploadHandler" enctype="multipart/form-data">
<table>
<tr>
<td> <strong> Browse photo to submit </strong> </td>
<td> <input type="file" name="ImageToUpload" value="Upload Photo"/> </td>
</tr>
<tr>
<td> <strong> Give a Caption to this photo </strong> </td>
<td> <input type="text" name="CaptionBox" size="40" /></td>
</tr>
<tr>
<td> <strong> Tags <i> Browse tags </i> </strong> </td>
<td> <input type="text" size="20" value="Tags" id="tagfield" style="color: #A0A0A4; font-size:16px;" onfocus="emptyTheDefaultValue()"> </td>
</tr>
<tr colspan="2">
<td> <input type="submit" value="submit photo"/> </td>
</tr>
</table>
</form>
Servlet that handles uploading
package projectcodes;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
import java.util.List;
import java.util.Iterator;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import NonServletFiles.HandleCaption;
import NonServletFiles.ChangePartToString;
public class UploadHandler extends HttpServlet {
#Override
public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException {
response.setContentType("text/plain");
String path = request.getParameter("ImageToUpload");
// Now handle the caption
// Note : They have a multipart/form-data request
// Using the servlet API 3.0
ChangePartToString cpts = new ChangePartToString(request.getPart("CaptionBox")); // get the CaptionBox part
String caption = null;
try {
caption = cpts.getValue();
System.out.println(caption); // <<-------- I get this value fine
}catch(Exception exc) {
exc.printStackTrace();
System.out.println(exc);
}
PrintWriter writer = response.getWriter();
try {
Boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(!isMultipart) {
Boolean AttemptToUploadFile = true;
RequestDispatcher rd = request.getRequestDispatcher("portfolio_one.jsp");
request.setAttribute("UploadAttempt", AttemptToUploadFile);
rd.forward(request, response);
} else {
DiskFileItemFactory diskFileItem = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(diskFileItem);
List list = null;
try {
list = fileUpload.parseRequest(request);
}catch(Exception exc) {
// Boolean AttemptToUploadFile = true;
// RequestDispatcher rd = request.getRequestDispatcher("portfolio_one.jsp");
// request.setAttribute("UploadAttempt", AttemptToUploadFile);
// rd.forward(request, response);
exc.printStackTrace();
System.out.println(exc);
}
Iterator iterator = list.iterator();
while(iterator.hasNext()) {
String emailOfTheUser = null;
FileItem fileItem = (FileItem)iterator.next();
if(!fileItem.isFormField()) {
String fieldName = fileItem.getFieldName();
String fileName = FilenameUtils.getName(fileItem.getName());
HttpSession session = request.getSession();
if(!session.isNew()) {
emailOfTheUser = (String)session.getAttribute("Email");
}
File file = new File("/home/non-admin/project uploads/project users/" + emailOfTheUser ,fileName);
fileItem.write(file);
// now since the file has been uploaded , upload the caption to the photo
System.out.println("THE CAPTION :" + caption);
HandleCaption hc = new HandleCaption(caption,emailOfTheUser,fileName);
hc.SubmitCaptionToTheDatabase(); // This calls invokes a method that submits a caption to the database
RequestDispatcher rd = request.getRequestDispatcher("portfolio_one.jsp");
String message = "File Uploaded successfully !";
request.setAttribute("SuccessMessage", message);
rd.forward(request, response);
}
}
}
}catch(Exception exc) {
exc.printStackTrace();
System.out.println(exc);
}
}
}
The caption string is returned fine. What could be the reason that file is not uploading. I don't see any exception thrown in the server log.
You're mixing Servlet 3.0 builtin multipart parser with Apache Commons FileUpload. You should not do that. Once a request body is parsed by one API, it cannot be parsed anymore by another API. The client ain't going to resend the same request body multiple times as the server needs to parse it.
Remove Apache Commons FileUpload. You don't need it when already utilizing Servlet 3.0 builtin multipart parser. You only need to add #MultipartConfig annotation to the servlet class in order to get the multipart parser to work correctly for both plain form fields and file fields. You should also not use getParameterXxx() methods. See also How to upload files to server using JSP/Servlet?
Here's the necessasry rewrite of your code so that you get the both values:
#WebServlet("/UploadHandler")
#MultipartConfig
public class UploadHandler extends HttpServlet {
#Override
public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException {
Part imageToUpload = request.getPart("ImageToUpload");
String imageFilename = getFilename(imageToUpload);
InputStream imageContent = imageToUpload.getInputStream();
String captionBox = getValue(request.getPart("CaptionBox"));
// ...
}
private static String getFilename(Part part) {
for (String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
}
}
return null;
}
private static String getValue(Part part) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(part.getInputStream(), "UTF-8"));
StringBuilder value = new StringBuilder();
char[] buffer = new char[1024];
for (int length = 0; (length = reader.read(buffer)) > 0;) {
value.append(buffer, 0, length);
}
return value.toString();
}
}