Java servlet not receiving request attributes [duplicate] - java

This question already has answers here:
Difference between getAttribute() and getParameter()
(10 answers)
Closed 3 years ago.
I'm currently working on a web app in which I want to update the user as to whether or not an operation was successful. I attempt to achieve this by setting request attributes and forwarding from one servlet to the next. However, the attribute is always null in the receiving controller.
code block that sets the attribute:
try {
updateXRef(request, response, cmds);
} catch (Exception e) {
request.setAttribute("results", "Error encountered. Contact system administrator.");
push(request, response);
}
request.setAttribute("results", "Update Successful");
push(request, response);
}
else {
push(request, response);
}
the method that sends to the other servlet:
private void push(HttpServletRequest request, HttpServletResponse response) {
String url = "/PushServer";
try {
request.getServletContext().getRequestDispatcher(url).forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
and the servlet that processes the request:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(FileFactory.getFileOperationsObject() == null || request.getParameterValues("input") == null) {
initiliaze(request, response);
String url = "/Display.jsp";
request.setAttribute("xRefFile", FileFactory.getXRefFileObjects());
request.setAttribute("platforms",FileFactory.getUniqueSortedPlatforms());
request.setAttribute("showModal", 0);
if(request.getParameter("results") == null) {
request.setAttribute("results", "Update Pending");
}
request.getServletContext().getRequestDispatcher(url).forward(request, response);
}
My only guess is that a new request is somehow being generated. If that is indeed what is happening - how do I avoid it?

The problem is method selection.
request.getParameter("yourAttributeName") only works for retrieving form data (<form></form>) - aka data from your .jsp page - as well as query parameters.
If one wishes to send information from one Java servlet to another Java servlet, as in the above code, one must use:
request.getAttribute("myAttributeName");

Related

How to resolve NullPointerException in JSP

I am developing a web application using jsp and servlet and I want to show all my records from my database and the number of records in a table.
I have created a DAO in which I performed queries where they returned the data correctly and put it in a session in a servlet giving the name of sessaoListaMotoristasTodos and totalMotorista.
But when passing the values ​​retrieved from the session and assigning the variables, the values ​​are not assigned, the called variables are List ListMotoristas and Integer totalRegistros giving a java.lang.NullPointerException
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
MotoristasDAO dao= new MotoristasDAO();
MotoristasDAO dao2= new MotoristasDAO();
String pesquisa=request.getParameter("pesquisa");
try {
if(pesquisa==null){
pesquisa="";
}
Integer totalMotorista=dao.totalRegistros(pesquisa);
request.setAttribute("totalMotoristas", totalMotorista);
List listaMotoristas2=dao2.mostrarMotoristas();
request.setAttribute("sessaoListaMotoristasTodos", listaMotoristas2);
RequestDispatcher rd= request.getRequestDispatcher("/listaMotoristas2.jsp");
rd.forward(request, response);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Erro na servelet"+e);
}
}
JSP:
<%
List listaMotoristas=(List) request.getAttribute("sessaoListaMotoristasTodos");
Integer totalRegistros= (Integer) request.getAttribute("totalMotorista");
int totalPaginas=totalRegistros/limite;
if(totalRegistros%limite!=0){
totalPaginas++;
}else{
totalPaginas=0;
}
%>
MotoristasDAO dao2= new MotoristasDAO();
List listaMotoristas2=dao2.mostrarMotoristas();
As per your code you are doing this
request.setAttribute("sessaoListaMotoristasTodos", dao2);
But you should do this
request.setAttribute("sessaoListaMotoristasTodos", listaMotoristas2);
or this
request.setAttribute("sessaoListaMotoristasTodos", dao2.mostrarMotoristas());
you should set the list "listaMotoristas2" in the request and not the "dao2"
and now in the jsp your code is as follows
List listaMotoristas=(List) request.getAttribute("sessaoListaMotoristasTodos");
This will not return a list it will return dao2

jsp/servlet Pages redirection

i have two page JSP profile.jsp and comprofile.jsp
I will make a direction towards page profile.jsp if my attribut booleen etatin my table etat=1 redirection profile.jsp
else if etat=0 redirection comprofile.jsp
My code
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
HttpSession Session = request.getSession();
// response.getWriter().print("welcome" + Session.getAttribute("idoperateur"));
// Object getAttribut(int idoperateur);
String idoperateur = (String)Session.getAttribute("idoperateur");
int etat;
try {
dbcon= new javaConnectDB();
conn=dbcon.setConnection();
stmt=conn.createStatement();
query="select * from operateur where idoperateur='"+idoperateur+"' ";
res=dbcon.getResult(query, conn);
etat=res.getInt(6);
while(res.next()){
etat=res.getInt(6);
lst.add(res.getString("idoperateur"));
lst.add(res.getString("nom_o"));
lst.add(res.getString("prenom_o"));
//lst.add(res.getString("password"));
}
if(etat==0){
request.setAttribute("data", lst);
RequestDispatcher rd= request.getRequestDispatcher("profile.jsp");
rd.forward(request, response);
lst.clear();
res.close();
}
}
catch(Exception e){
System.out.println();
}
}
but it did not work
your etat variable's scope is restricted to while{} loop alone..... then at your if condition etat will not be resolved to a variable
Your usage of try,catch & finally is bad.finally should be used for closing the connections etc.
Anyway it should not be a problem to display the .jsp.
RequestDispatcher rd=response.getRequestDispatcher("full path of jsp");//not just the file name.
You should mention the complete path when you are dispatching to RequestDispatcher.
If you can mention the specific error you are getting i can help.

