Reputation: 101
Hi I have a servlet class like this
public class DBConnection extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
resp.setContentType("text/html");
req.setAttribute("Message","Message from servlet page");
req.getRequestDispatcher("/index.jsp").forward(req,resp);
}
}
calling servlet on index.jsp page like this
<% String Msg= (String)request.getAttribute("Message");
out.println("<p> Servlet communicated message to JSP: "+ Msg + "</p>");%>
This in my web.xml file
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>dbconnection</display-name>
<welcome-file-list>
<welcome-file>Login.html
</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>DBConnection</servlet-name>
<servlet-class>DBConnection</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DBConnection</servlet-name>
<url-pattern>/DBConnection</url-pattern>
</servlet-mapping>
</web-app>
I am getting a null value .. can anyone help me?
Upvotes: 1
Views: 1576
Reputation: 21
You are not calling your servlet in url that you are trying to invoke Try as suggested by Yubi.
Example: If your url pattern is
<url-pattern>/TestingServlet</url-pattern>
in your web.xml
to execute your servlet get/post in that servlet u should use urlpattern
`http://yourserverhost:port/ServletTest/TestingServlet`
ServletTest is your application context and TestingServlet is your url pattern for your Servlet.
<servlet>
<description></description>
<display-name>TestingServlet</display-name>
<servlet-name>TestingServlet</servlet-name>
<servlet-class>TestingServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestingServlet</servlet-name>
**<url-pattern>/TestingServlet</url-pattern>**
</servlet-mapping>
Upvotes: 0
Reputation: 3988
You are getting null value because you are not accessing with right url.
Suppose you have url like following:
http://localhost:8080/TestWeb/
where your project name is TestWeb
. If you had tried with above url you are getting null
value because request is not comming from servlet. So you need to use like following url
http://localhost:8080/TestWeb/DBConnection
Then only you will get right output. Please try it.
Upvotes: 1
Reputation: 56
You can access the attributes defined in the servlet using Expression Language.
Inside JSP:
<p> Servlet communicated message to JSP: ${Message} </p>
Servlet:
RequestDispatcher rd;
resp.setContentType("text/html");
req.setAttribute("Message","Message from servlet page");
rd = req.getRequestDispatcher("/index.jsp");
rd.forward(req,resp);
Upvotes: 0