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
Related
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>
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.
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);
}
}
I'm begginer in JSP and I have the following servlet:
#SuppressWarnings("serial")
public class HelloAppIgorServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
RequestDispatcher disp = req.getRequestDispatcher("/mainpage.jsp");
disp.forward(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter pw = resp.getWriter();
pw.print("Test");
pw.close();
}
}
and one JSP file called mainpage.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>
<p>Hello there!<p>
<form action="." method="post">
<input type="text" name="name1" />
<input type="submit" value="name2" />
</form>
</body>
</html>
The problem is that doPost() method doesn't work. It's redirecting me to index.html page when I click the button. I'm sure that problem is not in servlets, so where can it be?
You need to set the appropriate action in <form action="." method="post">. The action is the (relative) URL of the servlet that you defined via <servlet-mapping> in the web.xml.
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.