How to include new page on jsp page in every 10 sec? - java

Hi i am trying to include a new jsp page on my jsp page in every 10 sec how can i achieve this
i am able to include page but not including according to time
Here is my code
<%# page language="java" contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html>
<head>
<title>Untitled Document</title>
section
{height:70%; background-color:blue; display:block; overflow:auto;}
section .push {height:500px;}
</style>
</head>
<body>
<form action="F1.jsp" method="post">
<%# include file="F2.jsp" %>
<footer>footer</footer>
</form>
</body>
</html>
How can i achieve this
Thanks in advance

If you want to include more content or refresh a section of the page you need to use browser side JavaScript to pull new content from the server.

Once you display something using JSP, that is final. It cannot change unless you provide the mechanisms to change. You can set a refresh rate of your JSP to auto refresh and display each time a new content.
Or you can use AJAX.
How to do it using ajax (I prefer the JQuery version) can be found here at the answer with 5 upvotes

You can set interval in Javascript.
syntax:
setInterval(function(){
// code //
},10000);
In the code you can use Ajax calls which pool the content of JSP from the server.

Related

How to link different URLs to different items in forEach loop in JSP page? [duplicate]

This question already has an answer here:
How do I pass current item to Java method by clicking a hyperlink or button in JSP page?
(1 answer)
Closed 7 years ago.
I have a facultylist.jsp page which displays List<Faculty> as a request attribute parameter in forEach loop and I want every item in this loop to be a link to specified faculty facultyview.jsp. How can I achieve that ?
facultylist.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Faculties</title>
</head>
<body>
<h1>Faculties list</h1>
<ul>
<c:forEach var="faculty" items="${faculties}">
<li>${faculty.name}</li>
</c:forEach>
</ul>
</body>
</html>
facultyview.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Faculty</title>
</head>
<body>
<h1>${faculty.name}</h1>
<ul>
<li>Faculty name: <c:out value="${requestScope.name}"></c:out></li>
<li>Total seats: <c:out value="${requestScope.total_seats}"></c:out></li>
<li>Budget seats: <c:out value="${requestScope.budget_seats}"></c:out></li>
</ul>
apply for this faculty
</body>
</html>
I don't know if its may help, but I'm using following technologies: tomcat, jsp, servlets and log4j.In my project I have one FrontController, which is a servlet that interacts with Command pattern - each Command returns a path to resource and action type: forward or redirect.
You can solve your issue by adding a query params to the link, edit with respect to the comment. Note that you cannot access directly the JSP pages that reside under WEB-INF folder. Also, to encode properly the paramters, better construct url like
<c:url value="facultyview.jsp" var="url">
<c:param name="name" value="${faculty.name}"/>
<c:param name="total_seats" value="${faculty.total_seats}"/>
<c:param name="budget_seats" value="${faculty.budget_seats}"/>
</c:url>
<li>${faculty.name}</li>
and than than in your facultyview.jsp read from the query params
<li>Faculty name: ${param.name}</li>
<li>Total seats: ${param.total_seats}</li>
<li>Budget seats:${param.budget_seats}</li>
This direct JSP communication should solve your immediate issue, but a truly proper way would be to pass an id of a faculty to servlet, fetch the faculty instance, place in the model and pass to the view.
in other way is just take the selected value from the drop down with a name and forward it to front controller servlet ,there use if else conditions and depends on the value you could forward the request to corresponding jsp or servlet
<select name="value"> in jsp
String value=req.getParameter("value"); in servlet
if()
else if()
If you have a field in Faculty entity simply:
${faculty.name}
#Mark: faculty represents an entity from database, i'm not sure if I want to change it adding another field, or you mean some other way ?
Add a field does not means you must change database, you can have a Helper entity that inherits from Faculty and have more fields you can need,
public class FacultyFormHelper extends Faculty implements Serializable {
private String URL;
and in your view:
${facultyHelper.name}
But, If you don't want to modify your database, either create a helper class, you may add onclick event to the <a>
<a onclick="goToURL(${faculty.id})">
Then retrieve the data... i'm not sure how you get the urls... from a variable in the view, ajax call or wherever you have this URL...

Not getting the attribute in jsp which is set in request in java servlet?

I am using gwt and the gwt is including in my jsp like below
Once i clicked the menu item it is taking me to myJsp.jsp which includes gwt module and i am displaying form with upload button.
Once i click the upload, it is uloading a file (and get the blobKey) and returns back to the same jsp(myJsp.jsp) but here before dispatching to this jsp(second time) i am setting one attribute in the request.
I am trying to get that attribute in the jsp by using ${ImportId} but i am getting empty value.
The below is my jsp.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<script type="text/javascript" language="javascript" src="/ActivityLog/ActivityLog.nocache.js">
</script>
</head>
<body>
<iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' class="iframe"></iframe>
<div class="wrapper">
<input type="hidden" name="memcacheHeaderId" value="${importId}" />
<div id="activityLogModule">
</div>
</div>
</div>
</body>
</html>
When ever executing gwt module ${importId} is null.
Second time before dispatching to this jsp, i am setting request.setAttribute("importId", importId); but in the jsp i am not getting this value
What might be the reason, Is there scope problem?
the only reason is you are setting value in request, as your request is completed, server discard your request.
when you are setting
request.setAttribute("importId", importId);
Than you must be redirecting to the JSP, which creates a new Request for the JSP to the Server. Meaning server creates a new request object and does not remembers the old object with your attribute set into it.
I am not much aware of gwt but in JSP-Servlet, there are 2 mechanisms 1)Redirect and 2)Forward. we use Forward mechanism to go to the JSP with the Same request object, so the attribute which is set into the Object is available on the JSP as well, because it is a copy of the request object passed in the Request.
So please check what you can do in GWT.

