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.
Related
I just started using JSP and Servlet, so I encountered a really basic problem.
I'm trying to make a request from JSP to servlet, where I set a parameter and then forward the answer from servlet back to the jsp.
Here is the code from my JSP:
<% String s = (String)request.getAttribute("name");
out.println(s);
%>
Here is my code from servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try (PrintWriter out = response.getWriter()) {
request.setAttribute("name", new String("aa"));
this.getServletContext().getRequestDispatcher("/index.jsp").forward(request,response);
}
}
So in the end, the servlet has the value, but my jsp doesn't.
Here you have already declared a String type but you cast it as String also, this is redundant.
<% String s = (String)request.getAttribute("name");
out.println(s);
%>
Also, there's a difference between <%= %> and <% %>. If you want to output the variable into your jsp use the one with the equals (<%= %>). The second line of your scriptlet code would also generate an error. The code you write in your servlet doesn't just continue on the JSP, it's not how it works.
if you want to output the name attribute just do this:
<%= request.getAttribute("name") %>
However since 2010 scriptlets are discouraged (outdated technology).. We use EL and JSTL instead. You should be able to just output the variable like this:
${name}
In your Servlet all you need to do is this:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = "Jane"; //create a string
request.setAttribute("name", name); //set it to the request
RequestDispatcher rs = request.getRequestDispatcher("index.jsp"); //the page you want to send your value
rs.forward(request,response); //forward it
}
EDIT
You asked,
Is there a way to trigger the servlet let s say on a click of a button
or something like that?
Yes, there are multiple ways to do it and it really depends on how you want it setup. An easy way to trigger the servlet on a button click is like this. *(Assuming you have a servlet mapped onto /Testing):
<a href="/Testing">Trigger Servlet<a>
Another way could be with a form:
<form action="Testing" method="get">
<input type="hidden" name="someParameterName" value="you can send values like this">
<button type="submit">Do some magic</button>
</form>
There's also AJAX (which involves javascript). But this is fairly advanced and i don't recommend doing it until you are familiar with normal synchronous http behaviour.
Try without a writer, you don't want two writing contexts to a single response. You are also not using it:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("name", new String("aa"));
this.getServletContext().getRequestDispatcher("/index.jsp").forward(request,response);
}
I think you should call the request dispatcher method using request object. This is how you do it :
RequestDispatcher rs = request.getRequestDispatcher("index.jsp");
rs.forward(request,response);
This question already has answers here:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
(6 answers)
Closed 6 years ago.
Hi every one can any help me ...
i want to list all the data from data base and display to jsp table
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session = request.getSession(true);
try {
Connection con=DataConnection.getconnection();
PreparedStatement pst;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
pst = con.prepareStatement("select * from [user]");
ResultSet rs = pst.executeQuery();
List<User> ee = new ArrayList<User>();
while (rs.next()) {
User e = new User();
e.setName(rs.getString(1));
e.setUserName(rs.getString(2));
e.setPass(rs.getString(3));
ee.add(e);
}
request.getSession().setAttribute("ee", ee);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/user.jsp");
rd.forward(request, response);
} catch (Throwable theException) {
System.out.println(theException);
}
}
this my code it contain the array list and passing it trought request.getSession().setAttribute("ee", ee);
now how to acess this value in jsp and it should display in the from of table
can any give me the sample code for this
Use JSTL
I would suggest to set data in request instead of session.
replace line
request.getSession().setAttribute("ee", ee);
with
request.setAttribute("ee", ee);
than use code below in your JSP
<c:forEach items="${ee}" var="element">
<tr>
<td>${element.col1}</td>
<td>${element.col2}</td>
</tr>
</c:forEach>
You can access the array using ${ee}.
There are serveral ways to iterate using JSTL.
Assuming your User.java contains for example two atributes: name and surname you can access to this information in your JSP with the following code:
<%# page language="java" pageEncoding="UTF-8" contentType="text/html; charset=utf-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:forEach items="${sessionScope.ee}" var="item">
${item.name} - ${item.surname}
</c:forEach>
You should take into account that you are putting your attribute in session. (that's why you have to use ${sessionScope}) Make sure if you want to use session or not.
I have the following servlet:
#WebServlet(name = "Placeholder",urlPatterns = {"/foo"})
public class Placeholder extends HttpServlet {
public static int numbers=5;
HttpSession session;
public void doGet (HttpServletRequest _req, HttpServletResponse _res) throws ServletException, IOException {
/* Refresh session attributes */
session = _req.getSession();
session.setAttribute("wee","ok");
}
}
With the following JSP:
<%#page language="java" contentType="text/html"%>
<%#page import="java.util.*, java.io.*"%>
<%#page import="main.java.Placeholder.*" %>
<html>
<body>
<b><% out.println("wee, printing from java");%></b>
<% out.println("<br/>Your IP address is " + request.getRemoteAddr());
String value = (String) session.getAttribute("wee");
out.println(value);%>
</body>
</html>
I'm surely missing the point somewhere as attribute wee is resolved as null, first time I load the page. If I go to /foo I get empty an page, and after I get back and reload the root page of servlet, wee actually gets its value.
My goal here is to simply print variables from the servlet into the view, no routing needed. Not sure that urlPatterns are needed here, but it does not work for now without this little hack.
UPD. Ok, so I've figured out that whatever route I put in, I need to add some characters in browser, get back and reload the page.
So, the root is 0.0.0.0:8080/webapp
I need to access,say 0.0.0.0:8080/webapp/qwerty , get back to /webapp and refresh the page.
How do I get session instantiated by just going to /webapp?
Why don't I have 404 or 500 on accessing some random unexisting route /webapp/randomstuff?
First configure servlet as welcome file in web.xml. If web.xml not present than create it manually inside WEB-INF folder and put below content inside it.
<welcome-file-list>
<welcome-file>foo</welcome-file>
</welcome-file-list>
than in your servlet dispatch request to your jsp lets say your jsp name is index.jsp than your servlet code would be look like:
#WebServlet(name = "Placeholder",urlPatterns = {"/foo"})
public class Placeholder extends HttpServlet {
public static int numbers=5;
public void doGet (HttpServletRequest _req, HttpServletResponse _res) throws ServletException, IOException {
HttpSession session = _req.getSession();
session.setAttribute("wee","ok");
_res.sendRedirect("index.jsp");
}
}
Now run your servlet you will see output.
Hope this solve your problem!!!
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" ) %>
I want to send data to controller action and I want to get value from action. But I cannot send value and I cannot convert value getting from controller to boolean, string etc..
contact =(List)response.sendRedirect("contact/login.action");
My contactController's login.action is below: (Also, I tried the boolean function)
#RequestMapping(value="/contact/login.action")
public #ResponseBody Map<String,? extends Object> login(#RequestParam Object data) throws Exception {
try{
List<Contact> contacts = contactService.login(data);
return getMap(contacts);
} catch (Exception e) {
}
return null;
}
My jsp codes are below:
<%#page import="com.loiane.web.ContactController"%>
<%#page import=" com.loiane.model.Contact"%>
<%#page import="java.util.List"%>
<%# page language="java" pageEncoding="UTF-8"%>
<%
String result;
List<Contact> contact;
String loginUsername = request.getParameter("loginUsername");
String loginPassword = request.getParameter("loginPassword");
contact =(List)response.sendRedirect("contact/login.action");
out.println(request.getAttribute("message"));
if ((null != loginUsername && loginUsername.length() > 0) && (null != loginPassword && loginPassword.length() > 0)) {
if (contact.size()>0)
result = "{success:true}";
else
result = "{success:false,errors:{reason:'Login failed.Try again'}}";
} else {
result = "{success:false,errors:{reason:'Login failed.Try again'}}";
}
%>
<%=result %>
Rather than doing response.sendRedirect to your servlet from JSP, your form should have the servlet as its action.
<form action='contact/login.action' method='post'>
Your servlet needs to implement doPost. Having just a method called login will not work.
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
Your JSP should be the login form that sends to the servlet (via HTML, when you click submit, not via JSP code) and the servlet should do ALL of the login stuff, including the request.getParameter calls.
Then if there is a login error, the servlet should response.sendRedirect to the login form jsp.
And please note that response.sendRedirect actually sends the browser to another page. Thus it will never return a list or any other datatype.
And you would be better off not using scriptlets in your JSP. You can do everything in the servlet. Just use the jsp like a HTML page.