sending data from java servlet to jsp - java

I am trying to send a string from a Java servlet to JSP but I always get a null in the string
Test.java servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String s = "HelloWolrd";
System.out.println(s);
response.setContentType("text/jsp");
request.setAttribute("s", s);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/test.jsp");
dispatcher.forward(request,response);
}
test.jsp
<body><%= request.getAttribute("s")%> </body>
web.xml has servlet class mapped to apis. Test and url-pattern as /test.

The test.jsp file is placed outside the WEB-INF as per your project structure. Validate it again.
Servlet:
public class Test extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String s = "HelloWolrd";
System.out.println(s);
response.setContentType("text/jsp");
request.setAttribute("s", s);
RequestDispatcher dispatcher = getServletContext()
.getRequestDispatcher("/test.jsp"); // CHANGE IT HERE
dispatcher.forward(request, response);
}
}
web.xml:
<servlet>
<servlet-name>XYZ/servlet-name>
<servlet-class>apis.Test</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>XYZ</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
Have a look at my another post How does a servlets filter identify next destination is another filter or a servlet/jsp? for detailed description on Servlet Matching Procedure used for url-pattern.
Note: Always try to avoid Scriplet instead use JavaServer Pages Standard Tag Library and Expression Language.

Also as per your eclipse directory structure you have your JSP under WebContent folder. So you need to do
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/traders/test.jsp");
Few other thing you can try
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/traders/test.jsp?s=s");
and then in your JSP you can do
<%= request.getAttribute("s")%>
OR
you can use Session
HttpSession session = request.getSession(true);
session.setAttribute("s", "s");
and do
<%= session.getAttribute( "s" ) %>

Related

Java-EE redirect to a custom error page

Is there way to include error page for any wrong path request?
I need all wrong path requested by the user to be sent to error.jsp
For example if "/example" is part of the web.xml then it would send to localhost:8080/example
If user specifies localhost:8080/examp then it would redirect to error.jsp
I tried the following code in the web.xml and created a error.jsp inside Web Pages directory in Netbeans and it still sent me to yahoo error handle page:
<web-app>
<error-page>
<error-code>404</error-code>
<location>/error.jsp</location>
</error-page>
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/error.jsp</location>
</error-page>
</web-app>
error.jsp
<%# page isErrorPage="true" %>
<html>
<head>
<title>Show Error Page</title>
</head>
<body>
<h1>Opps...</h1>
<p>An error occurred.</p>
</body>
</html>
First create a custom servlet and use it for both exceptions and errors. Refer the below code.
#WebServlet("/AppExceptionHandler")
public class AppExceptionHandler extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processError(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processError(request, response);
}
private void processError(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// Analyze the servlet exception
Throwable throwable = (Throwable) request
.getAttribute("javax.servlet.error.exception");
Integer statusCode = (Integer) request
.getAttribute("javax.servlet.error.status_code");
String servletName = (String) request
.getAttribute("javax.servlet.error.servlet_name");
if (servletName == null) {
servletName = "Unknown";
}
String requestUri = (String) request
.getAttribute("javax.servlet.error.request_uri");
if (requestUri == null) {
requestUri = "Unknown";
}
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.write("<html><head><title>Exception/Error Details</title></head><body>");
if(statusCode != 500){
out.write("<h3>Error Details</h3>");
out.write("<strong>Status Code</strong>:"+statusCode+"<br>");
out.write("<strong>Requested URI</strong>:"+requestUri);
}else{
out.write("<h3>Exception Details</h3>");
out.write("<ul><li>Servlet Name:"+servletName+"</li>");
out.write("<li>Exception Name:"+throwable.getClass().getName()+"</li>");
out.write("<li>Requested URI:"+requestUri+"</li>");
out.write("<li>Exception Message:"+throwable.getMessage()+"</li>");
out.write("</ul>");
}
out.write("<br><br>");
out.write("Home Page");
out.write("</body></html>");
}
}
Then configure it in deployment descriptor which is your web.xml
<welcome-file-list>
<welcome-file> index.html</welcome-file >
</welcome-file-list>
<error-page>
<error-code> 404</error-code>
<location> /AppExceptionHandler</location >
</error-page>
<error-page>
<exception-type> javax.servlet.ServletException</exception-type>
<location>/AppExceptionHandler</location >
</error-page>
<error-page>
<exception-type >java.lang.Throwable </exception-type>
<location >/AppExceptionHandler </location>
when a exception occures it will call the AppExceptionHandler class and then it will cause to display a custom error page.

