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}
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 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
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I am trying to implement listener program in which i get an HTTP status 500 Error once i submit with the index.html form page which redirect it to Servlet1 class.!
Mylistener.java
import javax.servlet.annotation.WebListener;
import javax.servlet.*;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
#WebListener
public class Mylistener implements HttpSessionListener {
static int total=0, current=0;
ServletContext ctx=null;
public void sessionCreated(HttpSessionEvent e) {
total++;
current++;
ctx=e.getSession().getServletContext();
ctx.setAttribute("total users",total);
ctx.setAttribute("looged users",current);
}
/**
* #see HttpSessionListener#sessionDestroyed(HttpSessionEvent)
*/
public void sessionDestroyed(HttpSessionEvent e) {
current--;
ctx.setAttribute("currentusers",current);
}
}
![enter image description here][1
Servlet1.java
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class Servlet1 extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
res.setContentType("Text/html");
PrintWriter out=res.getWriter();
String n= req.getParameter("nname");
System.out.println("Welcome"+n);
HttpSession session=req.getSession();
session.setAttribute("uname",n);
ServletContext ctx= getServletContext();
int i=(Integer)ctx.getAttribute("total");
int c=(Integer)ctx.getAttribute("current");
out.println("total users"+i);
out.println("Current users"+c);
out.close();
}
}
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="servlet1" method="post">
Enter your name <input type="text" name="nname"><br>
Enter your password : <input type="password" name="npass">
<input type="submit" value="submit">
</form>
</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">
<listener>
<listener-class>Mylistener</listener-class>
</listener>
<servlet>
<servlet-name>First</servlet-name>
<servlet-class>Servlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>First</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
</web-app>
]
Error:
HTTP Status 500 -
type Exception report
message
description The server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.NullPointerException
Servlet1.doPost(Servlet1.java:25)
javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.59 logs.
check null condition before casting.
int i=0,c=0;
if(ctx.getAttribute("total") != null){
i=(Integer)ctx.getAttribute("total");
}
if(ctx.getAttribute("current") != null){
c=(Integer)ctx.getAttribute("current");
}
out.println("total users"+i);
out.println("Current users"+c);
I am trying to make AJAX call from html file to a servlet class to pass a variable but not getting any output. Please check the code below and suggest the changes that should be done.
This is my project structure
FrontPage.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function func() {
var build = document.getElementById('name').textContent;
$.ajax({
type : 'GET',
url : 'http://localhost:8081/Sample/TestServlet',
data : build,
success : function(data) {
alert("Success");
},
error : function() {
alert("Error");
}
});
}
</script>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a id="name" href="#" onClick="func();">Build1</a>
</body>
</html>
This is TestServlet.java. This is trying to print variable which is passed from javascript function using Ajax call:
package com.infy;
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;
/**
* Servlet implementation class TestServlet
*/
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public TestServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println(request.getParameter("build"));
}
}
Web.xml file
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Sample</display-name>
<welcome-file-list>
<welcome-file>FrontPage.html</welcome-file>
</welcome-file-list>
<servlet>
<description>Sample Servlet</description>
<display-name>TestServlet</display-name>
<servlet-name>TestServlet</servlet-name>
<servlet-class>com.infy.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/TestServlet</url-pattern>
</servlet-mapping>
</web-app>
I want to send the build variable to the servlet class and print the same from the servlet class but not getting any output.Please help me in fixing this.
you are sending the request as GET method and you are not passing the variable in url.Try to print the build value in servlet first and check weather it is coming to servlet or not.
You should send the GET request as :-
url : "/TestServlet?build="+build+",
type : "GET"
,
And watch out the URL also.
in servlet site create a json object.Like
JSONObject jsonObj = new JSONObject();
jsonObj.put("build", build);
Try it and let me know.
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