JSTL - iterating through array of random integers - not displaying in webPage - java

I'm trying to iterate through myList (array) of random generated integers using JSP/JSTL.
My code snipet which generates and stores integers, is located in my servlet.
On the other hand,iterating through an arrayList of Strings (see code below) works perfectly but when i try it with arrays based on the same logic, my webpage just doesnt show any unordered list of my random integers.
thank you for helping me out
My Servlet
package be.intec.servlets;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.RequestDispatcher;
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 be.intecbrussel.entities.Auto;
#WebServlet("/JSTLServlet")
public class JSTLServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String VIEW = "WEB-INF/JSP/JSTL.jsp";
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher dispatcher = request.getRequestDispatcher(VIEW);
//=======below is the code using Array=====================================
int[] myList = new int[42];
for (int i = 0; i < myList.length; i++) {
myList[i] = (int) (Math.random() * 100);
}
request.setAttribute("mylist", myList);
//=======below is the code using ArrayList=====================================
List<String> names = Arrays.asList("John", "Georges", "Kevin");
request.setAttribute("names", names);
dispatcher.forward(request, response);
}
}
My jstl.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" session="false"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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=ISO-8859-1">
<link rel="stylesheet" type="text/css" href="styles/default.css">
<title>JSTL Expample</title>
</head>
<body>
<h2>Iterate through my array</h2>
<ul>
<c:forEach var="arrayVar" items="${myList}">
<li>${arrayVar}</li>
</c:forEach>
</ul>
<!-- ================================================================================ -->
<h2>Iterate through my arrayList</h2>
<ul>
<c:forEach var="name" items="${names}">
<li>${name}</li>
</c:forEach>
</ul>
</body>
</html>
my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>ServletsAndJSPExampleProject</display-name>
<welcome-file-list>
<welcome-file>IndexServlet</welcome-file>
</welcome-file-list>
</web-app>
my index Servlet
package be.intec.servlets;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/IndexServlet")
public class IndexServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String VIEW = "/WEB-INF/JSP/index.jsp";
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher dispatcher = request.getRequestDispatcher(VIEW);
dispatcher.forward(request, response);
}
}
Output in Browser is :
Iterate through my array:
// here it should be showing my random numbers
Iterate through my arrayList:
// work very well
John
Georges
Kevin

You've used "mylist" as name in your Servlet, and want to fetch the list using ${myList}. The name is case-sensitive!

Change your for each as shown below:
<c:forEach var="arrayVar" items="${mylist}">
<li>${arrayVar}</li>
</c:forEach>

Related

<c:out> tag is not showing up in JSP nor does it work