Sessions showing null error

I have a JSP page, say xyz.jsp in which I've set a session
request.getSession().setAttribute("path", loc);
and in a.java I've used this session successfully and sent response back to jsp page,
String fpath = request.getSession().getAttribute("path").toString();
But, when I to use the same session value in b.java I am getting null pointer exception.
my.jsp->on button click->a.java->get session1->send response to my.jsp->my.jsp reloads->b.java trying to use session1->NullPointerExceptionError
I've tried,
Using different session variables
session.setAttribute("session1", loc);
session.setAttribute("session2", loc);
Creating a new session variable in a.java and access the same in b.java
Still with the same error.
my.jsp looks like,
String loc = "/u/poolla/workspace/FirstServlet/WebContent/WEB-INF/" + ip +"/" +timeStamp;
session.setAttribute("path", loc);
a.java looks like
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session = request.getSession();
String fpath = session.getAttribute("path").toString();
if(!new File(fpath).exists())
{
File uploadedFile = new File(fpath, fileName);
item.write(uploadedFile);
two_file = "Right file " +fileName;
request.setAttribute("file2", two_file);
String f2 = "<span class='blue'>" +"Uploaded file " +fileName+ " at " +uploadedFile.getAbsolutePath()+ "<br>" + "</span>";
request.setAttribute("f2stat", f2);
}
RequestDispatcher rd = request.getRequestDispatcher("geco.jsp");
rd.forward(request, response);
b.java looks like
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session = request.getSession();
String b = session.getAttribute("path").toString();
File file = new File(b);
if(!file.exists())
{
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write("hi");
bw.close();
}
This is just to help you with the problem. What i mean to say is using the scriptlets in jsp, the naming conventions, using two servlets in this scenario are all not recommended..
code snippets
web.xml
<servlet>
<servlet-name>myservleta</servlet-name>
<servlet-class>com.examples.example.MyServletA</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>myservletb</servlet-name>
<servlet-class>com.examples.example.MyServletB</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>myservleta</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>myservletb</servlet-name>
<url-pattern>*.go</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
index.jsp
<body>
<%
session.setAttribute("location", "tvm");
%>
<form action="gotoajava.do" method="post">
<input type="Submit" />
</form>
</body>
page2.jsp
<body>
<form action="gotobjava.go" method="get">
<input type="Submit" />
</form>
</body>
MyServletA.java
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String loc = request.getSession().getAttribute("location").toString();
System.out.println("location in ServletA from session is " + loc);
RequestDispatcher rd = request.getRequestDispatcher("geco.jsp");
rd.forward(request, response);
}
MyServletB.java
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
String loc = session.getAttribute("location").toString();
System.out.println("location in ServletB from session is " + loc);
}
Console log:
Mar 20, 2014 9:28:33 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 343 ms
location in ServletA from session is tvm
location in ServletB from session is tvm
edit: The jsp that performs 'gotobjava.go' action is renamed to page2.jsp as per OP's edit request

browser shows 404 error [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
I am new to servlet and making my first servlet using eclipse.I have made Index.html, Login.java and WelcomeServlet.java. But whenever I am trying to access the using
localhost:8080/ServletExample/
It shows 404 error.Here are the codes..
Index.html
<form action="Login" method="post">
Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPass"/><br/>
<input type="submit" value="login"/>
</form>
Login.java
public class Login extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
if(p.equals("servlet")) {
RequestDispatcher rd=request.getRequestDispatcher("WelcomeServlet");
rd.forward(request, response);
} else {
out.print("Sorry UserName or Password Error!");
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request, response);
}
}
}
WelcomeServlet.java
package java.io;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class WelcomeServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/WelcomeServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
package java.io;
why u put this line in WelcomeServlet.java.
You're mapping to 'WelcomeServlet' not 'ServletExample'.
Try going to localhost:8080/WelcomeServlet
EDIT: There shouldn't be a trailing slash, sorry!
Make sure ur projrct name is ServletExample.
localhost:8080/ServletExample/index.html

