I have a JSP and a Java class that work with each other.
I have a boolean variable in my Java class. I want to check it all the time with AJAX, if its value has changed to true. A JavaScript alert shows a message.
In JSF, there is something like this :
<h:outputScript rendered="#{categoryBean.showCategoryNameAlert}">
alert("CategoryName already exist!");
</h:outputScript>
but I don't know how to do it in JSP?
-
See Using AJAX with JSFPaul Samsotha– Paul Samsotha2014年02月09日 06:46:57 +00:00Commented Feb 9, 2014 at 6:46
-
tnx, but I don't want JSF , I want to do this in JSPomid haghighatgoo– omid haghighatgoo2014年02月09日 06:48:45 +00:00Commented Feb 9, 2014 at 6:48
2 Answers 2
You can try to use the following example.
Front-end part:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function(){
$.get('/backEnd',function(responseText) {
if(responseText == 'true') {
alert("Variable has been set");
}
});
},1000);
});
</script>
</head>
<body>
</body>
</html>
Back-end part:
@WebServlet(name = "checkerServlet", urlPatterns = { "/backEnd" })
public class CheckerServlet extends HttpServlet {
private YourClass yourClass;
@Override
public void init() {
yourClass = new YourClass();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
PrintWriter writer = response.getWriter();
if(yourClass.getBooleanValue) {
writer.write("true");
} else {
writer.write("false");
}
writer.close();
}
@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
Example of a class with a boolean variable -
public class YourClass {
private static boolean booleanValue = false;
public void setBooleanValue() {
booleanValue = true;
}
public void resetBooleanValue() {
booleanValue = false;
}
public boolean getBooleanValue() {
return booleanValue;
}
...
}
If you are not using a servlet, you can use this call:
<%@ page import="fullpackagename.YourClass" %>
<jsp:useBean id="yourClass" scope="request" class="fullpackagename.YourClass" />
<%
YourClass yourClass = new YourClass();
// check your variable here
%>
Add it to the presentation layer.
Code for auto-refreshing:
<%response.setIntHeader("Refresh", 1); %>
Comments
you need a servlet that listen on a specific url. give it "/check".
in servlet :
if(category.categoryName != null) // or any thing you want
out.write("true"); // out is response outputstream
in jsp : a ajax request that request for "/check" all the time and alert if see true.