I have a servlet, and I want to print some data from the servlet with a JSP file, and I have to use compulsory the Expression Language.
I have this code in the servlet:
String saludo="hi";
req.setAttribute("exito",saludo);
And I have this in my JSP file:
${exito}
And I also tried with this:
${requestScope.exito}
But when I try to see it with my browser (Google Chrome), instead of seeing hi, I see
${exito}
What am I doing wrong?
When you are sending information to the JSP you need to dispacth the current request to the JSP, I try the above code and I don't have any problem, this is my code:
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String saludo="hi";
req.setAttribute("exito",saludo);
req.getRequestDispatcher("MyPage.jsp").forward(req, resp);
}
And this is the code for MyPage.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>Title</title>
</head>
<body>
${exito}
</body>
</html>
Related
I am trying to just set up a very basic jsp file that takes in a query from a url and displays it. I have the following test.jsp file that I run on the server:
<%# 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>Test jsp</title>
</head>
<body>
<% String firstName = (String) request.getAttribute("firstName");
out.println("Hello :" + firstName);%>
</body>
</html>
However, when I type in the following URL, I still get a "null" result (even after refreshing): see Picture.
Note: my ultimate goal is to do have an event at some point that sends a POST request from a java file and display its result in the jsp page. If I understood well from my research, I would have to do it via a Servlet with a DispacherRequest forwarding method. But I first want to understand why the simple aforementioned code isnt working).
Thank you for your help !
You mention that you're trying to display a query parameter from the URL. A query or request parameter is not the same as a request attribute.
To get a query parameter, you would have to use the getParameter() method:
String firstName = request.getParameter("firstName")
I'm not understanding how to set up an href to redirect to another jsp. This is what I have so far.
JSP with a href in it:
<%# 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>
<div align="center">
<h1>${gradebook.gradeBookName} was created.</h1>
<br> Home Page <br>
Add grades to GradeBook
</div>
</body>
</html>
The href "/createGradeBook3" is the link I want to re-direct to.
Controller:
#RequestMapping(value = "/viewGradeBook3", method = RequestMethod.GET)
public String viewGradeBook3(Locale locale, Model model)
{
return "viewGradeBook3";
}
Try to use the following code snippet in your controller -
return "redirect:/path/to/jsp";
Or you may use another URL that has been mapped with a controller's handler method. In this case the redirected request will be handled by the controller's handler method.
Hope it will help.
Thanks a lot.
Trying to find the best way to make a quasi java-javascript web application. I want to write a java servlet (for the controller and backend) with a jQuery front end. What's the best approach to having these two communicate with each other? I'm used to coding in both but never worked on them together.
Can anybody help me out? I suppose a start would be having a Java Servlet call from jQuery code and getting a response back from the servlet.
Thanks!
Create REST backend using one of JAX-RS implementations (Jersey, RESTeasy etc.). Writing web service with plain old Servlet API is tedious.
You can start learning JAX-RS from here.
Take a look at jQuery's ajax function. Here is a simple example:
// Servlet
#SuppressWarnings("serial")
public class AjaxHandler extends HttpServlet {
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
resp.setContentType("text/plain");
resp.getWriter().print("Hello jQuery!");
}
}
// View.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">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<title>Insert title here</title>
</head>
<body>
<script>
$(document).ready(function() {
$.ajax({
url : '/AjaxHandler', // servlet mapping ("web.xml")
success : function(responseText) {
$('#ajaxHandlerResponse').text(responseText);
}
});
});
</script>
Servlet's message: <span id="ajaxHandlerResponse"></span>
</body>
</html>
This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 2 years ago.
Here I am sending data from servlet to jsp using ajax request.But i didn't get any value from servlet on my client side.This is my code
Servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String s="msg";
System.out.print("Servlet");
response.setContentType("text/plain");
PrintWriter out=response.getWriter();
out.print(s);
out.flush();
out.close();
}
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 content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<title>Insert title here</title>
<script src="js/jquery-1.11.1.js" type="text/javascript"></script>
<script type="text/javascript">
function poll() {
setTimeout(function () {
$.ajax({
type: 'POST',
url: 'http://localhost:8080/ajaxtest/testajax',
success: function (data) {
alert(data); //DatO ANY PROCESS HERE
//document.getElementById("testid").value=data;
//document.write(data)
},
complete: poll
});
}, 5000);
}
</script>
</head>
<body onload="poll()">
<form><input type="text" name="test" id="testid" value=""></form>
</body>
</html>
output:
Am getting empty alert box and "No element found" on the browser debugging tool.
Your code is working fine for me. Check if you have your jquery.js accessed properly from jsp and also check your web.xml for correct servlet mapping.
best to include below line for jquery.js , one less thing to bother about:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
You should set the data, before putting alert box. currently alert box is not getting any data
I'm learning java and try to pass some variable from servlet to jsp page. Here is code from servlet page
#WebServlet("/Welcome")
public class WelcomeServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session = request.getSession();
session.setAttribute("MyAttribute", "test value");
// response.sendRedirect("index.jsp");
RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
dispatcher.forward(request, response);
}
}
And simple 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>My Index page</title>
</head>
<body>
Index page
<br />
<%
Object sss = request.getAttribute("MyAttribute");
String a = "22";
%>
<%= request.getAttribute("MyAttribute"); %>
</body>
</html>
Whatever I do attribete at jsp is null.
What is wrong at this simple code?
you are getting if from request not session.
It should be
session.getAttribute("MyAttribute")
I suggest you to use JavaServer Pages Standard Tag Library or Expression Language instead of Scriplet that is more easy to use and less error prone.
${sessionScope.MyAttribute}
or
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:out value="${sessionScope.MyAttribute}" />
you can try ${MyAttribute}, ${sessionScope['MyAttribute']} as well.
Read more
Oracle Tutorial - Using JSTL
Oracle Tutorial - Expression Language
You set an attribute in a session. You have to retrieve it from a session:
Object sss = session.getAttribute("MyAttribute");
And since you are dispatching the request, you actually don't need a session. You can set the attribute in a request object in your servlet:
request.setAttribute("MyAttribute", "test value");
Then read it as you are already doing in you JSP.
You should avoid scriptlets because they are java code in HTML, they break MVC pattern, they are ugly, odd and deprecated.
Simply replace :
<%
Object sss = request.getAttribute("MyAttribute");
String a = "22";
%>
with simply using EL ${MyAttribute}
But if you want to stick with scriptlets, you should get the attribute from the proper scope which is session in your case.