How to resolve NullPointerException in JSP - java

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

Related

retrive session attribute and sort it into String [duplicate]

This question already has answers here:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
(6 answers)
Closed 7 years ago.
I've been a PHP developer but recently need to work on some project using Google App Engine (Java). In PHP I can do something like this (in term of MVC model):
// controllers/accounts.php
$accounts = getAccounts();
include "../views/accounts.php";
// views/accounts.php
print_r($accounts);
I take a look at some demos of Google App Engine Java using Servlet and JSP. What they're doing is this:
// In AccountsServlet.java
public class AccountsServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String action = req.getParameter("accountid");
// do something
// REDIRECT to an JSP page, manually passing QUERYSTRING along.
resp.sendRedirect("/namedcounter.jsp?name=" + req.getParameter("name"));
}
}
Basically in the Java case it's 2 different HTTP requests (the second one being automatically forced), right? So in JSP file I can't make use of the data calculated in the Servlet.
Is there some way I can do it similar to the PHP way?
You will need to set the data retrieved in the servlet in request scope so that the data is available in JSP
You will have following line in your servlets.
List<Account> accounts = getAccounts();
request.setAttribute("accountList",accounts);
Then in JSP you can access this data using the expression language like below
${accountList}
I would use request dispatches instead of the sendRedirect as follows
RequestDispatcher rd = sc.getRequestDispatcher(url);
rd.forward(req, res);
If you can use RequestDispatcher then you can store these values in request or session object and get in other JSP.
Is there any specific purpose of using request.sendRedirect?. If not use RequestDispatcher.
See this link for more details.
public class AccountServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Account> accounts = getAccountListFromSomewhere();
String url="..."; //relative url for display jsp page
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(url);
request.setAttribute("accountList", accounts );
rd.forward(request, response);
}
}
What you want to do is first define an object to represent the information from getAccounts() - something like AccountBean.
Then in your servlets doPost or doGet function, use the request info to populate your AccountBean object.
You can then store the AccountBean object either in the request, session, or servlet context by using the setAttribute method, and forward the request to the JSP page.
The AccountBean data in your jsp page is extracted using the and tags.
Here might be an example of your servlet:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
// get data from request querystring
String accountId = req.getParameter("accountid");
// populate your object with it (you might want to check it's not null)
AccountBean accountBean = new AccountBean(accountId);
// store data in session
HttpSession session = req.getSession();
session.setAttribute("accountBean", accountBean);
// forward the request (not redirect)
RequestDispatcher dispatcher = req.getRequestDispatcher("account.jsp");
dispatcher.forward(req, resp);
}
Then your JSP page would have the following to display the account information:
<jsp:useBean id="accountBean" type="myBeans.AccountBean" />
Your account is <jsp:getProperty name="accountBean" property="status" />
Besides what's mentioned above about using expression lang, you can also pass attributes via request itself. In Servlet's doGet(), we write something like:
Account[] accounts = AccountManager.getAccountList();
request.setAttribute("accountList", accounts );
RequestDispatcher rd = req.getRequestDispatcher(nextJSPurl);
rd.forward(req, resp);
In JSP, we can retrieve the attribute from request:
<%
Account[] accounts= (Account[])request.getAttribute("accountList");
if (accounts.length>0) {
for (Account account: accounts) {
%>
<blockquote>account name: <%= account.getName() %></blockquote>
<%
}
}
%>
import javax.servlet.http.*;
public class AccountsServlet extends HttpServlet {
public void doGet (HttpServletRequest request, HttpServletResponse response) {
try {
// Set the attribute and Forward to hello.jsp
request.setAttribute ("somename", "someValue"); // to save your temporary calculations.
getServletConfig().getServletContext().getRequestDispatcher("/namedcounter.jsp?name=" + req.getParameter("name")).forward(request, response);
} catch (Exception ex) {
ex.printStackTrace ();
}
}
}
In the above code servlet will not create 2 different requests. It will forward, also will retain all data from original request.
request.setAttribute ("somename", "someValue"); // to save your temporary calculations.
This is my understanding of your question - you want to redirect or dispatch to a new JSP page along with the data calculated in Servlet, right? To do so you need to set request attributes before dispatching the request.
You can set attributes using HttpServletRequest object (req.setAttribute("attribute name", "attribute value")). Attribute value can be any Java object.
You can retrieve the value by req.getAttribute("attribute name"). You'll also need to type cast the object while user getAttribute() function.
You can set the data inside java beans and easily access that data onto jsp page when control goes to jsp. set the date in java beans using setters get access those data onto jsp page by including that bean into jsp.
<%#page contentType="text/html"%>
<jsp:useBean id="man" class="beans.Person"/>
<jsp:setProperty name="man" property="*"/>
First Name: <jsp:getProperty name="man" property="firstName"/>
like this you can access as many properties your bean class can have.

