for loop on ArrayList change the object - java

I have a jsp page (says , MyJspPage.jsp) -
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<%
ArrayList<Person> ownerList = (ArrayList<Person>) request
.getAttribute("ownerList");
//set again ..
request.setAttribute("ownerList",ownerList) ;
%>
</head>
<body>
<%
//itr on all the persons ..;
for (Person person : ownerList) {
%>
// some HTML code..
<%
}
%>
<form action="servlet123" method="POST">
// some fields ..
<input type="submit" value="join" />
</form>
</body>
</html>
And a servlet -
#WebServlet("/servlet123")
public class servlet123 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// get the then set ..
ArrayList<Person> ownerList = (ArrayList<Person)request.getAttribute("ownerList");
request.setAttribute("ownerList", ownerList);
// forward to `MyJspPage.jsp`
dispather.forward(request, response);
}
}
Firstly another servlet forward to MyJspPage.jsp and it work fine , then there is like ping pong between MyJspPage.jsp and servlet123 . The problem is that when at the 2nd time reachs to MyJspPage.jsp it throws an exception -
type Exception report
message java.lang.NullPointerException
description The server encountered an internal error (java.lang.NullPointerException) that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: java.lang.NullPointerException
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:549)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:470)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
It should be noted that when I omit the for loop from MyJspPage.jsp and change it to be -
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<%
ArrayList<Person> ownerList = (ArrayList<Person>) request
.getAttribute("ownerList");
//set again ..
request.setAttribute("ownerList",ownerList) ;
%>
</head>
<body>
<form action="servlet123" method="POST">
// some fields ..
<input type="submit" value="join" />
</form>
</body>
</html>
all the relation between MyJspPage.jsp and servlet123 returns work fine .

This is one approach.
JSP Code is as follows
Instead of setting the arraylist again in the request, you can set it in session as follows
session.setAttribute("ownerList",ownerList) ;
You can check for the arraylist to be NOT null before using it in the for loop.
if (ownerList != null)
{
for (Person person : ownerList) {
%>
// some HTML code..
<%
}
}
%>
In the servlet you can write the code as
HttpSession session = request.getSession(false);
ArrayList<Person> ownerList = (ArrayList<Person)session.getAttribute("ownerList");
request.setAttribute("ownerList", ownerList);
session.setAttribute("ownerList", null); // toremove unnecessary code from the session
There could be other approach also. This one is just closer to the one you chose.

Related

Need help in passing converted text to voice from servelet to jsp page

I want my servlet page to retrieve the information provided in textarea of jsp page
and convert that text into voice and return to the jsp page.
This piece of code is giving me this error
org.apache.catalina.core.StandardWrapperValve invokeSEVERE: Servlet.service() for servlet [Myclass] in context with path [/test] threw exception [Servlet execution threw an exception] with root cause java.lang.ClassNotFoundException: com.sun.speech.freetts.VoiceManager at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1365)
Any help or suggestion will be appreciated.
servlet page (Myclass.java)
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//2nd approach
final String VOICENAME ="kevin16" ;
String button = request.getParameter("button");
Voice voice;
VoiceManager vm= VoiceManager.getInstance();
voice =vm.getVoice(VOICENAME);
voice.allocate();
if ("text".equals(button)) {
try {
voice.speak(request.getParameter("box"));
}
catch( Exception e){
System.out.println(e.getMessage());
}
System.out.println("line 5");
request.getRequestDispatcher("NewFile.jsp").forward(request, response);
}
}
}
jsp page (NewFile.jsp)
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="Myclass" enctype="multipart/form-data">
<textarea name ="box" rows="4" cols="50">
</textarea>
<button value="text" name ="button" type="submit" >Click Me!</button>
</form>
</body>
</html>

Display the calculation of servlet before forwarding it to jsp [duplicate]

HTML code appears when I try to execute the jsp page. This appears in the browser.
I tried to change the contentType and language in the tag. But it did not work.
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<HTML>
<HEAD> <TITLE> The Welcome JSP </TITLE> </HEAD>
<BODY>
<H3> Welcome! </H3>
<P><B> Today is <%= new java.util.Date() %>. Have a nice day! </B></P>
</BODY>
</HTML>
This is my servlet code.
public class Add extends HttpServlet {
public void service(HttpServletRequest rq, HttpServletResponse rs)throws IOException, ServletException
{
int i=Integer.parseInt(rq.getParameter("t1"));
int j=Integer.parseInt(rq.getParameter("t2"));
int k=i+j;
PrintWriter out=rs.getWriter();
out.println("The sum is:"+k);
RequestDispatcher rd=rq.getRequestDispatcher("/Welcome.jsp");
rd.include(rq,rs);
}
}
I want the code to get rendered and view the output.

Variables not making it from one JSP to the other when using HttpSession

