I am beginning to learn servlet . I had issue try to get url from a folder(outside my project) which contains many images but i don't know how to display them in jsp (GrassFish Server). i try with some code but it don't working correctly .Simply outputting to HTML does not seem to work.
I've not performed any manual servlet mapping and I haven't changed any of Tomcat's configuration files.
this is my servlet
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author tamgi
*/
public class getServlets extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
File file = new File("C:\\Users\\tamgi\\Downloads\\Source\\Kyou No Cerberus\\Chap_56");
File[] files = file.listFiles();
request.setAttribute("files", files);
request.getRequestDispatcher("Test.jsp").forward(request, response);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
this is my jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Page</title>
<% File[] files =(File[]) request.getAttribute("files"); %>
</head>
<body>
<br>
<% for(File f : files) { %>
<img src="<%= f.getCanonicalPath() %> " alt="empty">
<br>
<% } %>
</body>
</html>
Related
the java web client.
this is 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>Calcular factorial</title>
</head>
<body>
<div align="center">
<form action="calcular.do" style="font-family:arial">
Numero :<br>
<input type="text" name="base" style="text-align:right"/><br><br>
<input type="submit" value="calcular" name="Calcular" />
<br><br>
Resultado:<br>
<input type="text" name="resultado" value="${result}"
style="text-align:right"/><br><br>
</form>
</div>
</body>
</html>
this is the Calcular.java
package controlador;
import Webservicce.ClientRest;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author x2010s
*/
#WebServlet(name = "Calcular", urlPatterns = {"/calcular.do"})
public class Calcular extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ClientRest rest = new ClientRest();
String base = request.getParameter("base");
String factorial = rest.factorial(base);
request.setAttribute("factorial",factorial);
request.getRequestDispatcher("index.jsp").forward(request, response);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
in the servlet, the factorial method must be called from the restful, to calculate the factorial with the entered number
this is the imported RESTful Java Client
package Webservicce;
import javax.ws.rs.ClientErrorException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.WebTarget;
public class ClientRest {
private WebTarget webTarget;
private Client client;
private static final String BASE_URI = "http://localhost:8080/SimpleRESTweb/webresources";
public ClientRest() {
client = javax.ws.rs.client.ClientBuilder.newClient();
webTarget = client.target(BASE_URI).path("factorial");
}
public String factorial(String base) throws ClientErrorException {
WebTarget resource = webTarget;
if (base != null) {
resource = resource.queryParam("base", base);
}
return resource.request().get(String.class);
}
public void close() {
client.close();
}
}
When I enter the number and click on calculate it appears
HTTP Status 500 - Internal Server Error
type Exception report
message Internal Server Error
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.ws.rs.NotFoundException: HTTP 404 Not Found
errors appear in the java web client. I can not find the error, because it does not calculate the factorial
I'm working on one web app. I have problem when I want to test my servlet.
When I run my servlet error pops up -
HTTP Status 404 - Not Found.
I search another similar problems but i can't find solution. I think that there is no connection between my servlet and jsp file. Below my code:
GetServletController
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author Adam
*/
public class GetServletController extends HttpServlet {
// private HandsDBUtil handsDBUtil;
//
// private ServletConfig config = getServletConfig();
// private ServletContext context = config.getServletContext();
//
// private String user = null;
// private String pass = null;
// private String c_name = null;
// private String url = null;
// #Override
// public void init() throws ServletException {
// super.init();
// Enumeration enumeration = context.getInitParameterNames();
// while (enumeration.hasMoreElements()) {
// String name = (String) enumeration.nextElement();
// switch (name) {
// case "url":
// url = context.getInitParameter(name);
// break;
// case "pass":
// pass = context.getInitParameter(name);
// break;
// case "user":
// user = context.getInitParameter(name);
// break;
// case "c_name":
// c_name = context.getInitParameter(name);
// break;
// }
// }
//
// handsDBUtil = new HandsDBUtil(user, pass, c_name, url);
//
// }
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain; charset=ISO-8859-2");
PrintWriter out = response.getWriter();
out.println("WOW");
HandsDBUtil handsDBUtil;
ServletConfig config = getServletConfig();
ServletContext context = config.getServletContext();
String user = null;
String pass = null;
String c_name = null;
String url = null;
Enumeration enumeration = context.getInitParameterNames();
while (enumeration.hasMoreElements()) {
String name = (String) enumeration.nextElement();
switch (name) {
case "url":
url = context.getInitParameter(name);
break;
case "pass":
pass = context.getInitParameter(name);
break;
case "user":
user = context.getInitParameter(name);
break;
case "c_name":
c_name = context.getInitParameter(name);
break;
}
}
handsDBUtil = new HandsDBUtil(user, pass, c_name, url);
out.println("wow");
out.println(user);
try {
//listHands(request, response);
List<Hand> hands = handsDBUtil.getHands();
System.out.println(hands);
request.setAttribute("HAND_LIST", hands);
RequestDispatcher dispatcher = request.getRequestDispatcher("getHands");
dispatcher.forward(request, response);
} catch (Exception ex) {
throw new ServletException(ex);
}
}
// private void listHands(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, Exception {
//
// List<Hand> hands = handsDBUtil.getHands();
//
// request.setAttribute("HAND_LIST", hands);
//
// RequestDispatcher dispatcher = request.getRequestDispatcher("getHands");
// dispatcher.forward(request, response);
//
// }
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
jsp
<%#page import="java.util.*, Servlets.GetServletController, Servlets.Hand" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Poker Hands List</title>
</head>
<form action="GetServletController"/>
<%
List<Hand> theHands = (List<Hand>) request.getAttribute("HAND_LIST");
%>
<body>
<%= theHands %>
<div id="wrapper">
<div id="header">
<h2>
Poker Hands List
</h2>
</div>
</div>
<div id="container">
<div id="content">
</div>
</div>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<context-param>
<param-name>url</param-name>
<param-value>jdbc:derby://localhost:1527/lab</param-value>
</context-param>
<context-param>
<param-name>c_name</param-name>
<param-value>org.apache.derby.jdbc.ClientDriver</param-value>
</context-param>
<context-param>
<param-name>user</param-name>
<param-value>lab</param-value>
</context-param>
<context-param>
<param-name>pass</param-name>
<param-value>lab</param-value>
</context-param>
<servlet>
<servlet-name>ServletTest</servlet-name>
<servlet-class>Servlets.ServletTest</servlet-class>
</servlet>
<servlet>
<servlet-name>GetServletController</servlet-name>
<servlet-class>Servlets.GetServletController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletTest</servlet-name>
<url-pattern>/ServletTest</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>GetServletController</servlet-name>
<url-pattern>/GetServletController</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>getHands.jsp</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>mainMenu.jsp</welcome-file>
</welcome-file-list>
</web-app>
Request dispatcher is used to dispatch request to any resources,such as HTML, Image, JSP, Servlet on the server. If you want to forward your request to a jsp you need to define like below
RequestDispatcher dispatcher = request.getRequestDispatcher("getHands.jsp");
In your case you are forwarding the request to a servlet.
RequestDispatcher dispatcher = request.getRequestDispatcher("getHands");
There is no such servlet defined in your web.xml
That's why you are getting 404 error
This question already has answers here:
How to retrieve and display images from a database in a JSP page?
(6 answers)
Closed 6 years ago.
I would like to my JSP page:
<%#page contentType="text/html" pageEncoding="windows-1250"%>
<%#page import="java.util.Random"%>
<%#page import = "java.util.*" session="true"%>
<!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=windows-
1250">
<title>JSP Page</title>
</head>
<body>
<%
String text = "text";
%>
<jsp:include page="header.jsp">
<jsp:param name="test" value="<%=text%>"/>
</jsp:include>
</body>
</html>
invoked header.jsp with the parameter "test" aroused:
<%#page contentType="text/html" pageEncoding="windows-1250"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<table bgcolor="#aaaaaa">
<tr>
<td>
<h1>Image:
<br>
<jsp:include page="/ServletExample"/>
</h1>
</td>
</tr>
</table>
and this invoked a servlet :
#WebServlet(name = "ServletExample", urlPatterns = {"/ServletExample"})
public class ServletExample extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
BufferedImage graph = new BufferedImage(500, 500, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D) graph.getGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.ORANGE);
String text = request.getParameter("test")== null ? "no text" : request.getParameter("text");
g2d.drawString(text, 100, 100);
OutputStream out;
response.setContentType("image/png");
try {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ImageIO.write(graph, "PNG", buffer);
response.setContentLength(buffer.size());
out = response.getOutputStream();
out.write(buffer.toByteArray());
} catch (Exception ex) {
throw new ServletException(ex);
}
out.close();
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
but in line "out = response.getOutputStream();" throw exception:
Warning: Servlet.service() for servlet jsp threw exception
java.lang.IllegalStateException
at org.apache.jasper.runtime.ServletResponseWrapperInclude.getOutputStream(ServletResponseWrapperInclude.java:124)
at example.ServletExample.processRequest(ServletExample.java:59)
at example.ServletExample.doGet(ServletExample.java:79)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.ApplicationDispatcher.doInvoke(ApplicationDispatcher.java:875)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:739)
at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:695)
I tried to set the flush () but it does not work. You met a similar problem?
text will be test there.
String text = request.getParameter("test")== null ? "no text" : request.getParameter("test");
I have a HTML page where new users are added to the Database,I have done MS-Access connection through JDBC-ODBC and Servlets.I have no errors but the values aren't getting saved in the Database.
*******HTML FILE*****
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div>
<center><h1>login page</h1></center>
<form action="Serve" method="get">
Username: <input type="text" name="username"><br>
Password: <input type="text" name="password"><br>
<button> Login</button>
</form>
</div>
</body>
</html>
***JDBC-ODBC FILE****
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class base {
Connection con;
Statement st;
ResultSet rs;
String s;
public base() throws SQLException {
connect();
}
private void connect() throws SQLException {
try {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con =DriverManager.getConnection("jdbc:odbc:db","","");
st=con.createStatement();
} catch (ClassNotFoundException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
}
*****SERVLETS***
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;
#WebServlet(name = "Serve", urlPatterns = {"/Serve"})
public class Serve extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
base s = new base();
s.s="insert into Table1 values("+request.getParameter("name")+","+request.getParameter("pass")+")";
s.st.executeQuery(s.s);
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
The problem is that you get the wrong parameters from the request Object.
Try this:
s.s="insert into Table1 values("+request.getParameter("username")+","+request.getParameter("password")+")";
I am having a problem with request attributes in my jsp, I am using the mvc pattern and setting a request attribute and forwarding to a jsp from the servlet. The application is a banking application, the goal is to use the customer id to get the customer by customer id pass it to the Account class to collect all of the accounts of the user. I have this problem solved I can get the account information and process it without any issue. The problem I am having is when I close the page and run again from the beginning I find that when I get to the table it is still putting in the information from the previous request as well as the new information that I am requesting. Like So:
()
My code is as follows for the servlet that directs me to the jsp and the jsp that I use the information into.
AccountServlet.java:
package com.ChattBank.controller;
import com.ChattBank.business.Account;
import com.ChattBank.business.Accounts;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* #author AARONS
*/
public class AccountServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet AccountServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet AccountServlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//HttpSession session = request.getSession();
String action = request.getParameter("action");
if (action == null) {
request.getRequestDispatcher("/Welcome.jsp").forward(request, response);
} else if (action.equals("view")) {
Accounts acct = new Accounts();
ArrayList<Account> list = new ArrayList();
try {
acct.setCustAccounts(request.getParameter("id"));
list.addAll(acct.getCustAccounts());
System.out.println(request.getParameter("id"));
} catch (SQLException ex) {
Logger.getLogger(Accounts.class.getName()).log(Level.SEVERE, null, ex);
}
request.setAttribute("acctList", list);
request.getServletContext().getRequestDispatcher("/accounts.jsp").forward(request, response);
}
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("action");
String custId = request.getParameter("custID");
if (action == null) {
request.getRequestDispatcher("/Welcome.jsp").forward(request, response);
}
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
accounts.jsp:
<%--
Document : accounts
Created on : Jun 25, 2014, 12:24:38 AM
Author : Richard Davy
--%>
<%#page import="java.util.ArrayList"%>
<%#page import="com.ChattBank.business.Account"%>
<%#page import="com.ChattBank.business.Accounts"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Your Accounts</title>
</head>
<body>
<%
ArrayList<Account> list = new ArrayList();
list.addAll((ArrayList)request.getAttribute("acctList"));
for (Account custAccount : list) {
System.out.println("From JSP: " + custAccount.getCustId() + " " + custAccount.getAcctNo() + " " + custAccount.getAcctType() + " " + custAccount.getBalance());
System.out.println("Getting Object From Section");
}
%>
<h1>You Made It Here!</h1>
<table border="1" width="2" cellspacing="5" cellpadding="2">
<thead>
<tr>
<th colspan="10">Your Chatt Accounts</th>
</tr>
</thead>
<tbody>
<% for (int i = 0; i < list.size(); i++){ %>
<tr>
<td colspan="2">Account: </td>
<td colspan="2"><%= list.get(i).getCustId() %></td>
<td colspan="2"><%= list.get(i).getAcctNo() %></td>
<td colspan="2"><%= list.get(i).getAcctType() %></td>
<td colspan="2"><%= list.get(i).getBalance() %></td>
</tr>
<% } %>
<% list.clear(); %>
</tbody>
</table>
<p>Thank you for your business!</p>
</body>
</html>
I am not really sure what is going on I started with session attributes and thought that was my issue, so I turned to using request attributes. But I am still facing the same issue. I was under the impression that the request attribute only lasted per that request but it seems that the information is still being carried through. Any suggestions?
The funny thing about this issue is that it wasn't anything to do with the request attribute variables. Since I was instantiating a list of objects in a class that list of objects was persisting and just being added to. I think this is mostly because I was using an ArrayList which is able to be appended to. Instead of re-writing the entire class to figure out some work around I included a try{}finally{} statement like so:
package com.ChattBank.controller;
import com.ChattBank.business.Account;
import com.ChattBank.business.Accounts;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* #author AARONS
*/
public class AccountServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet AccountServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet AccountServlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//HttpSession session = request.getSession();
String action = request.getParameter("action");
if (action == null) {
request.getRequestDispatcher("/Welcome.jsp").forward(request, response);
} else if (action.equals("view")) {
Accounts acct = new Accounts();
ArrayList<Account> list = new ArrayList();
try {
acct.setCustAccounts(request.getParameter("id"));
list.addAll(acct.getCustAccounts());
System.out.println(request.getParameter("id"));
//This was moved into the try block itself
request.setAttribute("acctList", list);
request.getServletContext().getRequestDispatcher("/accounts.jsp").forward(request, response);
} catch (SQLException ex) {
Logger.getLogger(Accounts.class.getName()).log(Level.SEVERE, null, ex);
//This is the added finally statement with the clearAccounts method
} finally {
acct.clearAccounts();
}
}
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("action");
String custId = request.getParameter("custID");
if (action == null) {
request.getRequestDispatcher("/Welcome.jsp").forward(request, response);
}
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
The clear accounts method in the Accounts class was very very simple:
/**
* Clears the current array list of accounts
*/
public void clearAccounts(){
this.custAccounts.clear();
}