Program hanging at call for REST service

I am running a REST service on Tomcat and a client service from Eclipse.
My program keeps stopping when on it's second run through. I am not receiving any exceptions in the console running Tomcat
The first time my Controller is called, there is no issue and everything runs fine. After everything executes in the Controller, the user is redirected back to a JSP page. When a button is clicked on the JSP page, the Controller code shown below is run again.
However this time, the program stops in the function:
getOrderDetails(id, order, service);
while executing the line:
String orderXML = service.path("rest").path("coffee").header("user", "customer-123").accept(MediaType.APPLICATION_XML_TYPE).get(String.class);
This line calls the REST service which will interact with my SQLite database and then return some `XML.
I really cannot work out why it is stopping on the second attempt!
Any help with this would be GREATLY appreciated!
Thank you!
Update 1: If it's of any significance, I find that when the program hangs, I need to not only quit Eclipse and restart it, but I also need to restart the server. Otherwise, the client program won't work properly.
Update 2: I have defined only one ClientResponse to be used at all points in the program.
Update 3: I've been using ClientResponse.close() after each of my requests.
NOTE: Code updated to reflect comment below
Controller:
static ClientConfig config = new DefaultClientConfig();
static Client client = Client.create(config);
static WebResource service = client.resource(getBaseURI());
ClientResponse clientResp;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Get All Coffee Orders
clientResp = service.path("rest").path("coffee").header("user", "customer-123").type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).get(ClientResponse.class);
String orderXML = clientResp.getEntity(String.class);
clientResp.close();
try {
Document document = loadXMLFromString(orderXML);
NodeList nodeList = document.getDocumentElement().getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element elem = (Element) node;
CoffeeOrder order = new CoffeeOrder();
// Set ID
String id = elem.getElementsByTagName("id").item(0).getChildNodes().item(0).getNodeValue();
order.setId(id);
// Get ALL Order Details
getOrderDetails(id, order);
// Get ALL Payment Details
getPaymentDetails(id, order);
// If order has not been cancelled, add to open orders
if (!order.getOrderStatus().equals("cancelled")){
openOrders.add(order);
// If order has been cancelled, add to cancelled orders.
} else {
cancelledOrders.add(order);
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp");
dispatcher.forward(request, response);
}
// Get all Order Details
private void getOrderDetails(String id, CoffeeOrder order){
// PROGRAM STOPS HERE ON SECOND RUN THROUGH
clientResp = service.path("rest").path("coffee").path(id).header("user", "customer-123").type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).get(ClientResponse.class);
orderXML = clientResp.getEntity(String.class);
clientResp.close();
// Do Things here with XML
} catch (Exception e){
e.printStackTrace();
}
}
// Get all Payment Details
private void getPaymentDetails(String id, CoffeeOrder order){
clientResp = service.path("rest").path("payment").path(id).header("user", "customer-123").type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).get(ClientResponse.class);
orderXML = clientResp.getEntity(String.class);
clientResp.close();
// Do Things here with XML
} catch (Exception e){
e.printStackTrace();
}
}
I finally realised what the problem was...
It had to do with multiple database connections that were being opened on the server side! This was causing the issue and once I dealt with that the problem resolved itself.
Thanks for all your help!

What is the behaviour of getParameter for post and get actions?

I have a java servlet with a URL Query string with instructions like this
http://hostname/servet?param1=value1&param2=value2
I also structure the doPost/doGet like this
public void doPost(HttpServletRequest req, HttpServletResponse res) {
try {
doGet(req, res);
} catch (Exception e) {
e.printStackTrace();
}
}
public void doGet(HttpServletRequest req, HttpServletResponse res) {
try {
String sParam1 = req.getParameter("param1")
} catch (Exception e) {
e.printStackTrace();
}
}
I can access each queryString parameters via getParameter() for GET actions. But when I attempt to access the same queryString via getParameter() for POST actions, the returned value is NULL.
So, I would like to confirm this behaviour of getParameter for POST and GET actions. That is getParameter does NOT return queryString parameters for POST actions ? And do I need to manually dissect a query string to process them in cases of a POST action ?
For GET method, parameters are sent as part of the URL (the query string), for POST method parameters are sent as part of the body, that's why in the POST case you don't get the parameters, as they are searched in the body not in the URL.
do I need to manually dissect a query string to process them in cases of a POST action ?
Yes, if you are in the case where you are sending a query string but using method POST, you'll have to parse the query string by yourself, unless you honor the standards and send parameters inside the body rather than in the URL.

response.sendRedirect() in Servlet not working correctly after file upload

I have a web application with a simple upload function. The idea is to allow user select a file and upon successfully upload, redirect to index.jsp.
However, although the file got uploaded, the response.redirect is not working. After a successfully upload, the page doesn't get redirected. It just stays there. The weird thing is that I can see it is processing the index.jsp from the tomcat server log even though it doesn;t get redirected.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//processRequest(request, response);
boolean status=false;
if (!ServletFileUpload.isMultipartContent(request)) {
throw new IllegalArgumentException("Request is not multipart, please 'multipart/form-data' enctype for your form.");
}
ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
PrintWriter writer = response.getWriter();
response.setContentType("text/plain");
try {
List<FileItem> items = uploadHandler.parseRequest(request);
for (FileItem item : items) {
if (!item.isFormField()) {
File file = new File(getServletContext().getRealPath("/WEB-INF/upload"), item.getName());
item.write(file);
writer.write("{\"name\":\"" + item.getName() + "\",\"type\":\"" + item.getContentType() + "\",\"size\":\"" + item.getSize() + "\"}");
}
}
//redirect to index.jsp if successfully
redirect(request, response);
} catch (FileUploadException e) {
throw new RuntimeException(e);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
writer.close();
}
}
The redirect method:
private void redirect(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
The file upload plugin is from https://aquantum-demo.appspot.com/file-upload
I used the front-end and developed the upload event handler using java apache fileupload. Everything works fine except the redirect part.
The application.js file which handles the JSON returns:
$(function () {
// Initialize jQuery File Upload (Extended User Interface Version):
$('#file_upload').fileUploadUIX();
// Load existing files:
$.getJSON($('#file_upload').fileUploadUIX('option', 'url'), function (files) {
var options = $('#file_upload').fileUploadUIX('option');
options.adjustMaxNumberOfFiles(-files.length);
$.each(files, function (index, file) {
options.buildDownloadRow(file, options)
.appendTo(options.downloadTable).fadeIn();
});
});
});
Any ideas?
You're attempting to send two responses on a single request. One with JSON data in the response body and one which redirects the response to another request. This is not going to work. You can send only one response back per request. A redirect requires an untouched (uncommitted) response body, otherwise the redirect will just fail with IllegalStateException: response already committed in the server logs.
You need to move the redirect call from the servlet code to JavaScript code. Get rid of the redirect() line in the servlet and add the following line as the last line of the $.getJSON() callback function.
window.location = '/index.jsp';
This way JavaScript will take care of the redirect.

Categories

Resources