I am using Struts2 framework (with annotations) and need help in redirection.
Step 1: The action class extends ActionSupport, in execute method add action message. On success of action, location is set to a JSP - common_popup.jsp.
Step 2: In JSP check for hasActionMessages() and sets a dialog with action messages.
ISSUE: a. On action success due to redirection the action messages set are lost.
b. Due to redirection the common_popup.jsp is opening up in a new URL.
Is there a way to set redirection to FALSE ? Such that I retain the page which submitted request to action class and common_popup.jsp appears on top of same page as a popup dialog.
ACTION Class:
public class Settings extends ActionSupport {
#Action(value="settings",
results = { #Result (name="success", location="common_popup.jsp"),
#Result (name="failure", location="${actionUrl}")
})
#Override
public String execute()
{
try {
addActionMessage(" ITS SETTINGS TIME !! ");
}
catch (Exception exp )
{
addActionError(" Failed to update the data base configuration. Please retry. ");
this.actionUrl = "main.jsp?settings=true";
return "failure";
}
return "success";
}
}
JSP Code - common_popup.jsp:
<html>
<head>
<link rel="stylesheet" type="text/css" href="stylesheets/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="stylesheets/loader.css">
<script src="scripts/jquery-1.11.0.min.js" type="text/javascript"></script>
<script src="scripts/jquery-ui-1.10.4.js" type="text/javascript"></script>
<script src="scripts/loader.js" type="text/javascript"></script>
</head>
<body>
<s:if test="hasActionMessages()">
<div id="actionMessage" class="ui-dialog" style="display:none" >
<s:actionerror/>
</div>
<script>
$( "#actionMessage" ).css("display","");
$( "#actionMessage" ).dialog();
</script>
</s:if>
</body>
</html>
The result results = { #Result (name="success", location="common_popup.jsp") is forwarding a servlet dispatcher to the URL built from the result location.
This is also known a default dispatcher result type. So, in you code you are not redirect, but dispatch or forward the JSP page specified by the location attribute.
So, nothing in your code that has shown is redirecting. If it does and you want to save action messages between actions (you should not redirect to the JSP) you can use messageStore interceptor.
Find the examples of this interceptor on the linked page or read my answers to find more detailed explanation with examples.
Related
The struts 2 jQuery plugin has a built in publish/subscribe framework.
If you define your own publish and subscribe event (for example on a grid) the subscribed function will be called every time the event is published. For details please see (Struts 2 jQuery Subscribe is called more than once)
To prevent this, there is a isSubscribed method which can be used.
For a grid as:
<sjg:grid id="gridtable"
onBeforeTopics="before_grid_load" >
The JS will be:
$.subscribe('before_grid_load', function(event, data) {
if ( $('#gridtable').isSubscribed('before_grid_load') ){
return ;
}
//go on with function
}
The problem is that the $('#gridtable').isSubscribed('before_grid_load') returns false every time!
The function isSubscribed is applied on the element $('#gridtable') but subscribed to the $(document). I have tested with the last element and it didn't work to me. But tried with the first element and it worked.
Script:
<head>
<link href="<s:url value="/css/template_styles.css"/>" type="text/css" rel="stylesheet">
<sj:head />
<title>jQuery Grid</title>
<script type="text/javascript">
$(document).ready(function(){
console.log("Before subscribe");
$("#gridtable").subscribe("beforeTopic", function(topic, data) {
console.log('Topic: '+data, topic);
if ( $("#gridtable").isSubscribed("beforeTopic") ){
console.log('Subscribed: '+data, topic);
return;
}
//go on with function
console.log('Not subscribed: '+data, topic);
});
console.log("After subscribe");
});
</script>
</head>
For grid:
<sjg:grid id="gridtable"
onBeforeTopics="beforeTopic" >
Check your lib to your jsp
<%# taglib prefix="sjg" uri="/struts-jquery-grid-tags"%>
Enable jQuery Grid Plugin in your Head Tag
<sj:head jqueryui="true" jquerytheme="redmond" />
I have a website and ran into an issue.
First of all the website is in dutch however the problem i have you don't have to understand dutch.
My website is www.hobbysite.zz.mu/
When you click the login button it redirects you to a mybb forum login (this is correct)
next part is the tricky part for me.
when you click the login button there it should run this script:
<html> <head>
<script language="Javascript">
function trigger(){
document.php-form.submit();
document.htm-form.submit(); }
</script> </head>
<body onload="trigger();">
<form name="php-form" action="http://hobbysite.zz.mu/top.html" target="_topframe">
<form name="htm-form" action="http://hobbysite.zz.mu/Main/main.html" target="mainframe">
</body>
Problem is however that its not doing the first option and chance the "cloud" set.
my first cloudset iswww.hobbysite.zz.mu/top1.html and it should chance in the target frame topframe to hobbysite.zz.mu/top.html
thanks in advance
Instead of trying to submit two forms you could change the location of the frames. Try this code:
<html><head>
<script>
function trigger() {
top.frames["topFrame"].location.href="http://hobbysite.zz.mu/top.html";
top.frames["mainFrame"].location.href="http://hobbysite.zz.mu/Main/main.html";
}
</script>
</head>
<body onload="trigger();">
</body></html>
I am trying to redirect the user from one jsp page to another jsp page after making him wait for 10 seconds or 10000 milliseconds. But there is a redirect as soon as the page is opened in the browser. Why is this is so ? Is there anything wrong in the following code ? I am calling the redirectFunction which does the redirect.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP - 1</title>
<script>
function redirectFunction() {
<% response.sendRedirect("jsp-2.jsp"); %>
}
</script>
</head>
<body>
<h1>
Wait while you are redirected...
</h1>
<script type="text/javascript">
setTimeout(redirectFunc,10000); // wait for 10 seconds,then call redirectFunc
</script>
</body>
You sends redirect exactly from server that`s why it fired immediatelly.
If you want to fire redirect after 10 seconds than you need to change your code:
function redirectFunction() {
window.location.href = "jsp-2.jsp"
}
and setTimeout(redirectFunction,10000);
Actually when you call <% response.sendRedirect("jsp-2.jsp"); %> Java server sets http code 302 to your http response, and header Location: jsp-2.jsp
And browser redirects to page specified in Location header immediately.
Hope it helps.
the code in scriptlet is executed on the server, it is not javascript. use this
function redirectFunction() {
window.location.href = "jsp-2.jsp";
}
Assuming you're using HttpServletResponse, what's happening is that you're sending the HTTP location header with a status code 302. This happens when the page is requested, not during client-side execution of the JavaScript.
If you want it to be during JavaScript execution you need to assign the URL you want to window.location.
window.location = "http://google.com";
for example
This is because
<script>
function redirectFunction() {
<% response.sendRedirect("jsp-2.jsp"); %>
}
</script>
is translated and executed as
out.print(" <script> function redirectFunction() {");
response.sendRedirect("jsp-2.jsp");
out.print("</script>");
The call sendRedirect is executed on the server side, while preparing your page, and it's performing the redirect. You can do the sleep and the redirect in javascript only, using window.location.
Background:
I have a servlet in which I am dynamically generating javascript and putting into a variable script. Then I set the response content type as text/javascript and send the script over to the client:
resp.setContentType("text/javascript");
resp.getWriter().println(script);
Problem:
The browser does download the javascript file but it doesn't recognize the functions inside the file. If I create a static javascript file and use it instead, it works fine.
Question:
What should be done so that browser treats response from the servlet as a regular javascript file?
Thank you for help.
It should work fine. I suspect that you're just including it the wrong way or calling the function too early or that the response content is malformed.
I just did a quick test:
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 6156155</title>
<script src="javaScriptServlet"></script>
<script>test()</script>
</head>
<body>
</body>
</html>
with
#WebServlet(urlPatterns={"/javaScriptServlet"})
public class JavaScriptServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/javascript");
response.getWriter().write("function test() { alert('peek-a-boo'); }");
}
}
and I get
How do you refer to this servlet from your browser ?
If you want to include this with a HTML page (existing one), you should refer to it from the tag of your page.
Ex.
<html>
<head>
<script type='text/javascript' src='URL_TO_YOUR_SERVLET'></script>
</head>
</html>
Or if you want it to be executed as part of a Ajax call, just pass the response to eval function.
Or else, if you just want to send the output and get it executed in browser, you need to send the HTML segment as well. Then include your JS with in the body tags, as a script tag.
ex. Your servlet sends the following, using content type 'text/html' :
<html>
<body>
<script type='text/javascript'>
<!-- write your generated JS here -->
</script>
</body>
</html>
You could always write the script 'in-line' to the web page.
I think this way is better.
<%# page language="java" contentType="text/javascript; charset=UTF-8" pageEncoding="UTF-8"%>
alert('Pure JavaScript right here!');
Set content type in JSP:
contentType="text/javascript; charset=UTF-8"
How can I read/access a JSP variable from JavaScript?
alert("${variable}");
or
alert("<%=var%>");
or full example
<html>
<head>
<script language="javascript">
function access(){
<% String str="Hello World"; %>
var s="<%=str%>";
alert(s);
}
</script>
</head>
<body onload="access()">
</body>
</html>
Note: sanitize the input before rendering it, it may open whole lot of XSS possibilities
The cleanest way, as far as I know:
add your JSP variable to an HTML element's data-* attribute
then read this value via Javascript when required
My opinion regarding the current solutions on this SO page: reading "directly" JSP values using java scriplet inside actual javascript code is probably the most disgusting thing you could do. Makes me wanna puke. haha. Seriously, try to not do it.
The HTML part without JSP:
<body data-customvalueone="1st Interpreted Jsp Value" data-customvaluetwo="another Interpreted Jsp Value">
Here is your regular page main content
</body>
The HTML part when using JSP:
<body data-customvalueone="${beanName.attrName}" data-customvaluetwo="${beanName.scndAttrName}">
Here is your regular page main content
</body>
The javascript part (using jQuery for simplicity):
<script type="text/JavaScript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script type="text/javascript">
jQuery(function(){
var valuePassedFromJSP = $("body").attr("data-customvalueone");
var anotherValuePassedFromJSP = $("body").attr("data-customvaluetwo");
alert(valuePassedFromJSP + " and " + anotherValuePassedFromJSP + " are the values passed from your JSP page");
});
</script>
And here is the jsFiddle to see this in action http://jsfiddle.net/6wEYw/2/
Resources:
HTML 5 data-* attribute: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
Include javascript into html file Include JavaScript file in HTML won't work as <script .... />
CSS selectors (also usable when selecting via jQuery) https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started/Selectors
Get an HTML element attribute via jQuery http://api.jquery.com/attr/
Assuming you are talking about JavaScript in an HTML document.
You can't do this directly since, as far as the JSP is concerned, it is outputting text, and as far as the page is concerned, it is just getting an HTML document.
You have to generate JavaScript code to instantiate the variable, taking care to escape any characters with special meaning in JS. If you just dump the data (as proposed by some other answers) you will find it falling over when the data contains new lines, quote characters and so on.
The simplest way to do this is to use a JSON library (there are a bunch listed at the bottom of http://json.org/ ) and then have the JSP output:
<script type="text/javascript">
var myObject = <%= the string output by the JSON library %>;
</script>
This will give you an object that you can access like:
myObject.someProperty
in the JS.
<% String s="Hi"; %>
var v ="<%=s%>";
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
<title>JSP Page</title>
<script>
$(document).ready(function(){
<% String name = "phuongmychi.github.io" ;%> // jsp vari
var name = "<%=name %>" // call var to js
$("#id").html(name); //output to html
});
</script>
</head>
<body>
<h1 id='id'>!</h1>
</body>
I know this is an older post, but I have a cleaner solution that I think will solve the XSS issues and keep it simple:
<script>
let myJSVariable = <%= "`" + myJavaVariable.replace("`", "\\`") + "`" %>;
</script>
This makes use of the JS template string's escape functionality and prevents the string from being executed by escaping any backticks contained within the value in Java.
You could easily abstract this out to a utility method for re-use:
public static String escapeStringToJS(String value) {
if (value == null) return "``";
return "`" + value.replace("`", "\\`") + "`";
}
and then in the JSP JS block:
<script>
let myJSVariable = <%= Util.escapeStringToJS(myJavaVariable) %>;
</script>
The result:
<script>
let myJSVariable = `~\`!##$%^&*()-_=+'"|]{[?/>.,<:;`;
</script>
Note: This doesn't take separation of concerns into consideration, but if you're just looking for a simple and quick solution, this may work.
Also, if you can think of any risks to this approach, please let me know.