Java servlet not receiving request attributes [duplicate]

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");

How to get page name from WebSphere Portal page?

I am creating a portlet for WebSphere portal 8 and would like to retrieve the page name where my portlet is rendered. This is important because depending on the page, the portlet will server content differently
I've tried to use the NavigationSelectionModel API but do not think I'm using it correctly. I want this code to happen before the view is rendered and I put the code in the doView method. The problem is that I cannot cast a ServletRequest/Response because I only have the RenderRequest and RenderResponse available in the doView method.
public void doView(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
// Declarations
List<ForeignAuthority> faList = new ArrayList<ForeignAuthority>();
String resp;
// Set the MIME type for the render response
response.setContentType(request.getResponseContentType());
// Check if portlet session exists
ForeignAuthoritiesPortletSessionBean sessionBean = getSessionBean(request);
if (sessionBean == null) {
response.getWriter().println("<b>NO PORTLET SESSION YET</b>");
return;
}
try{
Context ctx = new InitialContext();
NavigationSelectionModelHome home = (NavigationSelectionModelHome)
ctx.lookup("portal:service/model/NavigationSelectionModel");
if (home != null) {
NavigationSelectionModelProvider provider =
home.getNavigationSelectionModelProvider();
NavigationSelectionModel model =
provider.getNavigationSelectionModel((ServletRequest)request, (ServletResponse)response);
for (java.util.Iterator i = model.iterator(); i.hasNext(); )
{
NavigationNode node = (NavigationNode) i.next();
if (i.hasNext()) {
System.out.println(node.getObjectID().getUniqueName());
}
}
}
}catch(Exception e){
e.printStackTrace();
}
PortletRequestDispatcher rd = getPortletContext()
.getRequestDispatcher(getJspFilePath(request, VIEW_JSP));
rd.include(request, response);
}
The expected result would be to retrieve the page name or unique name of the current page that the portlet is rendered on.
You can try whether the below code snippet helps. You can get the URI value and extract the page name from it.
HttpServletRequest httpServletRequest = PortletUtils.getHttpServletRequest(renderRequest);
httpServletRequest.getRequestURI();

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.

Pass java arraylist to jsp through servlet and create field on the basis of size of arrayList

**=========================== MY JAVA FUNCTION RETURNS AN ARRAYLIST============
public ArrayList<Class1> getDetails(String id, String year) {
ArrayList<Class1> arraylist1 = new ArrayList<Class1>();
return arraylist1;
}
============================== SERVLET CODE =================================
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try{
String operation=request.getParameter("operation");
log.debug("Operation : "+operation);
Class1 obj1 = new Class1();
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
if(operation.equals("getDetails")){
ArrayList<Class1> record1 = new ArrayList<Class1>();
String id = request.getParameter("id_code");
String year = request.getParameter("fin_yr");
if(id != null) {
record1 = obj.geDetails(id, year);
}
out.print(record1);
}
} catch(Exception e){
log.error("Exception : "+ e.toString());
}
}
======================JSP CODE=====================================
if($('idCode').val() != ""){
$('#IdCode').focus(function(){
var fYear = $('#txtYear :selected').attr('label');
htmlObj = $.ajax({
type: "GET",
url: "Servlet1",
data: "operation=getDetails&id_code="+ $('#IdCode').val() + "&fin_yr="+ fYear,
async: false,
contentType:"text/html; charset=utf-8",
dataType:"html",
success: function(result){
}
}
});
});
}**
In this above code i added dummy function that will return an arrayList after servlet calls that function. Now my question is how do i get arraylist into may jsp page.
I got arraylist properly upto servlet i have no idea how do i get it into my jsp page and designs controls as per the size of servlet returned by sevlet.
You did not add elements to your list. So even if you iterate over the list, there will be no elements inside. Basically you can iterate over the list on the jsp using java code between these: <% ... %>
But this is not best practice.
You can include your list to the response:
request.setAttribute("list", categoryList);
And at the jsp you can get it, and iterate over it:
<%
// retrieve your list from the request, with casting
ArrayList<Category> list = (ArrayList<Category>) request.getAttribute("list");
// print the information about every category of the list
for(Category category : list) {
out.println(category.getId());
out.println(category.getName());
out.println(category.getMainCategoryId());
}
%>
Please look at this answer: Passing ArrayList from servlet to JSP

Categories

Resources