Simple Servlet and Nullpointerexception (error 500) - java

I get following error after trying to launch my first servlet... what may be wrong? I am using proper method (get) and the same code works for my friend... is it possible to be tomcat's fault?
org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet Ciastko threw exception
java.lang.NullPointerException
DOGET method:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=UTF-8");
HttpSession sesja = request.getSession(true);
PrintWriter out = response.getWriter();
String login = request.getParameter("login");
String pass = request.getParameter("pass");
if(login.isEmpty() || pass.isEmpty()){
out.println("Brak sesji lub atrybutu.");
}
if(login.equals("admin") || pass.equals("admin")){
out.println("ADMIN");
}
else{
sesja.setAttribute("login", login);
sesja.setAttribute("pass", pass);
}
}
and here is index.html file:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Tytuł</title>
</head>
<body>
<form action="Ciastko" method="GET">
<p>Login: </p><input name="login" id="login" />
<p>Hasło: </p><input name="pass" id="pass" />
<input type="submit" value="Wyślij!" />
</form>
</body>
</html>

ServletRequest.getParameter
Returns the value of a request parameter as a String, or null if the parameter does not exist.
You're not checking your login/pass for null, which will make isEmpty crash if the parameters are not set.

Related

Update password from database using JavaServlet

Hello, im working on a project in the university, and im stuck on an error.
Im working on a mypage feature, where you can update your old password, when you are looged in. The problem is that ChangepasswordServlet is not doing what it is supposed to do.
Here you can see my servlet, the problem is probably somewhere in the IF sentence. (Manager=Entitymanager)
#WebServlet(name = "ChangePasswordServlet", urlPatterns = {"/ChangePassword"})
public class ChangePasswordServlet extends HttpServlet {
#EJB
UserManagerLocal manager;
private void changePassword(HttpServletRequest request, HttpServletResponse response) throws IOException {
String loggedInUsersUsername = request.getRemoteUser();
/* PrintWriter writer = response.getWriter(); */
User userFromTheDB = manager.getUser(loggedInUsersUsername);
String oldPasswordFromDB = userFromTheDB.getPassword();
String oldPasswordFromForm = (String) request.getAttribute("theOldPW");
;
String newPasswordFromForm = (String) request.getAttribute("theNewPW");
String newPasswordToCheckFromForm = (String) request.getAttribute("theNewPWCheck");
try {
if (oldPasswordFromDB.toLowerCase().equals(oldPasswordFromForm.toLowerCase()) && newPasswordFromForm.toLowerCase().equals(newPasswordToCheckFromForm.toLowerCase())) {
userFromTheDB.setPassword(newPasswordFromForm);
manager.updateUser(userFromTheDB);
response.sendRedirect("/Slit/MyPage/PasswordSucsess.jsp");
} else {
response.sendRedirect("Slit/Error/error.jsp");
}
}
catch (NullPointerException en) {
PrintWriter print = response.getWriter();
print.println("nullpointeryes");
print.close();
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
changePassword(request, response);
}
#Override
protected void doPost (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
changePassword(request, response);
}
so
Here is my JSP with the form
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<head>
<title>Her kan du endre ditt nåværende passord</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css"
href="/Slit/Templates/CSS/MainPageTemplate.css">
</head>
<body>
<title>Slit</title>
<div>
<div class="form">
<form method="post" action="/Slit/ChangePassword">
<input type="Password" name="theOldPW" placeholder="Gammelt
Password"/>
<input type="Password" name ="theNewPW" placeholder="Nytt
Password"/>
<input type="Password" name ="theNewPWCheck" placeholder=" Nytt
Password på nytt"/>
<input type="submit" name="ByttePassord" value="Trykk her for å bytte
passord!"/>
</form>
</div>
</div>
</body>
</html>
</head>
<body>
</body>
So im getting nullpointer after i have filled in the form with the old and the new password.
If im running the code now, im getting the "nullpointeryes" error.
Edit:
This is the console error after filling in the form:
12:39:37,194 INFO [stdout] (default task-12) Hibernate: select
user0_.username as username2_3_0_, user0_.fName as fName3_3_0_, user0_.lName
as lName4_3_0_, user0_.password as password5_3_0_, user0_.DTYPE as
DTYPE1_3_0_ from User user0_ where user0_.username=?
Thanks for any answers
After hours i figured that i used get.attribute instead of parameter :/
String newPasswordFromForm = (String) request.getParameter("theNewPW");
String newPasswordToCheckFromForm = (String)
request.Paramter("theNewPWCheck");

Multiple servlet communication

I have a simple servlet 'Login' deployed in Server A tomcat
Index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Login</h1>
<form method="post" action="Validate">
User: <input type="text" name="user" /><br/>
Password: <input type="text" name="pass" ><br/>
<input type="submit" value="submit">
</form>
</body>
Validate.java
doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
String name = request.getParameter("user");
String pass = request.getParameter("pass");
if(pass.equals("1234"))
{
//creating a session
HttpSession session = request.getSession();
session.setAttribute("user", name);
response.sendRedirect("Welcome");
}
else
{
PrintWriter out = response.getWriter();
out.println("Wrong password!!!");
}
}
Welcome.Java
doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
String user = (String)session.getAttribute("user");
out.println("Welcome"+user);
}
This set up works fine.
Now what I want to try is to create another Servlet 'Validate' which would be deployed in another Server B tomcat with a different IP. I need to pass the parameters from Servlet 'Login' to Servlet 'Validate' which will then validate the credentials and send back the validation message, a String, to the Servlet 'Login' which will then display the same on its index.jsp page.
Please provide some help on this. Let me also add that I have no prior experience in servlets.