I am having trouble retrieving any type of parameter from one jsp page to the other using doPost, and a form where my method is post. Note below is a minimal example.
First, I have two pages:
Here is search.jsp:
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<!DOCTYPE html>
<html>
<head>
<title>search</title>
<body>
<form name="search" method="post" action="search_results.jsp">
<p>
<input type="text" class="inputTitle" id="inputTitle" value="${fn:escapeXml(param.inputTitle)}">
<button type="submit">Search</button>
<p>
</form>
</body>
</html>
And my search_results.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<title>search results</title>
<body>
<p>Title: ${movie.title}</p>
</body>
</html>
Now I have a class called SearchServlet.java:
#WebServlet("/search")
public class SearchServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
HttpSession session = request.getSession();
request.getRequestDispatcher("search.jsp").forward(request,response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
HttpSession session = request.getSession();
String title = request.getParameter("inputTitle");
String searchTitle;
try {
if(title != null && !title.isEmpty()) {
searchTitle = "hello";
} else {
searchTitle = "world";
}
session.setAttribute("movie.title", searchTitle);
request.getRequestDispatcher("search_results.jsp").forward(request, response);
} catch(ServletException e) { e.printStackTrace(); }
}
}
No matter what I enter the result (movie.title) always ends up being empty and so I get world on search_results.jsp. Why is my parameter not being passed to search_results.jsp?
It will not happen if you bypass the servlet
Look at your form action
<form name="search" method="post" action="search_results.jsp">
You are sending the post request directly to the search_results.jsp: you should send it to the servlet instead (mapped # /search)
<form name="search" method="post" action="search">
Then from the servlet you should forward the request to the search_result.jsp, which you actually did.
In addition to that when you call request.getParameter you have to keep in mind that what counts is the name of the input field, not the id. You should change the id attribute to name
<input type="text" class="inputTitle" name="inputTitle" value="${fn:escapeXml(param.inputTitle)}">
Lastly, hopefully :) the '.' (dot) might cause issues:
session.setAttribute("movie.title", searchTitle);
When you retrieve the attribute the dot notation indicates that you are accessing a field in a object called movie
<p>Title: ${movie.title}</p> <!-- you are accessing the title property of a movie object !-->
but you do not have that...you have a movietitle, a String presumably. Change the attribute name to something like movietitle without the dot and retrieve it in the jsp the same way. the above lines will become:
session.setAttribute("movietitle", searchTitle);
<p>Title: ${movietitle}</p>
That should solve the issue.

Request a variable defined in jsp from servlet? [duplicate]

This question already has an answer here:
Authentication filter and servlet for login
(1 answer)
Closed 6 years ago.
The username of the person who logs in is present on the index page and the code works fine. But trying to access the variable username from the servlet is proving hard. Any ideas?
index.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title><%=request.getParameter("username")%> - Cloud</title>
<link rel="stylesheet" href="css/bootstrap.css">
</head>
<header class="page-header">
<% String username = request.getParameter("username");%> // How can i get this variable?
<h1 align="center" class="inline"><%=username%> - Files</h1>
</header>
<body>
Servlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
}
?
You have to call the servlet through the jsp page
How to call servlet through a JSP page
This is an official example from oracle of how to do that:
Jsp2Servlet.jsp
<HTML>
<HEAD> <TITLE> JSP Calling Servlet Demo </TITLE> </HEAD>
<BODY>
<!-- Forward processing to a servlet -->
<% request.setAttribute("empid", "1234"); %>
<jsp:include page="/servlet/MyServlet?user=Smith" flush="true"/>
</BODY>
</HTML>
MyServlet.java
public class MyServlet extends HttpServlet {
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
PrintWriter out= response.getWriter();
out.println("<B><BR>User:" + request.getParameter("user"));
out.println(", Employee number:" + request.getAttribute("empid") + "</B>");
this.getServletContext().getRequestDispatcher("/jsp/welcome.jsp").
include(request, response);
}
}
welcome.jsp
<HTML>
<HEAD> <TITLE> The Welcome JSP </TITLE> </HEAD>
<BODY>
<H3> Welcome! </H3>
<P><B> Today is <%= new java.util.Date() %>. Have a nice day! </B></P>
</BODY>
</HTML>
The key is in the line:
<jsp:include page="/servlet/MyServlet?user=Smith" flush="true"/>
In this example a jsp call a servlet a that servlet call another jsp. The example is from this page:
https://docs.oracle.com/cd/A87860_01/doc/java.817/a83726/basics4.htm

Reload a jsp page from servlet when form data is involved

I have a jsp that calls a servlet. This servlet does some tasks and then I want to return to the page I was just at and reload it. This would be simple if I knew the exact url it would be each time using the redirectUrl. However, I can't hard code a value in this as it is dynamically created. Is there a way to do this when the previous url is Not known to me?
I am not sure if I understood you correctly, do you need move from jsp to servlet, and return to the same jsp? If this is what you need, I would put some hidden input in jsp form with path
<input type="hidden" name="jspPath" value="${pageContext.request.requestURI}"/>
So full solution is below:
page1.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
${requestScope.dataFromServlet }
<form action="${pageContext.request.contextPath}/HelloWorldServlet " method="POST">
<input type="hidden" name="jspPath" value="${pageContext.request.requestURI}"/>
<input type="hidden" name="param1" value="value1"/>
<input type="submit" value="Submit">
</form>
</body>
</html>
HelloWorldServlet.java
public class HelloWorldServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String jspPath = request.getParameter("jspPath");
if(jspPath == null || "".equals(jspPath))
jspPath = "errorPage.jsp";
request.setAttribute("dataFromServlet", "Hello World");
RequestDispatcher rd = request.getRequestDispatcher(jspPath);
rd.forward(request, response);
}
}

Categories

Resources