java.lang.NullPointerException in servlet error 500 - servlets

When I run my Servlet I get this error:
java.lang.NullPointerException please i tried many solutions but it didn't work it's simple code
public LoginServlett() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("UserName");
String pass = request.getParameter("Password");
RequestDispatcher d=null;
if (name.contentEquals("Gestionnaire") && pass.contentEquals("1234")) {
HttpSession session;
session =request.getSession(true );
d =request.getRequestDispatcher("/EspaceGestionnaire.html");
session. setAttribute("NomSauvegardé" ,name);
}
else {
d = request.getRequestDispatcher("/Authentification.html");
d.forward(request, response);
}
}
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
}
}

A NPE will be thrown from the code if the Username and Password parameters are not set. If they are not set then the user and pass variables will be null, and when the contentEquals methods are called on them a NPE will be thrown as a result.
A way to do this would be to reverse the equality checks so the operation is called on string you want to check:
if ("Gestionnaire".contentEquals(name) && "1234".contentEquals(pass)) {
which will do what your code intends without throwing a NPE.
Although if you are sending passwords over the internet it is better to use POST than GET. For Java EE security there is also the new security API (https://javaee.github.io/security-spec/)

Related

Can I write code after RequestDispatcher?

public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//some code here
}
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//performTask(req, resp);
//some code here
}
private void insertRequestTemplate() {
HttpSession session = req.getSession();
responsePage = req.getParameter("ResponsePage");
ServletContext ctx = getServletConfig().getServletContext();
ctx.getRequestDispatcher(responsePage).forward(req,resp);
readMessage();
public void readMessage()
{
System.out.println("calling MessageTrigger_ABean");
MessageTrigger_ABean msg = new MessageTrigger_ABean();
msg.read();
}
msg.read() has the code to read messages from MQ. Inside insertRequestTemplate method, I am calling readMessage method after ctx.getRequestDispatcher(responsePage).forward(req,resp);is this the correct way of calling this?
But inside insertRequestTemplate method, the page is not getting forwarded to the next page untill readMessage() is executed because of which the page keeps on loading for a long time until message is read from MQ. Could you please help me on this.
Most examples I have seen of a servlet forwarding the request to another servlet have the dispatcher forward invocation at the end of the method. ie. there is no more code, other than closing braces at the end of the method.
I am guessing that the forwarding doesn't happen until the invoking method completes. So where you have your msg.read() will stop the insertRequestTemplate method from completing. This will more than likely be because the code inside msg.read is being performed synchronously. Leading to http timeouts on the http request.
How you solve this will depend on what you want to do with the messages you obtain from msg.read().

CRUD JDBC template problem with delete operation

I have problem with CRUD delete operation. When i click Delete which is written in this way in jsp file <form action="delete?Id=${medicines.id}" method="post">
<input type="submit" value="Delete">
</form>.
Here is my DeleteController(if I type something in doGet, then I get results from it, not blank page)
#WebServlet("/delete")
public class MedicinesDeleteController extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
int id = Integer.parseInt(request.getParameter("Id"));
if(request.getUserPrincipal() != null) {
MedicinesService query = new MedicinesService();
query.delete(id);
response.sendRedirect(request.getContextPath() + "/");
} else {
response.sendError(403);
}
}
}
Delete function from MedicinesService(i think this is my problem)
public void delete(int id) {
DAOFactory factory = DAOFactory.getDAOFactory();
MedicinesDAO medicinesDao = factory.getMedicinesDAO();
Medicines medicines = new Medicines();
medicines.setId(id);
medicinesDao.delete(medicines);
}
And MedicinesDAOImpl
private final static String DELETE_MEDICINES =
"DELETE FROM medicines WHERE id_medicines=:id_medicines;";
#Override
public void delete(Medicines medicines) {
SqlParameterSource namedParameter = new MapSqlParameterSource("Id", medicines.getId());
template.update(DELETE_MEDICINES, namedParameter);
}
New errors
medicinesDao.delete(medicines); < MedicicinesService:41
template.update(DELETE_MEDICINES, namedParameter); < MedicinesDAOImpl:77
query.delete(id); <MedicinesDeleteController:31
Type Exception Report
Message No value supplied for the SQL parameter 'id_medicines': No value registered for key 'id_medicines'
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
org.springframework.dao.InvalidDataAccessApiUsageException: No value supplied for the SQL parameter 'id_medicines': No value registered for key 'id_medicines'
org.springframework.jdbc.core.namedparam.NamedParameterUtils.buildValueArray(NamedParameterUtils.java:355)
org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.getPreparedStatementCreator(NamedParameterJdbcTemplate.java:398)
org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.getPreparedStatementCreator(NamedParameterJdbcTemplate.java:370)
org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.update(NamedParameterJdbcTemplate.java:317)
pl.firstaidkit.dao.MedicinesDAOImpl.delete(MedicinesDAOImpl.java:77)
pl.firstaidkit.dao.MedicinesDAOImpl.delete(MedicinesDAOImpl.java:1)
pl.firstaidkit.service.MedicinesService.delete(MedicinesService.java:41)
pl.firstaidkit.controller.MedicinesDeleteController.doPost(MedicinesDeleteController.java:31)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
pl.firstaidkit.filter.LoginFilter.doFilter(LoginFilter.java:26)
Note The full stack trace of the root cause is available in the server logs.
Original issue was that , this would result in an http get method call and doGet() method had no code to handle the same
Delete
Second issue was with the mismatch in MapSqlParameterSource param name and place holder in query.

