This question already has an answer here:
How do I pass current item to Java method by clicking a hyperlink or button in JSP page?
(1 answer)
Closed 7 years ago.
Hello everyone hope you having a good day,because i'm not xD , i'm new to the web programming and i've started with JSP and Servelts to do web operation my problem is when i click on "delete" it triggers the servlet but nothing happen the row doesn't get deleted and the value ( pw.print(name) ) doesn't show up. these are my codes.
DeleteServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
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;
public class deleteuser extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter pw=response.getWriter();
try {
Connection con=Connecter.obtenirconnexion();
Statement st=con.createStatement();
String name=request.getParameter("id");
String Query="delete from users where name ='"+ name+"'";
st.executeUpdate(Query);
pw.print(name);
} catch (SQLException ex) {
Logger.getLogger(deleteuser.class.getName()).log(Level.SEVERE, null, ex);
}
request.getRequestDispatcher("users.jsp").forward(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Users.jsp
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.PreparedStatement"%>
<%#page import="login.Connecter"%>
<%#page import="java.sql.Connection"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Users</title>
<style> table,td,th
{
border:1px black solid;
} </style>
</head>
<body>
<h1>Hello World</h1>
<%
Connection con = Connecter.obtenirconnexion();
String req = "select * from users";
PreparedStatement pst = con.prepareStatement(req);
ResultSet cur = pst.executeQuery();
out.println("<table ><tr><th>Name</th> <th>Password </th><th>Rank </th><th>Delete </th>");
while (cur.next()) {
out.println("<tr><td>" + cur.getString(1) + "</td><td>" + cur.getString(2) + "</td><td>" + cur.getString(3) + "</td><td> <a href=deleteuser id='"+cur.getString(1)+"'> delete </a></td></tr>");
}
out.println("</table>");
out.close();
%>
</body>
Well, the link to the DeleteServlet is broken. In order to pass a request parameter, it should be:
<a href=deleteuser?id='"+cur.getString(1)+"'> delete </a>
(note the ?)
But what you do is bad.
you have direct database accesses in a JSP. Best practices recommend to do data accesses in a servlet that would populate request attributes and forward to a JSP to display everything (or even to have layers that could be unit tested : Servlet <-> service <-> persistence)
you do a response.getWriter().print(...) inside the servlet before forwarding to the JSP. What you print will be outside of the body part (and even before the head!): here again you should put it in a request attribute and use it in JSP
you use a GET request to change database values. GET requests should only be used for read only operations. A delete should use a POST request - this last part is mainly for purists and if it has been the only problem I would not even have mentioned it...
Related
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.
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);
}
}
I am trying to load data into JSP page from MySQL database using Eclipse and Tomcat 8 server. My .jsp file looks as follows:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# page import="java.util.ArrayList"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<jsp:forward page="/ProductDisplay" />
<table border="2">
<tr>
<td>Id</td>
<td>First Name</td>
<td>Last Name</td>
<td>Email</td>
<td>Phone Number</td>
</tr>
<c:forEach var="patients" items="${patients}">
<tr>
<td>${patients.getPatientId()}</td>
<td>${patients.getPatientfName()}</td>
<td>${patients.getPatientlName()}</td>
<td>${patients.getPatientEmail()}</td>
<td>${patients.getPatientPhone()}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
The .java servlet file:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ProductDisplay
*/
#WebServlet("/ProductDisplay")
public class ProductDisplay extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ProductDisplay() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
PatientsDao p = new PatientsDao();
ArrayList<Patient> patients = p.getPatients();
request.setAttribute("patients", patients);
request.getRequestDispatcher("/Patient.jsp").forward(request, response);
}
}
And the database connector class looks as follows:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class PatientsDao {
DBConnection mt = new DBConnection();
Connection myConn = mt.myConn;
private class DBConnection {
public Connection myConn;
public DBConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
myConn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/PatientsDB", "root", "");
} catch (Exception exc) {
exc.printStackTrace();
}
}
}
public ArrayList<Patient> getPatients() {
ArrayList<Patient> patients = new ArrayList<>();
try {
PreparedStatement pst =
myConn.prepareStatement("select * from Patients");
ResultSet r = pst.executeQuery();
while(r.next()) {
Patient p = new Patient();
p.setId(r.getInt("id"));
p.setfName(r.getString("fName"));
p.setlName(r.getString("lName"));
p.setEmail(r.getString("Email"));
p.setPhone(r.getString("Phone"));
patients.add(p);
}
}
catch (SQLException exc) {
System.out.println("An error occured. Error: " + exc.getMessage());
}
return patients;
}
}
Correct me if I'm wrong but I believe that upon running the Tomcat server the .java servlet class is invoked and information from the database is loaded into JSP page without any action needed. However, this does not happen in my case. Once I start Tomcat server and navigate to the Patient.jsp page the only thing that is displayed is the table header (which does not come from database). No data from MySQL database is displayed.
I know that this is not a MySQL problem as I can load all the data successfully if I add a form and use a button. Once the button is clicked and doGet method is invoked everything is loaded successfully.
My question is, how would I load the data automatically, without clicking a button or a link? I was doing research and apparently all info is supposed to load automatically. This, however, does not happen in my case. Am I missing something? Thank you in advance!
No, you mistake.
Servlet load first time when you call it(for examle go to Patient.jsp).
But when you go to Patient.jsp work only servlet Patient.jsp(jsp page convert to servlet class automatically), and you servlet /ProductDisplay dont work at all.
Your request attribute is empty when you call Patient.jsp beacause ProductDisplay don`t work.
You have three ways:
1) You should start with /ProductDisplay page
2) Or add index.jsp page and start with this page.
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<jsp:forward page="/ProductDisplay" />
</body>
</html>
3) And bad variant - add scriptlet to page Patient.jsp with code and start whith this page
PatientsDao p = new PatientsDao();
ArrayList<Patient> patients = p.getPatients();
request.setAttribute("patients", patients);
And remember never call servlets directly. Only through any servlet.
This is bad practice
I need help in forwarding the result set values from servlet to jsp without using JSTL implementation
Work flow :
The user enters a value in text box and clicks search button
On clicking search the servlet is called.
The servlet focuses on the database implementation and forward the result set values to the same jsp page from where the request comes.
Issue:
My result set size is 3, but the value which is in the top of my table alone is getting printed in my jsp page. The remaining 2 values are missing.I want all the values to be printed in my jsp page.
This is my code:
Productlist.jsp
<%#page import="java.util.List"%>
<%#page import="web.Products"%>
<%#page import="java.util.ArrayList"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Products</title>
</head>
<body>
<form method="post" align="center" action="ProductList">
Company Name:<input type="text" size="20" id="company" name="company" />
<input type="submit" value="search"/>
<%
List<Products> pdts = (List<Products>) request.getAttribute("list");
if(pdts!=null){
for(Products prod: pdts){
out.println("<br/>" + prod.getProductname());
}
}
%>
</form>
</body>
</html>
Products.java
public class Products {
private String productname;
public String getProductname() {
return productname;
}
public void setProductname(String productname) {
this.productname=productname ;
}
}
ProductList.java(servlet-code)
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpSession;
public class ProductList extends HttpServlet {
static final String dbURL = "jdbc:mysql://localhost:3306/pdt";
static final String dbUser = "root";
static final String dbPass = "root";
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ResultSet rs = null;
Connection connection = null;
List<Products> pdt = new ArrayList<Products>();
try{
String company =request.getParameter("company");
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection (dbURL,dbUser,dbPass);
String sql="select product_pck from comp_pdt_list where company_name='"+company+"'";
PreparedStatement prep = connection.prepareStatement(sql);
rs=prep.executeQuery();
while(rs.next()) {
Products prod=new Products();
prod.setProductname(rs.getString("product_pck"));
pdt.add(prod);
request.setAttribute("list",pdt);
RequestDispatcher rd=request.getRequestDispatcher("Productlist.jsp");
rd.forward(request,response);
return;
}
prep.close();
} catch(Exception E) {
//Any Exceptions will be caught here
System.out.println("The error is"+E.getMessage());
} finally {
try {
connection.close();
} catch (Exception ex) {
System.out.println("The error is" + ex.getMessage());
}
}
}
}
You set the attribute to request in your while loop. So the "list" contains only one product. (method returns on first iteration)
Add products to the list in while loop and set your list (request attribute) only after while loop.
Following should fix it:
while(rs.next()){
Products prod=new Products();
prod.setProductname(rs.getString("product_pck"));
pdt.add(prod);
}
request.setAttribute("list",pdt);
RequestDispatcher rd=request.getRequestDispatcher("Productlist.jsp");
rd.forward(request,response);
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}