Servlet to JSP certain element in ArrayList

Im trying pass specific element from my Model to servlet to jsp.
This is working in my servlet: System.out.println(beanModel.getSortedDomainList().get(0).split(";")[1]) When I go to http://localhost:8080/Comparebet/Controller
But I dont know what Im doing wrong since I dont get it to my jsp. All tutorials ive been watching is mostly input parameters or they put code in the JSP.
UPDATE EDIT
Tried with this in my JSP and I get "null"
<%= request.getAttribute("rank1") %>
SERVLET
#WebServlet("/Controller")
public class Controller extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// ArrayList<String> sortedDomainList = new BeanModel().getSortedDomainList();
BeanModel beanModel = new BeanModel();
request.setAttribute("rank1", beanModel.getSortedDomainList().get(0).split(";")[1]);
RequestDispatcher view = request.getRequestDispatcher("view.jsp");
view.forward(request, response);
//TESTING SERVLET
System.out.println(beanModel.getSortedDomainList().get(0).split(";")[1]);
System.out.println("CONTROLLER CALLED");
// System.out.println(${rank1});
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
}
}
JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>CompareBet</title>
</head>
<body>
<form action="/Controller/*" method="get">
<h1>${rank1.getSortedDomainList().get(0).split(";")[1] } </h1>
</form>
</body>
</html>
In your JSP try this, instead of rank1.getSortedDomainList().get(0).split(";")[1]
<h1>${request.rank1 } </h1>
You have already done beanModel.getSortedDomainList().get(0).split(";")[1] in your servlet and have added the result to the request scope object.
Try to replace this line in your jsp:
<h1>${rank1.getSortedDomainList().get(0).split(";")[1] } </h1>
To this:
<h1>${rank1} </h1>
In JSP you can access this data using the expression language like ${rank1}.
And take it out from the <form like this:
<form action="/Controller/*" method="get">
...
</form>
Try to use <h1><%= request.getParameter("rank1")%></h1>

Passing value from servlet to Textbox in JSP

I'm trying to develop a simple web app that takes the input and run a specific command, and return the result to the user. I'm struggling a little bit when I'm trying to pass the result/output to a textbox, it always shows null...
What am I missing here?
JAVA Code:
public boolean CheckSite(String site) throws Exception
{
try
{
Process p=Runtime.getRuntime().exec("cmd /c nslookup -debug "+site+".abc.internal.rpz | findstr 666");
p.waitFor();
BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=reader.readLine();
if (line == null)
{
System.out.println("This website is not blocked");
return false;
}
else if(line!=null && line.contains("666"))
{
System.out.println("Website is blocked");
return true;
}
}
catch(IOException e1) {}
return false;
}
Servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
String site = request.getParameter("text1");
try {
b=ec.CheckSite(site);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute("value", b);
}
JSP Page:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Website Status</title>
</head>
<body>
<form align ="middle" action ="checkBlocked" method="post">
Please Enter The Website
<input type ="text" name ="inputText" >
<br>
<input type ="submit" value ="Submit">
</form>
<input type="text" name="done" value='<%=request.getAttribute("TextValue")%>'/>
</body>
</html>
Thank you in advance
You're setting attribute name:
request.setAttribute("value", b);
And trying to retrieve as:
getAttribute("TextValue")
Scriptlets are not recommended. JSP EL and JSTL are the way to go for this task (IMHO).
Make your servlet name is checkBlocked like it says below:
<form align ="middle" action ="checkBlocked" method="post">
Then forward or redirect the response from your servlet to your jsp:
request.getRequestDispatcher("confirmationPage.jsp").forward(request, response);

No context on this server matched

Here is my index.jsp code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Index JSP File</title>
</head>
<body>
<form action="/IndexController" method="get">
<table>
<tr><td>Enter Your Name :</td> <td><input type="text" name="name"/></td></tr>
<tr><td><input type="submit" value="Submit" /></td></tr>
</table>
</form>
</body>
</html>
Here is my IndexController Servlet code:
public class IndexController extends HttpServlet {
protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uname = request.getParameter("name");
response.sendRedirect("welcome.jsp?name="+uname);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doProcess(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doProcess(request, response);
}
}
Here is my welcome.jsp page code
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<% String fname = request.getParameter("uname");%>
<h1>Welcome to JSP World, <%=fname%></h1>
</body>
</html>
When I run this through the Java EE runtime, I got an index.jsp page, but after I entered a name and click submit I got the following error:
Error 404 - Not Found No context on this server matched or handled this request. Contexts known to this server are: JSPExample(/JSPExample)
Also change the line in welcome.jsp <% String fname = request.getParameter("**uname**");%> to <% String fname = request.getParameter("**name**");%>, since your parameter name is name response.sendRedirect("**welcome.jsp?name="+uname);** :)
Edit web.xml and add the servlet mapping
<servlet>
<servlet-name>IndexController</servlet-name>
<servlet-class>IndexController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>IndexController</servlet-name>
<url-pattern>/IndexController</url-pattern>
</servlet-mapping>
In eclipse if you face with this problem, just create a new index file with another name. Then terminate last running server, and start a new server, run the new index.. file. I solve this problem wiht this way, at the end I delete the new index file and run my first index file.

Categories