Struts 2, multiple views and jQuery - How do I reuse common code?

I've read most of the online resources for building a simple "Hello World" app using Java and Struts 2. I understand the simple stuff. My problem is that I'm trying to expand that learning and build a large scale app, and I just don't see how to connect the dots.
Scenario:
I've got three views to begin with: Home.jsp, MyAccount.jsp, Contact.jsp. Each has the following HTML:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="js/common.js"></script>
...
</head>
<body>
<!-- If logged in, says "hello <s:property name="username">"
Else displays link to .show() #loginPane -->
<div id="accountHeader">...</div>
<!-- Displays <s:textfield> tags and <s:submit> tag to accept username and password -->
<div id="loginPane" style="display: none">...</div>
<header>...</header>
<nav>...</nav>
<!-- Displays view-specific content that includes Struts 2 tags -->
<div id="content">...</div>
<footer>...</footer>
</body>
</html>
So, obviously there is a lot of code common to each view (anything not in #content div).
How do I architect these views for code reuse?
What I've tried:
Placing common code in common.js and using jQuery .html() calls to populate <div>s. [Doesn't work because jQuery cannot generate code with <s:> tags.]
Using only one .jsp view file and placing view-specific code in common.js to be generated with jQuery .html() calls. [Doesn't work for the same reason -- jQuery cannot generate code with <s:> tags.]
Placing all view components in .jspf files and loading each with jQuery .load() calls from common.js. [Doesn't work -- I'm guessing the .jspf files need the Struts 2 <%taglib ...%> included in each, but jQuery .load() treats the <%taglib ...%> as text to be displayed in the <div>... and also fails to properly generate the <s:> tags.]
What is the proper way to do this? How do I architect my view(s) for code reuse?
My apologies if this isn't the proper forum to ask for architecture help, but I'm really struggling here... Perhaps point me to a more appropriate forum or an online tutorial that addresses this type of architecture?
Thanks in advance!
I've used several methods to accomplish this type of re-use of code including Tiles and tooling around with Sitemesh and other template frameworks. What I've found is that, much as Steven Benitez, in the end I preferred to use JSP taglibs, native Struts2 taglibs, and JSTL to essentially build out my own templating routines. The main reason I prefer this is that there tends to be less overhead and it's been a lot easier to maintain and extend in the long run.
Generally What I do is define my base template, index.jsp for example, and then in each independent Struts controller class I will define what page fragment is used. I try to split my controllers up in such a way that each page or function is handled by a single controller and I implement the Preparable interface. This way I can set a parameter for the page to reference. Sometimes I set it as a variable in the controller class, sometimes a sessions variable depending on what type of stating I need for the application.
Once I have a variable with the page to reference, I can just use a JSTL import or Struts include tag to load the page fragment.
The controller class would look something like this:
#Results({
#Result(name = "success", location = "/WEB-INF/content/index.jsp")
})
public class IndexController extends RestActionSupport implements Preparable{
private String page;
private String pageTitle;
#Override
public void prepare() throws Exception {
page = "home";
pageTitle= "My Home Page";
}
...
}
And then the JSP would look something like this:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%# taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title> ${pageTitle}</title>
</head>
<body>
<c:import url="${page}.jsp" />
</body>
</html>
EDIT: Fragment page example:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%# taglib prefix="s" uri="/struts-tags"%>
<div>
<h1>Welcome Home!</h1>
</div>
<script type='text/javascript'>
$(document).ready(function() {
// page specific scripting if needed
);
</script>
You can encapsulate common template code in JSP tag files, as explained in this answer or you can also use decorator frameworks such as Tiles or SiteMesh to do this.
Personally, I prefer JSP tag files. Do not attempt to write out HTML with jQuery or to put all of your code into a single JSP.

How do I change the address bar when I make an Ajax request?

I have created a website that intensively use Ajax to load its contents.
I want the pages I select to load on AJAX but at the same time the URL also changes without reloading the whole page content. How would I achieve that? I've googled already but my search did not yield any results.
Let's say I have this page:
<%# taglib prefix="s" uri="/struts-tags"%>
<%# taglib prefix="sj" uri="/struts-jquery-tags"%>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<sj:head />
</head>
<body>
<h5>Struts Jquery Ajax Integration </h5>
<div id="resultContent"></div>
<noscript>Please Turn On Javascript to make the full use of this site</noscript>
<h4>Choose A task</h4>
<ul>
<s:url value="views/ajaxvalidation.jsp" var="ajaxvalidation" />
<li><sj:a targets="resultContent" href="%{ajaxvalidation}">Ajax Validation </sj:a></li>
</ul>
<div>
<h6>Play A Music while You Navigate</h6>
<audio src="x.mp3" controls>Your browser does not support the
audio element.
</audio>
</div>
</body>
</html>
I clicked the Ajax Validation link. it will not reload the page but however the url would be something like this:
localhost:8090/AppName/ajaxvalidation.jsp
or this:
localhost:8090/AppName/ajaxvalidation.action
How would I achieve such a goal?
Note that I am using this plugin: struts2-jquery
You need to use the History API
window.history.pushState(data, title, url)
Update
Noticing that you use struts2-jquery you can add ajaxhistory="true" to enable the build in ajax history functionality. See http://code.google.com/p/struts2-jquery/wiki/HeadTag#Attributes
<sj:head ajaxhistory="true" />
Keep in mind, though, that it is not supported in all browser versions..
You can use history.pushState if the browser supports (read < IE10)
var boolPushState = false;
if (typeof history.pushState !== "undefined") {
boolPushState = true;
}
if (boolPushState) {
history.pushState(null, null, "URL");
}

JSP, can it work similar to yield, layout, content_for in Ruby/Rails/Erb

I am trying to figure out how to most effectively reuse JSP code.
I love the way Rails/erb works in that way ... with yield, layout, content_for
Example:
main_layout.erb.html
<html>
<head><%= yield :head %></head>
<body><%= yield %></body>
</html>
use
<% content_for :head do %>
<title>A simple page</title>
<% end %>
<p>Hello, Rails!</p>
in controller
layout "main_layout"
What is the closest I can get to this with JSP (without using extra frameworks)? I know about JSP include but that's not really the same as yield.
Any suggestions?
Thanks
I'm not familiar with what yield and content_for provide, but JSP tag files allow you a more robust way to template pages than JSP includes.
Example:
layout.tag
<%# tag body-content="scriptless" %>
<%# attribute name="pageTitle" required="true" type="java.lang.String" %>
<html>
<head>
<title>${pageTitle}</title>
</head>
<body>
<jsp:doBody/>
</body>
</html>
An individual JSP
<%# taglib prefix="z" tagdir="/WEB-INF/tags" %>
<z:layout pageTitle="A simple page">
<p>Hello, JSP!</p>
</z:layout>
Just place your layout.tag in the /WEB-INF/tags directory. You can use any available prefix you want, I just used "z" for the example.
While you mentioned wanting no frameworks on top of stock jsp, the Layout functionality of the Stripes Framework does pretty much exactly what you're asking for.

Categories