how to send data from servlet to Jsp using request dispatcher - java

servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
System.out.println("Received Value: " + request.getRequestURL());
response.getWriter().append("Decoded string: ").append(
Utils.getDataFromFeedbackLink(request.getPathInfo().substring(1, request.getPathInfo().length())));
String decodeValue = Utils
.getDataFromFeedbackLink(request.getPathInfo().substring(1, request.getPathInfo().length()));
request.setAttribute("finalData", decodeValue);
RequestDispatcher rd = request.getRequestDispatcher(decodeValue);
rd.forward(request, response);
}
jsp:
<body>
Hello World ::::
<%=request.getAttribute("finalData")%>
</body>
web.xml
<servlet>
<servlet-name>SubmitFeedbackServlet</servlet-name>
<description></description>
<servlet-class>com.techjini.tfs.servlets.SubmitFeedbackServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SubmitFeedbackServlet</servlet-name>
<url-pattern>/submitfeedback/*</url-pattern>
</servlet-mapping>
i am getting value but when i try to send value from Servlet to Jsp then each time same servlet loaded so am unable to get value inside jsp please suggest me how to get value from servlet to jsp using request dispatcher or some thing i did wrong please point me where am doing mistake .

If you store some data in request attribute in will be seen on forwarded page. Just set req.setAttribute("key", "value") and it will be visible on destination page via ${"key"}

in the line "RequestDispatcher rd = request.getRequestDispatcher(decodeValue);"
the decodeValue should contain the name of the jsp file . can you check that by printing the value of decodeValue on console.

Related

Jsp servlet - login page is not redirecting properly

I am trying to create a login service but my pages are not redirecting properly. I have following:
login.jsp
<form action="login" method="post">
User Name
<br>
<input type="text" name="userId"/>
<br><br>
Password
<br>
<input type="password" name="password"/>
<br><br>
<input type="submit"/>
</form>
LoginServlet.java
package org.sohail.javabrains;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userId, password;
userId=request.getParameter("userId");
password=request.getParameter("password");
LoginService loginService = new LoginService();
boolean result = loginService.authenticate(userId, password);
if (result) {
RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/success.jsp");
dispatcher.forward(request, response);
return;
}
else {
response.sendRedirect("login.jsp");
return;
}
}
}
LoginService.java - has a authenticate(userId, password) method which connects to database, verifies userId and pass and returns a boolean value.
web.xml
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>org.sohail.javabrains.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
from login.jsp page, doesn't matter what I put I get following error:
HTTP Status 404 - /LoginApp/login
It should redirect the page to success.jsp if authenticate() reutrns true.
I am pretty new to this so please feel free to provide any other suggestions.
Thank you Birgit Martinelle for following answer:
change your web.xml servlet mapping to
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
and remove the WEB-INF part from your redirect url:
RequestDispatcher dispatcher = request.getRequestDispatcher("success.jsp");
– Birgit Martinelle 50 mins ago

Java Servlet looping when forwarded to jsp

I'm trying to convert a Java class to be displayed on a web page. Using the top answer here as a guideline. The Java does what it's supposed to if I print everything out with System.out. When trying to forward to a jsp page, it loops (re-instantiates?), and doesn't stop (have to manually kill the process).
Connector.java
public class Connector extends HttpServlet {
private static URL url = https://my.server.com/WEB-INF/ws/service.php?wsdl");;
private static final String USERNAME = "JoeBoB";
private static final String PASSWORD = "1337pass";
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//login to my.server.com
try {
authToken = serverAPI.login(USERNAME, PASSWORD);
System.out.println("Logged into server with Token: " + authToken);
//this shows up in console over and over again, until manually killed
}
catch (Exception ex) {
ex.printStackTrace();
}
request.setAttribute("message","bacon");
request.getRequestDispatcher("/WEB-INF/draw.jsp").forward(request, response);
//line above appears to be the one that re-inits the class.
//commenting this out stops the looping
//but also prevents the data from showing on the webpage
serverAPI.logout(authToken);
WEB-INF/draw.jsp
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>This is my drawn page</title>
</head>
<body>
${message}
</body>
</html>
WEB-INF/web.xml
<web-app>
<display-name>Connector</display-name>
<servlet>
<servlet-name>Connector</servlet-name>
<servlet-class>com.company.package.Connector</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Connector</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
I have a feeling it's somewhat simple (something I forgot to configure, or misconfigured), but for the life of me can't figure out what.
By mapping /* to your servlet you are overriding the default handler for JSP requests. You need to use a more specific pattern, using a file extension or subdirectory.

Sending a variable from Servlet to JSP

I got a question about servlets and jsp.
Servlet:
public class Servlet extends javax.servlet.http.HttpServlet {
protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
Integer i = new Integer(15);
request.setAttribute("var", i);
RequestDispatcher Dispatcher = getServletContext().getRequestDispatcher("/index.jsp");
Dispatcher.forward(request, response);
}
JSP page:
<html>
<head>
<title></title>
</head>
<body>
<form id="id" method="get" action="servlet">
<%= (request.getAttribute("var")) %>
</form>
</body>
</html>
As a result I expect to see 15, but I see null. Why does it happen?
Request parameters are sent from the view to the controller, request attributes are used to pass data in the current request to help build the new response. So, you should not use scriplets and access to the request attributes by using Expression Language:
<body>
<!-- No need to use a form for this page -->
The request attribute: ${var}
</body>
Note that by your current request, you should perform a GET request on your servlet. Since your servlet name is servlet (which I suggest your to change it immediately), you should access to this URL: http://yourServerName/yourApplicationName/servlet
Use request.getAttribute("var");
I don't know in the servlet but in struts 2 you need getter and setter method to sent data from jsp, you try this:
public class Servlet extends javax.servlet.http.HttpServlet
{
private Integer i;
protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
i = new Integer(15);
request.setAttribute("var", i);
RequestDispatcher Dispatcher = getServletContext().getRequestDispatcher("/index.jsp");
Dispatcher.forward(request, response);
}
public Integer getI()
{
return i;
}
public void setI(Integer i)
{
this.i = i;
}
}//also lacked this

Urlrewriting using Servlet

I am new to programming and i have written two pieces of code to learn urlrewriting in servlet:
My html form is :
<form action="loginhidden" method="get">
Login ID:<input name="login" ><br>
Password:<input name="pass" type="password"><br>
<input type="submit" >
</form>
My web.xml file is :
<web-app>
<servlet>
<servlet-name>loginhidden</servlet-name>
<servlet-class>loginhidden</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginhidden</servlet-name>
<url-pattern>/loginhidden</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>loginhidden1_name</servlet-name>
<servlet-class>loginhidden1_name</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginhidden1_name</servlet-name>
<url-pattern>/loginhidden1_name/*</url-pattern>
</servlet-mapping>
</web-app>
The pieces of code are as follows:
1.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class loginhidden extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String login= req.getParameter("login");
String pass=req.getParameter("pass");
if(pass.equals("admin"))
{
out.println(login);
out.println(pass);
out.println("<html><head><form action=loginhidden1_name?
mylogin="+login+">");
out.println("Your Name:<input type=text name=myname><br>");
out.println("<input type=submit>");
out.println("</body></head></html>");
}
}
}
2.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class loginhidden1_name extends HttpServlet{
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res )throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println(req.getParameter("mylogin"));
out.println(req.getParameter("myname"));
}
}
I am able to get the value of name in my second servlet(loginhidden1_name) but i am not able to get the value of login id("mylogin") through urlrewriting.I am getting null value for it.Please Help.
Thanks a lot in Advance.
If you're just looking to transfer control from one servlet to another, it's a simple matter of forwarding the request to the other servlet. A "forward" in this case does not go back to the client.
In your original servlet, at the end, you'll want to get a RequestDispatcher, and forward to the new URL.
e.g.
getServletContext().getRequestDispatcher("/modified/url").forward(request, response);
The thread of control will transfer to the other servlet. IIRC, you will still finish out the method call in the first servlet. i.e. it doesn't return from your method and then call the other servlet.
You can take advantage of this if you need post processing of the request for some reason. Although a ServletFitler would be a more appropriate way to handle this case.
You cannot can use URL rewriting in a form action. Any parameters after ? will be dropped by the browser. Instead you can add the login as a hidden form field in your second form:
...
out.println("<input type=hidden name=\"mylogin\" value=\""+login+"\">");
...
This will be passed through to your second Servlet in the same way as the other fields.
See submitting a GET form with query string params and hidden params disappear

HTTP status 405 - HTTP method POST is not supported by this URL

I am getting this "HTTP method POST is not supported by this URL" error when I run my project. The funny thing is, it was running perfectly fine two days ago. After I made a few changes to my code but then restored my original code and its giving me this error. Could you please help me?
Here is my index.html:
<form method="post" action="login.do">
<div>
<table>
<tr><td>Username: </td><td><input type="text" name="e_name"/>
</td> </tr>
<tr><td> Password: </td><td><input type="password" name="e_pass"/>
</td> </tr>
<tr><td></td><td><input type="submit" name ="e_submit" value="Submit"/>
Here is my Login servlet:
public class Login extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/*
* TODO output your page here. You may use following sample code.
*/
int status;
String submit = request.getParameter("e_submit");
String submit2 = request.getParameter("a_submit");
out.println("Here1");
String e_name = request.getParameter("e_name");
String e_password = request.getParameter("e_pass");
String a_name = request.getParameter("a_name");
String a_password = request.getParameter("a_pass");
out.println(e_name+e_password+a_name+a_password);
Author author = new Author(a_name,a_password);
Editor editor = new Editor(e_name,e_password);
// If it is an AUTHOR login:
if(submit==null){
status = author.login(author);
out.println("Author Login");
//Incorrect login details
if(status==0) {
out.println("Incorrect");
RequestDispatcher view = request.getRequestDispatcher("index_F.html");
view.forward(request, response);
}
//Correct login details --- AUTHOR
else {
out.println("Correct login details");
HttpSession session = request.getSession();
session.setAttribute(a_name, "a_name");
RequestDispatcher view = request.getRequestDispatcher("index_S.jsp");
view.forward(request, response);
}
}
//If it is an EDITOR login
else if (submit2==null){
status = editor.login(editor);
//Incorrect login details
if(status==0) {
RequestDispatcher view = request.getRequestDispatcher("index_F.html");
view.forward(request, response);
}
//Correct login details --- EDITOR
else {
out.println("correct");
HttpSession session = request.getSession();
session.setAttribute(e_name, "e_name");
session.setAttribute(e_password, "e_pass");
RequestDispatcher view = request.getRequestDispatcher("index_S_1.html");
view.forward(request, response);
} }
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}}
And my web.xml looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>2</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>controller.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/login.do</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
I use Glassfish v3 server - let me know anything else you need to know
That's because on your doGet() and doPost() method, you're calling it's super methods. Rather, call the processRequest() inside the respective methods mentioned above.
The super.doGet() and super.doPost() method, returns an HTTP 405, by default, so you don't call your superclass doGet() and doPost().
Why is there a processRequest method in your code? Who will call that method?
You can't get up to that method by calling super.doGet() or super.doPost()
you need to call that method explicitly.
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
processRequest(req,resp)
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
processRequest(req,resp)
}
EDIT
Do this
response.sendRedirect("index_F.html");
return;
instead of
RequestDispatcher view = request.getRequestDispatcher("index_F.html");
view.forward(request, response);
Inside doPost() you have to call processRequest().
You're calling doGet() and doPost() method without actually implementing (using super).
The HttpServlet basically follows the template method pattern where all non-overridden HTTP methods returns a HTTP 405 error "Method not supported". When you override such a method, you should not call super method, because you would otherwise still get the HTTP 405 error. The same story goes on for your doPost() method.
Call the processRequest(req,resp) inside the respective methods mentioned above.
EDIT:
Second,
Do not use dispatcher to forward request to HTML. Use redirect anyway if you want to show html only.
response.sendRedirect("index_F.html");
return;
Also, It is good practice to use redirect when you do Logout or send back for invalid credentials.

Categories

Resources