Somehow, the <c:out> tag is not working at all. It doesn't show any alerts and it's just blank. It's like I never added the tag into the file. Here's my code:
Connector.java:
package connect;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.servlet.ServletContext;
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.servlet.http.HttpSession;
import products.Product;
/**
* Servlet implementation class Connector
*/
#WebServlet("/Connector")
public class Connector extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Connector() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
#SuppressWarnings({ "unchecked", "null", "unused" })
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://\\\\.\\pipe\\MSSQL$SQLEXPRESS\\sql\\query:8888;databaseName=ShoppingDB";
Connection con = DriverManager.getConnection(url,"sa","33887899");
Statement stmt = con.createStatement();
ArrayList<Product> pro=new ArrayList<Product>();
ResultSet rs=stmt.executeQuery("select * from Products");
Product p = new Product();
while(rs.next()) {
p.setId(rs.getInt("product_id"));
p.setName(rs.getString("product_name"));
p.setDes(rs.getString("product_des"));
p.setPrice(rs.getInt("product_price"));
p.setSrc(rs.getString("product_img_source"));
p.setType(rs.getString("product_type"));
p.setBrand(rs.getString("product_brand"));
p.setAmount(1000);
pro.add(p);
}
Product re;
String name=request.getParameter("search");
for(int i =0;i<pro.size();i++) {
if(pro.get(i).getName()==name) {
re=pro.get(i);
break;
}
}
p=pro.get(0);
ServletContext context=getServletContext();
context.setAttribute("p", p);
}catch(Exception e) {
out.println(e);
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
Home.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" href="Style.css">
</head>
<body style="background-color:#f5f5f5;">
<h1 style="text-align:center">PRJ321X_202x</h1>
<div id="nav">
<button class="navbtn">Home</button>
<button class="navbtn">Products</button>
<button class="navbtn">About Us</button>
<button class="navbtn" style="float:right;" onclick="location.href='Login.jsp'">Log in</button>
<form style="float:right;" method="Post" action="Connector">
<input name="search" id="search" type="text" placeholder="Search..">
<input type="submit" style="display:none">
</form>
</div>
<script src="Script.js"></script>
<div style="float:left;width:75%;margin-right:5px;" id="products">
<div>
<c:out value="${p.id}"/>
</div>
</div>
<div style="float:left;width:24%">
<div style="background-color:white;width:100%">
<h3>Shopping cart</h3>
<div style="height:2.5cm;background-color:#8f8d8d;width:100%">Your cart is currently empty</div>
</div>
<div style="background-color:white;width:100%">
<h4>Popular products or banner</h4>
<p>Iphone 11 Pro Max</p>
<img src="11PM.jpg" style="width:50%">
<p>Iphone 12 Pro Max</p>
<img src="12PM.jpg" style="width:50%">
<p>Samsung Galaxy S20</p>
<img src="S20.jpg" style="width:50%">
</div>
</div>
</body>
</html>
In your servlet you are doing
context.setAttribute("p", p);
But in your JSP you are doing:
<c:out value="${s.id}"/>
Obviously, your names must match and the tag should be:
<c:out value="${p.id}"/>
One other thing I notice is that you are not dispatching to the JSP. You need to do a requestDispatcher.forward() to your JSP
Here is the minimum example to make everything work:
Servlet:
package connect;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
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 products.Product;
#WebServlet("/Connector")
public class Connector extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Product p = new Product();
p.setId(1234);
ServletContext context = getServletContext();
context.setAttribute("p", p);
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/Home.jsp"); // <--- your path here
requestDispatcher.forward(request, response);
}
}
If your Home.jsp file is on some other path, change above accordingly.
Home.jsp:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:out value="${p.id}" />
With that being said, a few comments on your controller code.
First of all, don't use #SuppressWarnings unless you know what you are doing. Based on your code, you are at a beginner level, so this annotation can hide a lot of issues that you should pay attention to.
You use an output stream PrintWriter out = response.getWriter(); in your code, but only to write a exception message into it when your code fails. If your code works, not only that you don't use your JSP, but you also don't use this out object to write a response to send to the client. So in regards with generating a response, your servlet did nothing, that's why nothing was displayed.
If you are doing a search for a product, you can write a WHERE clause and retrieve only what you are searching for instead of getting all the products in the database and then looping through them. Make sure you use prepared statement parameters when building your query. DO NOT CONCATENATE STRING TO BUILD YOUR SQL QUERY. That can cause SQL injection vulnerabilities.
You are looping through a list of product results but you are declaring your product object outside of the while loop. The result of this is that your array will only be filled with this reference object, that will point to objects that have the last retrieved value from the database. You need to move the product creation inside the while loop, like this:
while (rs.next()) {
Product p = new Product();
p.setId(rs.getInt("product_id"));
// all the other props
pro.add(p);
}
You are using the Product re; reference to search for your product, but then you never use it because you do a p=pro.get(0); to get the first product from your list and you use p to place in context for the JSP. I'me assuming you mean to use re instead.
Don't compare strings with ==. This code:
if (pro.get(i).getName() == name) {
should probably be something like:
if (pro.get(i).getName().equalsIgnoreCase(name)) {
Even more, you need to make sure you protect yourself from NullPointerExceptions in case getName() can also return null. If you used a WHERE SQL clause, you wouldn't need to loop again and search for products.
Finally, you should read some books or documentation on the concepts and code you are using. You might be able to put something together eventually, without fully understanding what's going on, but it might not necessarily be what you expect.

how i do when ihave this issue JSP Problem: HTTP 500 Internal Server Error Status when handling action?

I have searched the forums a lot for a solution to my problem but so far nothing. So I need your help!
Currently I am taking the Java EE course: "Develop websites with Java EE" on openclassrooms and arrived on JDBC I am blocked.
The principle consists of reading data in the database from the Java code and displaying them at the level of the JSP. But the display poses a problem at the JSP level. Thank you for your help! Here is my code for the JSP.
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>titre</title>
</head>
<body>
<h1>Bienvenue dans mon site</h1>
<ul>
<c:forEach var="utilisateur" items="${ utilisateurs }" >
<li><c:out value="${ utilisateurs.prenom }" /><c:out value="${ utilisateurs.nom }" /></li>
</c:forEach>
</ul>
</body>
</html>
import java.io.IOException;
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 sn.mballo.bdd.Personnes;
#WebServlet("/bonjour")
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
public Test() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Personnes tablePersonnes = new Personnes();
request.setAttribute("utilisateurs", tablePersonnes.recupererUtilisateurs());
this.getServletContext().getRequestDispatcher("/WEB-INF/bonjour.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

Cannot use forward method in java servlet

I just started learning servlet and got the following problem.
I need to use forward method in my servlet and show the result in other frame.
But nothing is shown. When I use include method, it's shown me the result.
How can I shown my result with forward method?
frame.jsp
<%# page import="StudyC.C18_HelloWeb"%>
<%# page language="java" contentType="text/html; charset=Windows-31J"
pageEncoding="Windows-31J"%>
<html>
<head>
<title>検索画面</title>
</head>
<FRAMESET ROWS ="20%,80%" >
<FRAME SRC ="C18_HelloINPUT.jsp" NORESIZE scrolling = yes>
<FRAME SRC ="C18_HelloOUTPUT.jsp" NORESIZE scrolling = no name = frameOutput>
</FRAMESET>
C18_HelloINPUT.jsp
<%# page language="java" contentType="text/html; charset=Windows-31J"
pageEncoding="Windows-31J"%>
<%# page import = "javax.servlet.RequestDispatcher" %>
<html>
<script>
function validateForm() {
var x = document.forms['myForm']['dataName'].value;
if (x == null || x.match(/^\s*$/)) {
alert('空です');
return false;
}
}
</script>
<style>
h1 {text-align:center;}
</style>
<h1>入力画面</h1><br>
<form name='myForm' action="C18_HelloWeb" method="get"
onsubmit='return validateForm()'target='frameOutput' >
<input type='text' name='dataName'>
<input type='submit' value='クエリ送信'>
</form>
C18_HelloOUTPUT.jsp
<%# page language="java" contentType="text/html; charset=Windows-31J"
pageEncoding="Windows-31J"%>
<html>
<style>
h1 {text-align:center;}
</style>
<h1>出力画面</h1>
</html>
C18_HelloWeb.java
package StudyC;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class C18_HelloWeb extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void init(ServletConfig config)
throws ServletException{
}
protected void doGet (HttpServletRequest request, HttpServletResponse respone)
throws ServletException, IOException {
respone.setContentType("text/html; charset=Windows-31J");
request.setCharacterEncoding("Windows-31J");
HttpSession session = request.getSession(true);
PrintWriter out = respone.getWriter();
RequestDispatcher rd = request.getRequestDispatcher("C18_HelloOUTPUT.jsp");
rd.forward(request,respone);
String firstName = request.getParameter("dataName");
#SuppressWarnings("unchecked")
ArrayList<String> dataList = (ArrayList<String>)session.getAttribute("PreviousItems");
if( dataList == null ) {
dataList = new ArrayList<String>();
session.setAttribute("PreviousItems", dataList);
}
dataList.add(firstName);
int i = 0;
do{
out.print(HTMLFilter.filter(dataList.get(i)) + "<br>");
i++;
} while(i<dataList.size());
}
protected void doPost(HttpServletRequest request, HttpServletResponse respone)
throws IOException, ServletException
{
doGet(request, respone);
}
}
I think there is a problem in the C18_HelloINPUT.jsp and C18_HelloWeb.java. Thank you!

JSP page not working in Servlet Program

Actually i'm trying to display the details obtained from JSP form with servlet. But I'm not able to display the JSP page. But I can see the program entering into the POST method in Servlet.
Here is my code,
Startup.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="controlServlets" method="post">
<input type="text" name="name"/><br>
<input type="text" name="group"/>
<input type="text" name="pass"/>
<input type="submit" value="submit">
</form>
</body>
</html>
web.xml
<web-app>
<servlet>
<servlet-name>controlServlets</servlet-name>
<servlet-class>com.selenium8x8.servlet.ControlServlets</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>controlServlets</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
ControlServlets.java
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/ControlServlets")
public class ControlServlets extends HttpServlet {
private static final long serialVersionUID = 1L;
public ControlServlets() {
super();
// TODO Auto-generated constructor stub
}
// #Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String group = request.getParameter("group");
String pass = request.getParameter("pass");
System.out.println("Name :"+ name);
System.out.println("group :"+ group);
System.out.println("pass :"+ pass);
System.out.println("Post method");
}
}
In console,
I can see the following,
Name :null
group :null
pass :null
Post method
Please Help...
Part I)If you want to use web.xml for your application then you need to make following changes :
1)In Startup.jsp change the action attribute of <form> tag to
<form action="ControlServlets" method="post">
↑
2)In web.xml change the <servlet-mapping> to
<servlet-mapping>
<servlet-name>controlServlets</servlet-name>
<url-pattern>/ControlServlets</url-pattern>
</servlet-mapping>
3)In ControlServlets.java several changes as, in web.xml you mentioned
<servlet-class>com.selenium8x8.servlet.ControlServlets</servlet-class>
↑
This is the package name, so you must have first statement in ControlServlets.java
package com.selenium8x8.servlet; //in your code it is missing
Then, comment following two lines
//import javax.servlet.annotation.WebServlet;
and
//#WebServlet("/ControlServlets")
Now, run application, it will give you desired output.
Part II) If you want to use #WebServlet annotation, as you did
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/ControlServlets")
public class ControlServlets extends HttpServlet {
...
.....
.......
}
Then, no need for web.xml. The above does basically the same as following:
<servlet>
<servlet-name>controlServlets</servlet-name>
<servlet-class>com.selenium8x8.servlet.ControlServlets</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>controlServlets</servlet-name>
<url-pattern>/ControlServlets</url-pattern>
</servlet-mapping>
For using #WebServlet annotation you need Java EE 6 / Servlet 3.0

