Below is my View.jsp code
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<portlet:actionURL name="myAction" var="myAction">
</portlet:actionURL>
<form action="${myAction}" method="POST">
Name : <input type="text" name="name">
<input type="button" value="SUBMIT">
</form>
Below is my Portlet class code
package com.generic;
import java.io.IOException;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.GenericPortlet;
import javax.portlet.PortletException;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
/**
* Portlet implementation class FirstGenericDemo
*/
public class FirstGenericDemo extends GenericPortlet {
public void init() {
viewTemplate = getInitParameter("view-template");
}
public void doView(RenderRequest renderRequest, RenderResponse renderResponse)throws IOException, PortletException {
System.out.println("view");
include(viewTemplate, renderRequest, renderResponse);
}
protected void include(String path, RenderRequest renderRequest,RenderResponse renderResponse)throws IOException, PortletException {
PortletRequestDispatcher portletRequestDispatcher =
getPortletContext().getRequestDispatcher(path);
if (portletRequestDispatcher == null) {
_log.error(path + " is not a valid include");
}
else {
portletRequestDispatcher.include(renderRequest, renderResponse);
}
}
protected String viewTemplate;
private static Log _log = LogFactoryUtil.getLog(FirstGenericDemo.class);
#Override
public void processAction(ActionRequest request, ActionResponse response)
throws PortletException, IOException {
System.out.println("ok");
String name=request.getParameter("name");
System.out.println("name is : "+name);
super.processAction(request, response);
}
}
When the portlet is rendered view method gets called but when i click on submit button neither processAction method gets called nor view method. Also these is no error in stacktrace. I did tried it by deploying several times but the issue is same. can anyone please help on this.
?
The code has several issues.
The renaming suggested by Ajay will not work as you are using the GenericPortlet as the parent.
To properly bind the jsp/html code with portlet class you need to rename the class and annotate it as suggested by Ajay.
#ProcessAction(name=myAction)
public void myAction(ActionRequest request, ActionResponse response)
throws PortletException, IOException {
//your code
}
Another option is to witch to MVCPortlet as a base class. Then the renaming will be enough (name attribute needs to match method name).
The second thing that will not work are the parameters. If you are not using the aui tags you need to add the namespace to the input names. In JAVA code you refer to the parameters just by the name (without namespace)
Name : <input type="text" name="<portlet:namespace/>name">
I suggest using the AUI tags. It's easier.
As said by Miroslav Ligas there are several issues.To remove those issues you need to do changes in view.jsp as well as your Portlet class.
a) In your view.jsp you need to use the below code snippet
<portlet:actionURL name="myAction" var="myAction">
</portlet:actionURL>
<form action="${myAction}" method="POST">
Name : <input type="text" name="name">
<input type="submit" value="SUBMIT">
</form>
If you are using the input type="button" then it will not work till you use document.getElementById("myForm").submit(); in your javascript part.
b) In your Portlet Class
1) You need to remove the super.processAction(request, response); as it will generate exception.
2) You need to add below code snippet in your ProcessAction method
response.setRenderParameter("jspPage","/html/jsps/displayEmployees.jsp");
above code snippet is use so as to redirect to some view part(jsp page) where /html/jsps/displayEmployees.jsp represents the path to jsp which you want to use it as view part.
and changes suggested by me earlier like using annotation #ProcessAction(name=myAction) or changing name of action method will not be recommended as you are extending the GenericPortlet class rahter then MVCPortlet class.If you extend MVCPortlet Class then it's mandatory to use them.
Changes like adding
<portlet:namespace/> in html tags like Name : <input type="text" name="<portlet:namespace/>name"> are optional to use in your code snippet.
Related
I have an HTML table with rows fetched from a database displayed in that table. I want the user to be able to delete a row by clicking on a delete hyperlink or button besides each row.
How do I invoke a JSP function on the page, when the user clicks on each of those delete hyperlinks or button, so that I can delete that row's entry from the database? What exactly should the <a> or <button> tag have to call the JSP function?
Note that I need to call a JSP function, not a JavaScript function.
Simplest way: just let the link point to a JSP page and pass row ID as parameter:
delete
And in delete.jsp (I'm leaving obvious request parameter checking/validating aside):
<% dao.delete(Long.valueOf(request.getParameter("id"))); %>
This is however a pretty poor practice (that was still an understatement) and due to two reasons:
HTTP requests which modifies the data on the server side should not be done by GET, but by POST. Links are implicit GET. Imagine what would happen when a web crawler like googlebot tries to follow all delete links. You should use a <form method="post"> and a <button type="submit"> for the delete action. You can however use CSS to style the button to look like a link. Edit links which just preload the item to prefill the edit form can safely be GET.
Putting business logic (functions as you call it) in a JSP using scriptlets (those <% %> things) is discouraged. You should use a Servlet to control, preprocess and postprocess HTTP requests.
Since you didn't tell any word about a servlet in your question, I suspect that you're already using scriptlets to load data from DB and display it in a table. That should also be done by a servlet.
Here's a basic kickoff example how to do it all. I have no idea what the table data represents, so let take Product as an example.
public class Product {
private Long id;
private String name;
private String description;
private BigDecimal price;
// Add/generate public getters and setters.
}
And then the JSP file which uses JSTL (just drop jstl-1.2.jar in /WEB-INF/lib to install it) to display the products in a table with an edit link and a delete button in each row:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
...
<form action="products" method="post">
<table>
<c:forEach items="${products}" var="product">
<tr>
<td><c:out value="${fn:escapeXml(product.name)}" /></td>
<td><c:out value="${product.description}" /></td>
<td><fmt:formatNumber value="${product.price}" type="currency" currencyCode="USD" /></td>
<td>edit</td>
<td><button type="submit" name="delete" value="${product.id}">delete</button></td>
</tr>
</c:forEach>
</table>
add
</form>
Note the difference of approach: the edit link fires a GET request with an unique identifier of the item as request parameter. The delete button however fires a POST request instead whereby the unique identifier of the item is passed as value of the button itself.
Save it as products.jsp and put it in /WEB-INF folder so that it's not directly accessible by URL (so that the enduser is forced to call the servlet for that).
Here's how the servlet roughly look like (validation omitted for brevity):
#WebServlet("/products")
public class ProductsServlet extends HttpServlet {
private ProductDAO productDAO; // EJB, plain DAO, etc.
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Product> products = productDAO.list();
request.setAttribute("products", products); // Will be available as ${products} in JSP.
request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String delete = request.getParameter("delete");
if (delete != null) { // Is the delete button pressed?
productDAO.delete(Long.valueOf(delete));
}
response.sendRedirect(request.getContextPath() + "/products"); // Refresh page with table.
}
}
Here's how the add/edit form at /WEB-INF/product.jsp can look like:
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
...
<form action="product" method="post">
<label for="name">Name</label>
<input id="name" name="name" value="${fn:escapeXml(product.name)}" />
<br/>
<label for="description">Description</label>
<input id="description" name="description" value="${fn:escapeXml(product.description)}" />
<br/>
<label for="price">Price</label>
<input id="price" name="price" value="${fn:escapeXml(product.price)}" />
<br/>
<button type="submit" name="save" value="${product.id}">save</button>
</form>
The fn:escapeXml() is just there to prevent XSS attacks when edit data is redisplayed, it does exactly the same as <c:out>, only better suitable for usage in attribtues.
Here's how the product servlet can look like (again, conversion/validation omitted for brevity):
#WebServlet("/product")
public class ProductServlet extends HttpServlet {
private ProductDAO productDAO; // EJB, plain DAO, etc.
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String edit = request.getParameter("edit");
if (edit != null) { // Is the edit link clicked?
Product product = productDAO.find(Long.valueOf(delete));
request.setAttribute("product", product); // Will be available as ${product} in JSP.
}
request.getRequestDispatcher("/WEB-INF/product.jsp").forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String save = request.getParameter("save");
if (save != null) { // Is the save button pressed? (note: if empty then no product ID was supplied, which means that it's "add product".
Product product = (save.isEmpty()) ? new Product() : productDAO.find(Long.valueOf(save));
product.setName(request.getParameter("name"));
product.setDescription(request.getParameter("description"));
product.setPrice(new BigDecimal(request.getParameter("price")));
productDAO.save(product);
}
response.sendRedirect(request.getContextPath() + "/products"); // Go to page with table.
}
}
Deploy and run it. You can open the table by http://example.com/contextname/products.
See also:
Our servlets wiki page (also contains an example with validation)
doGet and doPost in Servlets
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
I am old to JAVA but very new to the topics of JSPs & Servlets. I am trying to do some jdbc operations by taking the values from JSP into servlet. To do that, I have written a JSP with a drop down list and a submit button.
Jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<div align='left' >
<div align='left' >
<label class="text-white mb-3 lead">Which report do you want to generate?</label>
<select id="reportSelection" data-style="bg-white rounded-pill px-5 py-3 shadow-sm " class="selectpicker w-100" name="reportselection">
<option>Outage</option>
<option>DataQuality</option>
<option>Latency</option>
</select>
</head>
<body>
<p id = "demo"> </p>
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d;
</script>
</body>
</div>
</div>
</body>
<hr class="colorgraph">
<div class="row">
<div class="col-xs-12 col-md-6"><input type="submit" value="Submit" class="btn btn-primary btn-block btn-lg register" tabindex="7"></div>
</div>
</body>
</html>
And this is how my servlet class looks like.
#WebServlet("/getdata.do")
public class DataServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
GetTableColumn gt = new GetTableColumn();
String issue = request.getParameter("reportSelection");
String message;
try {
if ("Latency".equals(issue)) {
message = gt.process("latency");
} else if ("DataQuality".equals(issue)) {
message = gt.process("DataQuality");
System.out.println("Data quality");
} else if ("Outage".equals(issue)) {
message = gt.process("Outage");
}
} catch (SQLException s) {
s.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
I am reading the JSP drop down values in my servlet class and passing a String to method process based on the value received. I looked online to configure the web.xml file as below.
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>DataServlet</servlet-name>
<display-name>DataServlet</display-name>
<description>Begin servlet</description>
<servlet-class>com.servlets.DataServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DataServlet</servlet-name>
<url-pattern>/parse</url-pattern>
</servlet-mapping>
I am trying to run the code on IntelliJ and here is how I have configured my tomcar server on IntelliJ.
When I run the code, I see the page is generating the jsp as expected.
What I don't understand is how to configure the submit with onclick so that I click on submit and the java program in the backed triggers. I have written the java code just to read values from a database by taking the input from the method process. This was running fine and I was asked to take the input from JSP and display the result back on a JSP.
When I click on submit button, I don't see any progress in the console output. I guess I didn't map it correctly.
Most of the links online contain JSP & JAVA together which is even more confusing.
Could anyone let me know how can I trigger the program by clicking the submit button
Since you are using #WebServlet, you do not need mapping in web.xml. Just add the following line inside body of your JSP:
<form action="getdata.do" method="post">
Look at your JSP file, pay attention at your head and body tag. I think it's a wrong that you have body inside other body and closing head tag inside body.
Other case that can be more important that to send a form by clicking to submit button you should put it inside tag form, something like this.
<form action = "getdata.do" method = "POST">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
I have an HTML table with rows fetched from a database displayed in that table. I want the user to be able to delete a row by clicking on a delete hyperlink or button besides each row.
How do I invoke a JSP function on the page, when the user clicks on each of those delete hyperlinks or button, so that I can delete that row's entry from the database? What exactly should the <a> or <button> tag have to call the JSP function?
Note that I need to call a JSP function, not a JavaScript function.
Simplest way: just let the link point to a JSP page and pass row ID as parameter:
delete
And in delete.jsp (I'm leaving obvious request parameter checking/validating aside):
<% dao.delete(Long.valueOf(request.getParameter("id"))); %>
This is however a pretty poor practice (that was still an understatement) and due to two reasons:
HTTP requests which modifies the data on the server side should not be done by GET, but by POST. Links are implicit GET. Imagine what would happen when a web crawler like googlebot tries to follow all delete links. You should use a <form method="post"> and a <button type="submit"> for the delete action. You can however use CSS to style the button to look like a link. Edit links which just preload the item to prefill the edit form can safely be GET.
Putting business logic (functions as you call it) in a JSP using scriptlets (those <% %> things) is discouraged. You should use a Servlet to control, preprocess and postprocess HTTP requests.
Since you didn't tell any word about a servlet in your question, I suspect that you're already using scriptlets to load data from DB and display it in a table. That should also be done by a servlet.
Here's a basic kickoff example how to do it all. I have no idea what the table data represents, so let take Product as an example.
public class Product {
private Long id;
private String name;
private String description;
private BigDecimal price;
// Add/generate public getters and setters.
}
And then the JSP file which uses JSTL (just drop jstl-1.2.jar in /WEB-INF/lib to install it) to display the products in a table with an edit link and a delete button in each row:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
...
<form action="products" method="post">
<table>
<c:forEach items="${products}" var="product">
<tr>
<td><c:out value="${fn:escapeXml(product.name)}" /></td>
<td><c:out value="${product.description}" /></td>
<td><fmt:formatNumber value="${product.price}" type="currency" currencyCode="USD" /></td>
<td>edit</td>
<td><button type="submit" name="delete" value="${product.id}">delete</button></td>
</tr>
</c:forEach>
</table>
add
</form>
Note the difference of approach: the edit link fires a GET request with an unique identifier of the item as request parameter. The delete button however fires a POST request instead whereby the unique identifier of the item is passed as value of the button itself.
Save it as products.jsp and put it in /WEB-INF folder so that it's not directly accessible by URL (so that the enduser is forced to call the servlet for that).
Here's how the servlet roughly look like (validation omitted for brevity):
#WebServlet("/products")
public class ProductsServlet extends HttpServlet {
private ProductDAO productDAO; // EJB, plain DAO, etc.
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Product> products = productDAO.list();
request.setAttribute("products", products); // Will be available as ${products} in JSP.
request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String delete = request.getParameter("delete");
if (delete != null) { // Is the delete button pressed?
productDAO.delete(Long.valueOf(delete));
}
response.sendRedirect(request.getContextPath() + "/products"); // Refresh page with table.
}
}
Here's how the add/edit form at /WEB-INF/product.jsp can look like:
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
...
<form action="product" method="post">
<label for="name">Name</label>
<input id="name" name="name" value="${fn:escapeXml(product.name)}" />
<br/>
<label for="description">Description</label>
<input id="description" name="description" value="${fn:escapeXml(product.description)}" />
<br/>
<label for="price">Price</label>
<input id="price" name="price" value="${fn:escapeXml(product.price)}" />
<br/>
<button type="submit" name="save" value="${product.id}">save</button>
</form>
The fn:escapeXml() is just there to prevent XSS attacks when edit data is redisplayed, it does exactly the same as <c:out>, only better suitable for usage in attribtues.
Here's how the product servlet can look like (again, conversion/validation omitted for brevity):
#WebServlet("/product")
public class ProductServlet extends HttpServlet {
private ProductDAO productDAO; // EJB, plain DAO, etc.
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String edit = request.getParameter("edit");
if (edit != null) { // Is the edit link clicked?
Product product = productDAO.find(Long.valueOf(delete));
request.setAttribute("product", product); // Will be available as ${product} in JSP.
}
request.getRequestDispatcher("/WEB-INF/product.jsp").forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String save = request.getParameter("save");
if (save != null) { // Is the save button pressed? (note: if empty then no product ID was supplied, which means that it's "add product".
Product product = (save.isEmpty()) ? new Product() : productDAO.find(Long.valueOf(save));
product.setName(request.getParameter("name"));
product.setDescription(request.getParameter("description"));
product.setPrice(new BigDecimal(request.getParameter("price")));
productDAO.save(product);
}
response.sendRedirect(request.getContextPath() + "/products"); // Go to page with table.
}
}
Deploy and run it. You can open the table by http://example.com/contextname/products.
See also:
Our servlets wiki page (also contains an example with validation)
doGet and doPost in Servlets
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
So I'm new to servlets and jsp, and was following along to the Hello World post-process example from https://stackoverflow.com/tags/servlets/info. When I tried to run it using Tomcat v9.0 in Eclipse, I get
After doing some additional research, and poking around, I haven't found a working solution or an explanation of what is happening. I had basically copied the code from the example, so I'm pretty confused as to why it isn't working. I also don't really have the proficiency yet to figure out exactly what is wrong, so any help would be great. My only hunch so far is that I probably messed up the directories or something. Here is a picture:
The only discrepancy I could find was where my HelloServlet.class was located, which was in
apache-tomcat-9.0.19/webapps/hello/build/classes/com/example/controller/HelloServlet.class
instead of
/WEB-INF/classes/com/example/controller/HelloServlet.class
as stated in the example. I assumed this was because Eclipse, by default, had compiled the class file where it is now, but just to be sure, I copied the class folder into WEB-INF so it would match the example, but it still didn't work. So that is where I'm stuck. If anyone could point out my mistake or even help at all, that would be very much appreciated. I have included my hello.jsp, web.xml, and HelloServlet.java files below just in case there's any issues with them.
hello.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Servlet Hello World</title>
<style>.error { color: red; } .success { color: green; }</style>
</head>
<body>
<form action="hello" method="post">
<h1>Hello</h1>
<p>
<label for="name">What's your name?</label>
<input id="name" name="name" value="${fn:escapeXml(param.name)}">
<span class="error">${messages.name}</span>
</p>
<p>
<label for="age">What's your age?</label>
<input id="age" name="age" value="${fn:escapeXml(param.age)}">
<span class="error">${messages.age}</span>
</p>
<p>
<input type="submit">
<span class="success">${messages.success}</span>
</p>
</form>
</body>
</html>
web.xml
<web-app
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
</web-app>
HelloServlet.java
package com.example.controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#SuppressWarnings("serial")
#WebServlet("/hello")
public class HelloServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Preprocess request: we actually don't need to do any business stuff, so just display JSP.
request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Postprocess request: gather and validate submitted data and display the result in the same JSP.
// Prepare messages.
Map<String, String> messages = new HashMap<String, String>();
request.setAttribute("messages", messages);
// Get and validate name.
String name = request.getParameter("name");
if (name == null || name.trim().isEmpty()) {
messages.put("name", "Please enter name");
} else if (!name.matches("\\p{Alnum}+")) {
messages.put("name", "Please enter alphanumeric characters only");
}
// Get and validate age.
String age = request.getParameter("age");
if (age == null || age.trim().isEmpty()) {
messages.put("age", "Please enter age");
} else if (!age.matches("\\d+")) {
messages.put("age", "Please enter digits only");
}
// No validation errors? Do the business job!
if (messages.isEmpty()) {
messages.put("success", String.format("Hello, your name is %s and your age is %s!", name, age));
}
request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
}
}
You need to allow cross origin
private void setAccessControlHeaders(HttpServletResponse resp) {
resp.setHeader("Access-Control-Allow-Origin", "http://localhost:9000");
resp.setHeader("Access-Control-Allow-Methods", "GET");
}
I'm experimenting with sending data from a jsp form and calling a servlet and showing that data in the servlet.
I would like to use setAttribute and getAttribute.
In this jsp file I'm using setAttribute:
<HTML>
<HEAD>
<TITLE>
Multi Processor
</TITLE>
</HEAD>
<BODY>
<h4>This is a form submitted via POST:</h4>
<FORM action = "/MyWebArchive/MulitProcessorServlet" method = "POST">
Enter your name: <INPUT type="TEXT" name="name"/>
<BR/>
<INPUT type="submit"/>
</FORM>
<BR/>
<h4>This is a form submitted via GET:</h4>
<FORM action = "/Week05WebArchive/MulitProcessorServlet">
Enter your name: <INPUT type="TEXT" name="name"/>
<BR/>
<INPUT type="submit"/>
</FORM>
</BODY>
<%
String strMasjidLocation = "Selimiyie Masjid Methuen";
session.setAttribute("MasjidLocation", strMasjidLocation);
%>
</HTML>
This is the servlet I would like to use getAttribute but I don't know how to use GetAttribute. Can you show me what additional code I need to add to the servlet so I can capture the value from the setAttribute?
package temp22;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Locale;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class MulitProcessorServlet
*/
public class MulitProcessorServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
doPost(req, res);
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
String name = req.getParameter("name");
StringBuffer page = new StringBuffer();
String methodWhoMadeTheCall = req.getMethod();
String localeUsed = req.getLocale().toString();
String strMasjidLocation = null;
//strMasjidLocation = this is where I would like to capture the value from the jsp that called this servlet.
page.append("<HTML><HEAD><TITLE>Multi Form</TITLE></HEAD>");
page.append("<BODY>");
page.append("Hello " + name + "!");
page.append("<BR>");
page.append("The method who called me is: " + methodWhoMadeTheCall);
page.append("<BR>");
page.append("The language used is: " + localeUsed);
page.append("<BR>");
page.append("I am at this location: " + strMasjidLocation);
page.append("</BODY></HTML>");
res.setContentType("text/html");
PrintWriter writer = res.getWriter();
writer.println(page.toString());
writer.close();
}
}
This should work:
String value = (String) req.getSession(false).getAttribute("MasjidLocation")
Don't use scriptlets; that's 1999 style. Learn JSTL and write your JSPs using that.
Your servlets should never, ever have embedded HTML in them. Just validate and bind parameters, pass them off to services for processing, and put the response objects in request or session scope for the JSP to display.
I agree with duffymo that you should learn on newer technology (if this is applicable, maybe your client cannot allow that...). Anyway, to get the value of the attribute you owuld do:
strMasjidLocation = (String)req.getSession().getAttribute("MasjidLocation");
Also, I notice you have two different paths for your servlets in your HTML < form> tags:
MyWebArchive/MulitProcessorServlet
and
Week05WebArchive/MulitProcessorServlet
Is it expected?
You used Session not Request.
you may need to get Session from request.
String strMasjidLocation = request.getSession().getAttribute("MasjidLocation");