NullPointerException while retrieving data from the database - java

When I am trying to retrieve data from database it's showing NullPointerException.
Here is my servlet code:
public class displayData extends HttpServlet {
String query;
Connection conn;
Statement st;
ResultSet res;
ConnectionManager dbconn;
List lst= new ArrayList();
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
dbconn= new ConnectionManager();
conn=dbconn.getConnection();
st=conn.createStatement();
query="select * from reg";
res=dbconn.getResultSet(query, conn);
System.out.println(res);
while(res.next())
{
lst.add(res.getString("uname"));
lst.add(res.getString("password"));
}
res.close();
}catch(Exception e)
{
RequestDispatcher rd= request.getRequestDispatcher("/error.jsp");
rd.forward(request, response);
}
finally
{
request.setAttribute("EmpData", lst);
response.sendRedirect("/success.jsp");
RequestDispatcher rd= request.getRequestDispatcher("/success.jsp");
rd.forward(request, response);
lst.clear();
out.close();
}
}
And Here is JSP Code for Retrieving Data from database using above servlet Code:
<body>
<h1>Employee List</h1>
<% Iterator itr;%>
<% List data = (List) request.getAttribute("EmpData");
for(itr=data.iterator(); itr.hasNext();)
{
%>
<tr>
<% String s= (String) itr.next();%>
<td><%=s%></td>
<td><%=itr.next()%></td>
<td><input type="submit" value="Edit" onclick="editRecord(<%=s%>;)"</td>
<td><input type="submit" value="Delete" onclick="deleteRecord(<%=s%>;)"</td>
<%}%>
</tr>
</body>
Please help me for solving this problem.

After seeing your Servlet code I found multiple issues,Lets go one by one
I am not sure whether you defined your servlet as a servlet or not.
Either do mapping in web.xml or add annotation like this
#WebServlet("/displayData") public class displayData extends
HttpServlet {
In the servlet you don't have doGet and doPost method. So your
method processRequest will not be invoked by the container. either
put doGet and call your service method or rename your service method
to doGet. Reference - Is it mandatory to have a doGet or doPost method?
The disaster you done in try catch finally block. finally will be always called so there is no use writing the redirection code there as it will executed after catch also. In addition to that finally blocks first four lines are causing serious issues. You should not call both sendRedirect and forward one followed by another. Either do sendRedirect or do forward but not both at the same time.
You will get this exception illegalstateexception-cannot-forward-after-response-has-been-committed Reference - java.lang.IllegalStateException: Cannot forward after response has been committed
What to do forward or sendRedirect at last, In this case you have to
use forward as its a server side action. Reference -
Request Attributes not available in jsp page when using sendRedirect from a servlet
Based on your path of jsp do forward. if your success and error
jsp's are directly under Webcontent then do like this
request.getRequestDispatcher("success.jsp");
Change these things and try again if not working let me know

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.

Sending data from servlet to jsp? [duplicate]

This question already has answers here:
Generate an HTML Response in a Java Servlet
(3 answers)
Closed 2 years ago.
I have a form in a jsp from which i am retrieving data to servlet via doPost method, suppose username and password now there is an empty textarea field inside the same form where i want to send the username from servlet,how do i do it?
I don't really understand your case. But there're 2 common ways to send data from servlet to JSP:
Request attributes: you can use this if data is transferred along a same request.
request.setAttribute("username",obj);
request.getRequestDispatcher("url").forward(request,response);
In JSP:
<div>${username}</div>
Session attribute: use this to retain data during a session
Session session = request.getSession(true); //true: create session if not existed
session.setAttribute("username",obj);
response.sendRedirect("url"); //or use request dispatcher to forward the request
In JSP:
<div>${username}</div>
Write your Servlet class like this
public class ServletToJSP extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//communicating a simple String message.
String message = "Example source code of Servlet to JSP communication.";
request.setAttribute("message", message);
//Servlet JSP communication
RequestDispatcher reqDispatcher = getServletConfig().getServletContext().getRequestDispatcher("jsp url");
reqDispatcher.forward(request,response);
}
}
jsp page
<%
String message = (String) request.getAttribute("message");
out.println("Servlet communicated message to JSP "+ message);
%>

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.

How to save parameters and clear the url?