Why my Ajax call refresh page? (i.e. calling servlet again)

I'm studying RESTful web service using Java.
My environment is using Netbean with GlassFish v3.
I have a page URL /inventoryList which is URL mapped to InventoryApp.java servlet in web.xml
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<servlet>
<servlet-name>inventory servlet</servlet-name>
<servlet-class>local.test.servlet.InventoryApp</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>inventory servlet</servlet-name>
<url-pattern>/inventoryList</url-pattern>
</servlet-mapping>
</web-app>
In the servlet, it obtains list of inventory item info from DB and display to the JSP page.
inventory.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%# taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script type="text/javascript">
function ajaxGet(inventoryId) {
alert(inventoryId);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
alert('sigh');
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
alert('ready 4');
alert('After ready4 ===> ' + xmlHttp.responseText);
displayInventoryHtml(xmlHttp);
}
}
var url = "resources/inventory/" + inventoryId;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
function displayInventoryHtml(responseAjax) {
document.getElementById('inventoryItem').innerHTML = responseAjax.responseText;
}
</script>
</head>
<body>
<h1>Inventory page</h1>
<table border="1" cellspacing="1" cellpadding="5">
<th>id</th>
<th>amount</th>
<c:forEach items="${inventoryList}" var="inv" >
<tr>
<td>${inv.id}</td>
<td>${inv.amount}</td>
</tr>
</c:forEach>
</table>
<hr />
<div id="inventoryItem">
</div>
</body>
</html>
As you can see the inventory.jsp would successfully output the list of inventory item.
So far so good.
Here, I made the output of inventory amount value to be a link to Ajax call.
<td>${inv.amount}</td>
It calls HTTP GET method and REST service (code shown below) will get inventory data of specified id (database primary id) and I put the Ajax responseText into the div (id=inventoryItem)
InventoryResource.java
package local.test.jaxrs;
import java.util.List;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import local.test.dao.InventoryDao;
import local.test.session.Inventory;
#Path("/inventory")
public class InventoryResource {
#Context
private UriInfo context;
/** Creates a new instance of InventoryResource */
public InventoryResource() {
}
#Path("{inv_id}")
#GET
#Produces("text/html")
public String getJson(#PathParam("inv_id") String inventory_id) {
System.out.println("GET is being handled");
Inventory invBean = new Inventory(Integer.valueOf(inventory_id));
InventoryDao invDao = new InventoryDao();
List<Inventory> inv = invDao.findById(invBean);
String html = "<b>" + inv.get(0).getId() + "</b><br /><b>" + inv.get(0).getAmount() + "</b><br />";
return html;
}
}//end class
When I test this code, everything works just fine. The Ajax successfully get data and insert into the HTML DIV tag and the inventory data shows up for half second and disappear.
Using firebug and looking at glassfish v3 server log, I figure that at the end, it is calling InventoryApp.java servlet AGAIN which cause the page to redirect to /inventoryList
I know Ajax is partial request and should not cause page to refresh.
I'm stack in this for few days now, could anyone give me hint what's going on?
I'm not sure if it is practical to mix servlet and web.xml with REST like I do.
FYI, my InventoryApp.java servlet code
package local.test.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
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 local.test.dao.InventoryDao;
import local.test.session.Inventory;
#WebServlet(name="InventoryApp", urlPatterns={"/InventoryApp"})
public class InventoryApp 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");
PrintWriter out = response.getWriter();
try {
} finally {
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 {
InventoryDao invDao = new InventoryDao();
List<Inventory> invList = invDao.findAll();
//this list looks ok...
System.out.println("================= do get servelt ===" + invList.get(0));
request.setAttribute("inventoryList", invList);
request.getRequestDispatcher("inventory.jsp").forward(request, response);
//processRequest(request, response); //commented not sure what it is..
}
}//end class
${inv.amount}
remove the href attribute
<a onclick="ajaxGet(${inv.id})">${inv.amount}</a>
or cancel the promotion of the click event
${inv.amount}

Categories