Spring Security ExceptionTranslationFilter throw "Unable to handle the Spring Security Exception because the response is already committed."

I'm using spring security web 5.0.9 and tomcat 8. ExceptionTranslationFilter throw ServletException "Unable to handle the Spring Security Exception because the response is already committed."
I dig into the source code and find the root cause. I'm not sure whether it is a bug for spring security.
I throw the UsernameNotFoundException in AuthenticationUserDetailsService.loadUserDetails
SimpleUrlAuthenticationFailureHandler.onAuthenticationFailure catch the exception and then call
public void onAuthenticationFailure(HttpServletRequest request,
HttpServletResponse response, AuthenticationException exception)
throws IOException, ServletException {
if (defaultFailureUrl == null) {
logger.debug("No failure URL set, sending 401 Unauthorized error");
response.sendError(HttpStatus.UNAUTHORIZED.value(),
HttpStatus.UNAUTHORIZED.getReasonPhrase());
}
the sendError will set response committed to true, see ResponseFacade.java:
public void sendError(int sc, String msg)
throws IOException {
...
response.setAppCommitted(true);
...
}
Then ExceptionTranslationFilter catch it and check the response commit status, found it's true and then throw the exception
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
...
if (response.isCommitted()) {
throw new ServletException("Unable to handle the Spring Security Exception because the response is already committed.", ex);
...
}
nobody catch the ServletException and the application try to find the /web_framework/error_page/405.html
I find the spring security code is changed in this bug fix https://github.com/spring-projects/spring-security/issues/5273.
How to deal with the ServletException and return the valid 401 response, but not web_framework/error_page/405.html
This sounds like it could be a misconfiguration in the code.
Typically, if the SimpleUrlAuthenticationFailureHandler is invoked, then the ExceptionTranslationFilter is not also invoked since there is no further response handling required.

does returning from doGet() or doPost() automatically send a resonse

I have looked around and previously asked this question but did not get a full answer. When you explicity return from doGet() or doPost() does a response get sent regardless of if you have encoded anything or not. If so what is the default code ? Is it enough to simply response.setStatus() and return ? If not: so I have always manually send back a response ? What is the default way to just respond not using forward or redirect ?
If you do nothing, just return (or not even return) from a servlet, it will send back a status code 200(OK) empty response. Tested it in both tomcat and glassfish servers, using the servlet below:
#WebServlet("/a")
public class a extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
return;
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
return;
}
}
Using the network profiler tool of Chrome you can see what I said:

Error on Part.getSubmittedFileName

I am uploading a file, and I use javax.servlet.http.Part in the Servlet. It seems to behave strangely, since part.getSubmittedFileName() is returning an error (it seems a POST http://localhost:8080/.... 500 (Internal Server Error) ) so I have to use the old JEE 6 method to obtain the name. What could be happening? I tried to capture the error with a try-catch but when the sentence is executed, it just leaves the Servlet method entirely without entering into the catch block.
#MultipartConfig
#WebServlet(name = "UploadServlet", urlPatterns = {"/uploadServlet"})
public class UploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Part partFile = request.getPart("file");
....
try {
System.out.println("submName " + partFile.getSubmittedFileName()); // never prints
String fileName = partFile.getSubmittedFileName();
} catch (Exception e) {
System.out.println("EX: " + e); // never executes
}
....
}
}

Resources