It calls Servlet by click a href.
<li >privilegeManagement</li>
this code is include in the navigation.jsp which is included in the main.jsp.
then it's my servlet.
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
ProviderDao pd = new ProviderDao();
List<ProviderArchives> list = pd.getArchives();
String str = "chenfeng";
req.setAttribute("list", list);
req.setAttribute("hu" , str);
getServletContext().getRequestDispatcher("/jsp/main.jsp").forward(req,resp);
}
then it's my main.jsp.
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#page import="java.util.*"%>
<%#page import="com.chenfeng.javabean.ProviderArchives"%>
<%# 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=UTF-8">
<title>main</title>
</head>
<body>
<%# include file="navigation.jsp"%>
<div>
<%# include file="management.jsp"%>
</div>
<div>
<%
String k = (String)request.getAttribute("hu");
out.println(k);
%>
<c:forEach items="${list}" var="item">
<tr>
<td>${item.provideID() }</td>
<td>${item.GID }</td>
<td>${item.Gname }</td>
<td>${item.PID }</td>
<td>${item.TEL }</td>
<td>${item.ADDR }</td>
<td>
Modify
Delete
</td>
</tr>
</c:forEach>
</div>
</body>
</html>
then when I run this on server,it shows like this
thank in advance for any help!
Actually,there is no reason for this code.But the eclipse run into problem.The real problem log output after I delete class file in build directory and build it again.
It's quite clear. You set attribute of Request Object while you're forwarding Servlet Context Object.
Instead of:
getServletContext().getRequestDispatcher("/jsp/main.jsp").forward(req,resp);
Write:
req.getRequestDispatcher("/jsp/main.jsp").forward(req,resp);
Related
I can`t understand one thing when i send request to get object by name from db,
it always return me null. I surf all sites try to fix it with session and etc. Nothing to work.
Any ideas?
enter image description here
This is my Servlet class:
#WebServlet(value = "/display", name = "IndexServlet")
public class IndexServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
if(!(request.getParameter("mysql")==null)) {
MySQLRepository sql = new MySQLRepository();
Headline object = sql.getByHeadline(request.getParameter("mysql"), DatabaseConnection.initDatabase());
request.setAttribute("id", object.getId());
request.setAttribute("headline", object.getHeadline());
RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("out.jsp");
requestDispatcher.forward(request,response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is index.jsp:
<%# page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>MySQLSolrProject</title>
</head>
<!DOCTYPE html>
<body>
<form action="out.jsp" method="get">
<p>Headline:</p>
<label>
<input type="text" name="mysql">
</label>
<%--<br>
<p>Full text:</p>
<label>
<input type="text" name="solr">
</label>--%>
<br><br>
<input type="submit" value="Search" formmethod="get">
</form>
</body>
</html>
This is out.jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Out</title>
</head>
<body>
<h2>Text is:</h2>
<table>
<tr><th>Id</th><th>Headline</th><th></th></tr>
<tr><td><%=session.getAttribute("id")%></td>
<td><%=session.getAttribute("headline")%></td>
</tr>
</table>
<p>Return to search</p>
</body>
</html>
the error was that Tomcat version 10.* didn't want to work with version 4 servlets
I downgraded Tomcat to version 9.* and it worked.
This question already has an answer here:
Servlet send response to JSP
(1 answer)
Closed 3 years ago.
how do i set the jsp file as response in my servlet ?And what kind of expression do i need to use in the jsp page?
this is the form
<html>
<head>
<title>Select your Hobby</title>
</head>
<body>
<form method="POST" action="SelectHobby">
<p> Choose a Hobby:
</p>
<select name="hobby" size="1">
<option>horse skiing
<option>extreme knitting
<option>alpine scuba
<option>speed dating
</select>
<br><br>
<center>
<input type="SUBMIT">
</center>
</form>
</body>
</html>
the servlet
package com.example.web;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class HobbyServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html");
String hobby = request.getParameter("hobby");
}
}
and this is the jsp in wich i want to see the hobby in the body
<html>
<head>
<title>These are your hobbies</title>
</head>
<body>
<%
</body>
</html>
I recomend you to read this post. JSTL will help you. I suppose you mapped your servlet. Here is a quick example:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<form method="POST" action="testservlet">
<p> Choose a Hobby:
</p>
<select name="hobby" size="1">
<option>horse skiing
<option>extreme knitting
<option>alpine scuba
<option>speed dating
</select>
<br><br>
<center>
<input type="SUBMIT">
</center>
</form>
</body>
</html>
The servlet:
#WebServlet(name = "test", urlPatterns = { "/testservlet" })
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
public Test() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String hobby = request.getParameter("hobby");
request.setAttribute("theHobby", hobby);
request.getRequestDispatcher("hobbypage.jsp").forward(request, response);
}
I defined an attribute called theHobby to hold the value from the selected hobby in the first page. I also created a page called hobbypage.jsp where I want to send the value to.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Hobby: ${theHobby}
</body>
</html>
With JSTL you can call the attribute through the name you defined like this ${nameOfAttribute}.
I'm passing an array of beans from servlet to jsp. I also want to send status "onHand" for each bean. I'm using arrayList for the status.
In Servlet:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import pckg.ProductBean;
public class GetProducts extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
PrintWriter out = response.getWriter();
Vector<String[]> v = DBHelper.runQuery("SELECT * FROM SKU;");
ProductBean [] beans = new ProductBean[v.size()];
ArrayList<String> onHand=new ArrayList<String>();
//onHand.add("a");
for(int i=0; i < v.size(); i++) {
String [] tmp = v.elementAt(i);
Vector<String[]> on = DBHelper.runQuery("SELECT on_hand_quantity FROM on_hand where sku='"+tmp[0]+"' ;");
if((on.size())>0){
String [] tmp1 = on.elementAt(0);
if(Integer.parseInt(tmp1[0])>0){
onHand.add("InStock");}
else if(Integer.parseInt(tmp1[0])==0){
onHand.add("MoreOnTheWay");
}
}
beans[i] = new ProductBean(tmp[0],tmp[1],tmp[2],tmp[3],tmp[4],
tmp[5],tmp[8],Double.parseDouble(tmp[6]),Double.parseDouble(tmp[7]));
}
request.setAttribute("p_beans",beans);
request.setAttribute("onHand",onHand);
String toDo = "/WEB-INF/jsp/cameraList.jsp";
RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher(toDo);
dispatcher.forward(request, response);
}
}
In JSP page:
<%# page import = "java.util.*"%>
<%# page import="java.io.*" %>
<%# page import="java.net.*" %>
<%#page import="java.util.ArrayList" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1" />
<link rel="stylesheet" href="../css/cameraList.css" type="text/css"></link>
<script src="../script/jquery.js"></script>
<script src="../script/cameraList.js"></script>
</head>
<body>
<div id="main">
<% ArrayList<String> onHand=(ArrayList<String>) request.getAttribute("onHand");%>
<c:forEach items="${p_beans}" var="item">
<table >
<tr><td rowspan=5><img id="image" src="upload_dir/${item.image}" style="height:350px; width:350px; background-color:yellow";></td>
<td><b> ${item.vendor} ${item.model} ${item.category}</b></td></tr>
<tr><td width=45%> Price:$${item.retail}</td><td>Status:</td></tr>
<c:url value="/servlet/GetProductDetails?" var="myURL">
<c:param name="sku" value="${item.sku}" />
</c:url>
<tr><td><a href="${myURL}" >Get Details</a></td>
<c:url value="/servlet/OrderPage" var="cartURL">
<c:param name="itemID" value="${item.sku}" />
</c:url>
<td>Add To Cart</td></tr>
</table>
</c:forEach>
</div>
</body>
</html>
I get the following error in server:
An exception occurred processing JSP page /WEB-INF/jsp/cameraList.jsp at line 44:
41: <body>
42:
43: <div id="main">
44: <% ArrayList<String> onHand=(ArrayList<String>) request.getAttribute("onHand");%>
45: <c:forEach items="${p_beans}" var="item">
46:
47: <table >
request.getParameter() always return a String and it is basically use to get data from a form submitted by the user or to get the data from query string.
Because you are calling getParameter() , it will return String and therefore you are getting that exception.
As per your question, because you are setting value for onHand field as attribute in request, you should call getAttribute() method in JSP. Return type for getAttribute() is Object.
Cannot cast from String to ArrayList
It seems like your onHand object is of String type which you are setting your servlet/controller class (using request.setAttribute("onHand",onHand)), so you need to typecast to String rather than ArrayList<String> as shown below in your JSP:
<% String onHand= (String)request.getAttribute("onHand"); %>
Also, the important point is that you need to use request.getAttribute(key) to retrieve the objects inside JSP.
<%
String param = request.getAttribute("onHand");
%>
<c:forEach items="${p_beans}" var="item">
<tr>
<td>iterated fields</td>
<td>
..
..
<td><%=param%></td>
</tr>
Data is not printed in the table
Bean class name is address and user_id_fk is retrieved from user_id with the help of session
#RequestMapping("/address")
public ModelAndView address(HttpServletRequest request , HttpServletResponse response ,ModelAndView modelAndView){
HttpSession session=request.getSession();
String user_id_fk = (String)session.getAttribute("user_id");
UMService a = new UMserviceimp();
address ad=new address();
ad.setUser_id_fk(Integer.parseInt(user_id_fk));
ad=a.addr(ad);
modelAndView.addObject("studentbean",ad);
modelAndView.setViewName("address");
return modelAndView;
}
When we use this then the data is printed to the console:
System.out.println("address" +ad.getUser_id_fk());
System.out.println("line_1"+ad.getLine_1());
System.out.println("line_2"+ad.getLine_2());
System.out.println("line_3"+ad.getLine_3());
System.out.println("city"+ad.getCity());
System.out.println("state"+ad.getState());
System.out.println("pincode"+ad.getPin_code());
System.out.println("country"+ad.getCountry());
System.out.println("address_type"+ad.getAddress_type());
<!--address.jsp-->
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding``="ISO-8859-1"%>
<%#page import="com.cms.org.um.bean.address"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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>
<table border="1" align="left">
<tr>
<th>line_1</th>
<th>line_2</th>
<th>line_3</th>
<th>city</th>
<th>state</th>
<th>country</th>
<th>pin_code</th>
<th>address_type</th>
</tr>
<c:forEach items="${studentbean}" var="u">
<tr>
<td>${u.line_1}</td>
<td>${u.line_2}</td>
<td>${u.line_3}</td>
<td>${u.city}</td>
<td>${u.state}</td>
<td>${u.country}</td>
<td>${u.pin_code}</td>
<td>${u.address_type}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
<!-- end snippet -->
To get field value from object "u" you must do something like this:
<c:forEach items="${studentbean}" var="u">
<tr>
<td><%${u.line_1}%></td>
<td><%${u.line_2}%></td>
<td><%${u.line_3}%></td>
<td><%${u.city}%></td>
<td><%${u.state}%></td>
<td><%${u.country}%></td>
<td><%${u.pin_code}%></td>
<td><%${u.address_type}%></td>
</tr>
</c:forEach>
I want to add another user in registration JSP file to my HashMap which is created in my homepage, but it seems the another HashMap is being created when I'm trying to register user.
How to access the HashMap from homepage JSP file in another?
This is my base class:
package com.jakub.spring;
import java.util.HashMap;
public class registeredUsers {
public HashMap<String, String> userSource;
public registeredUsers() {
userSource=new HashMap<String, String>();
}
public void register(String name, String password) {
userSource.put(name, password);
}
public String userExists(String user) {
String passwordFromSource = userSource.get(user);
if(passwordFromSource != null) {
return passwordFromSource;
}else
return "";
}
}
This is my homepage:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page session="true" %>
<html>
<head>
<title>Home</title>
</head>
<body bgcolor="#CCCFFF">
<form method="post" action="validate.jsp">
<p align="left">Podaj login:</p>
<input type="text" name="name" />
<p align="left">Podaj haslo:</p>
<input type="text" name="password" />
<input type="submit" value="Zaloguj" />
</form>
Rejestracja
<jsp:useBean id="registeredUsers"
class="com.jakub.spring.registeredUsers" scope="application"></jsp:useBean>
<%
out.println("Dostepni uzytkownicy w systemie: \n");
out.print(registeredUsers.userSource.keySet());
%>
</body>
</html>
This is my registration page:
<%# page language="java" contentType="text/html; charset=ISO-8859-2"
pageEncoding="ISO-8859-2"%>
<!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-2">
<title>Konto utworzone</title>
</head>
<body>
<jsp:useBean id="registeredUsers"
class="com.jakub.spring.registeredUsers" scope="application"></jsp:useBean>
<%
registeredUsers.register(request.getParameter("name"),request.getParameter("password"));
out.print("Konto zostało utworzone");
out.print(registeredUsers.userSource.keySet());
%>
Powrót do strony glownej
</body>
</html>
Use ConcurrentHashMap instead of HashMap because it's in Application scope and that can be accessed simultaneously by multiple threads at a time and it results in ConcurrentModificationException.
Please have a look at Thread Safe JSP-Servlet Q&A