How can I pass object from servlet to JSP? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to pass an Object from the servlet to the calling JSP
How can I pass object from servlet to JSP?
I have used the following code in the servlet side
request.setAttribute("ID", "MyID");
request.setAttribute("Name", "MyName");
RequestDispatcher dispatcher = request.getRequestDispatcher("MangeNotifications.jsp");
if (dispatcher != null){
dispatcher.forward(request, response);
}
and this code in JSP side
<td><%out.println(request.getAttribute("ID"));%> </td>
<td><%out.println(request.getAttribute("Name"));%> </td>
I get null results in the JSP Page
I think servlet's service (doGet/doPost) method is not requested. In order to access request attributes in JSPs, you must request the servlet via url-pattern and that way you don't have to use session.
SampleServlet.java
#WebServlet(name = "SampleServlet", urlPatterns = {"/sample"})
public class SampleServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("ID", "MyID");
request.setAttribute("Name", "MyName");
RequestDispatcher dispatcher = request
.getRequestDispatcher("/MangeNotifications.jsp");
if (dispatcher != null){
dispatcher.forward(request, response);
}
}
}
MangeNotifications.jsp (I presume that this file is located at root of web-context)
<br/>ID : ${ID} Or scriptlets <%-- <%=request.getAttribute("ID")%> --%>
<br/>ID : ${Name}
Now open the browser and set request url somersetting like this,
http://localhost:8084/your_context/sample
Put it in the session (session.setAttribute("foo", bar);) or in the request; then it is accessible from the JSP through the name you gave it ("foo" in my example).
EDIT :
Use simply <%= ID %> and <%= Name %> instead of <%out.println.....%>. Note the = at the beginning of the java tag, indicating to output the result of the expression.

Java EE: Getting parameters from POST for a login form

I am trying to implement a simple login servlet but it's not working properly.
What I wanted to know is how to pass the parameters using a HTTP POST. It already works with HTTP GET but the username and password are visible from the URL. It would be better to hide them in a POST.
<form method="post" action="home" >
<input name="username" class="form-login" title="Username" value="" size="30" maxlength="2048" />
<input name="password" type="password" class="form-login" title="Password" value="" size="30" maxlength="2048" />
<input type="submit" value="Connect">
</form>
web.xml
<servlet>
<servlet-name>home</servlet-name>
<servlet-class>controller.HomeController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>home</servlet-name>
<url-pattern>/home</url-pattern>
</servlet-mapping>
Servlet:
public class HomeController extends HttpServlet {
private HttpSession session;
private UserBean userBean;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
UserBean user = new UserBean();
String userName = request.getParameter("username");
String password = request.getParameter("password");
user.setUsername(userName);
user.setPassword(password);
user = UserDAO.login(user);
dispatch(request, response, ApplicationRessource.getInstance().getHomePage());
}
protected void dispatch(HttpServletRequest request,
HttpServletResponse response, String page)
throws javax.servlet.ServletException, java.io.IOException {
RequestDispatcher dispatcher = getServletContext()
.getRequestDispatcher(page);
dispatcher.forward(request, response);
}
}
The problem is that the userName and password strings are always empty, meaning that the parameters are never fetched from the POST. What am I doing wrong?
it should work, can you check by changing form method to get and trying, you should see parameters in url.
Please try this
In your doPost(..) method code only doGet(..) and put all your logic in doGet(..) and check if still it is giving blank values.
Let me know what is the output.
Example:-
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
UserBean user = new UserBean();
String userName = request.getParameter("username");
String password = request.getParameter("password");
user.setUsername(userName);
user.setPassword(password);
user = UserDAO.login(user);
dispatch(request, response, ApplicationRessource.getInstance().getHomePage());
}
this simple implementation should have worked ..but since its not, there maybe some code which is manipulating the request. The code you have posted is not sufficient to determine that.
Some pointers I can give are -
Check your web.xml to see if there is any filter/interceptor which is manipulating the request.
Which web/app server are you using? Have you checked the service(Http...) method implementation of HttpServlet. You can try placing a debug point in service(..) method to see if the request object here has the required request parameters. If it doesn't, then the problem exists either in some filter or your jsp itself.
What does dispatch(request, response, ApplicationRessource.getInstance().getHomePage()); do? I know the problem is before this line, but this is not a standard HttpServlet method, so I assume there's lot more custom code then whats been posted in the question above.

Categories