My aim is to provide the ability to sending comments or reviews on the site. When I get the parameter from the form they are properly added to my reviews database. But the problem is that the URL contains the paramaters. So when I fill the form and press the submit button, there are a new record in the database, but the comment is not shown on the page at once. Also when I refresh the page, the same record is duplicated in the database. I want user to fill the forms, press the button and then redirect to the same page with his comment or review. Here is my servlet doGet method code:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Query query = new Query();
Object allReviews = query.getAllReviews();
request.setAttribute("allReviews", allReviews);
RequestDispatcher rd = request.getRequestDispatcher("reviews.jsp");
rd.forward(request, response);
if (request.getParameter("sendReviewButton") != null){
String userName = request.getParameter("reviewName");
String eMail = request.getParameter("reviewMail");
String reviewList = request.getParameter("reviewText");
query.addReview(userName, eMail, reviewList);
}
}
And my form in jsp:
<form action = "${pageContext.request.contextPath}/Reviews" method="get">
<p>Your name: <input type="text" size="107" name="reviewName" required></p>
<p>Your e-mail: <input type="text" size="90" name="reviewMail" required></p>
<p>Your review:</p>
<p><textarea rows="15" cols="135" name="reviewText" ></textarea></p>
<input type="submit" value="Send" name="sendReviewButton" class="btn btn-primary btn-lg" id="send-btn">
</form>
you should probably use POST and not GET, so that the data is not seen on the URL and the browser warns the user if she reloads the page
Add the new review before you get the list of reviews, so you get the updated list
use sendRedirect to the reviews.jsp page so that the url is the short one. This should render point 2 moot as you're going to list the review after you've added the new one.
I added the else statement. So the new review is correctly added, it is shown on the page immediately. When I refresh the page the record in the database is NOT duplicated:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Query query = new Query();
if (request.getParameter("sendReviewButton") != null){
String userName = request.getParameter("reviewName");
String eMail = request.getParameter("reviewMail");
String reviewList = request.getParameter("reviewText");
query.addReview(userName, eMail, reviewList);
Object allReviews = query.getAllReviews();
request.setAttribute("allReviews", allReviews);
response.sendRedirect("/ScopeSoftware/Reviews");
}else {
Object allReviews = query.getAllReviews();
request.setAttribute("allReviews", allReviews);
RequestDispatcher rd = request.getRequestDispatcher("reviews.jsp");
rd.forward(request, response);
}
}
You are forwarding to the JSP page, but this does not solve the refresh problem. The solution is - as you already said in your question - to redirect to the JSP:
response.sendRedirect("reviews.jsp"); // url of the JSP page.
This sends a HTTP redirect back to the browser and the browser then does a new GET to reviews.jsp.

Servlet-Servlet-Jsp redirecting

I'm developing an application in JAVA where a servlet is taking the inputs from a JSP page. After inserting the values in db it will redirect to another servlet. Then the 2nd servlet will dispatch a JSP page with an ArrayList. But I can't redirect from the 2nd servlet to the JSP page. The ArrayList is going to the JSP page but the page is not showing anything. I'm using NetBeans 6.8.
I'll be thankful if anyone can solve this problem.
Code for 1st Servlet:
RequestDispatcher dispatcher = request.getRequestDispatcher("/Servlet1?id="+id);
dispatcher.forward(request, response);
Code for 2nd Servlet:
request.setAttribute("list",list);
String url="test2.jsp";
RequestDispatcher v=request.getRequestDispatcher(""+url+"");
v.forward(request, response);
try this on 2nd servlet ..
request.setAttribute("list",list);
String url="test2.jsp";
RequestDispatcher v=request.getRequestDispatcher(url);
v.forward(request, response);
On jsp page ...
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title></title>
</head>
<body>
<c:forEach items="${list}" var="item">
${item}<br>
</c:forEach>
</body>
</html>
public class MySqlConnection {
Connection c;
public Connection getConnection() throws ClassNotFoundException, SQLException {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String dbName = "ignite292";
String user = "root";
String password = "root";
Class.forName(driver); // You don't need to call it EVERYTIME btw. Once during application's startup is more than enough.
c = (Connection) DriverManager.getConnection(url + dbName, user, password);
return c;
}
public void closeConnection() {
try {
if (!c.isClosed()) {
c.close();
}
} catch (Exception e) {
}
}
}
First things, If you are using any redirect mechanism, It should not be in RequestScope. It must be in Session or Context Scope(Based on your Requirement). So , the resultant code for 2nd Servlet may as follow
request.getSession().setAttribute("list",list);
String url="/test2.jsp";
RequestDispatcher v=request.getRequestDispatcher(""+url+"");
v.forward(request, response);
Try with this Code.
Sankha,
You can add those objects into session object. and you can use that session obj in any jsp and servlet.
suppose you have an arrayList Obj which have some data objects. and you are trying redirecting your servlet to jsp OR servlet to servlet.
eg:-
RequestDispatcher dispatcher = request.getRequestDispatcher("/Servlet1?id="+id);
dispatcher.forward(request, response);
request.setAttribute("list",list); // **Insted of using request object use session implicit object**.
String url="test2.jsp";
RequestDispatcher v=request.getRequestDispatcher(""+url+"");
v.forward(request, response);
Please refer below code to sort out your problem.
RequestDispatcher dispatcher = request.getRequestDispatcher("/Servlet1?id="+id);
dispatcher.forward(request, response);
**session.setAttribute("list",list);**
String url="test2.jsp";
RequestDispatcher v=request.getRequestDispatcher(""+url+"");
v.forward(request, response);
And get this list object by using
List dataList = session.getAttribute("list");
Hope this will help you.

Categories

Resources