I have no idea how to do this and found some examples of how to call it however creating the script in java code (what I don't want), in ASP.NET I would use this code ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "info only", "alert('" + message + "');", true); to call my script + pass parameters and would work fine as I wished. However I have no idea of how to do this in java. Thank you
Simply by googling I found this link which provides good examples on how to invoke a javascript file.
Here is a simple example to get you going:
import java.io.*;
import javax.script.*;
public class App
{
public static void main(String[] args)
{
String file = "javascript.js";
try
{
ScriptEngine engine =
new ScriptEngineManager().getEngineByName("javascript");
FileReader fr = new FileReader(file);
engine.eval(fr);
}
catch(IOException ioEx)
{
ioEx.printStackTrace();
}
catch(ScriptException scrEx)
{
scrEx.printStackTrace();
}
}
}
I saw that it wasn't possible to call my javascript via Servlet, however if I just pass my parameters using my resp/req objects and retrieve them in my JSP page and my JSP page call myt javascript method would work.
Anyway here is the code I used:
Check if my params arent empty and call my script
<c:if test="${not empty errors}">
<script>displayErrors(errors);</script>
</c:if>
The script I would like to call (sample):
<script>
var errors = ${errors};
if (errors.length) {
displayErrors(errors);
}
</script>
And I found this answer here (How to call function of JavaScript from servlet)
Big thanks for everybody
Related
Let's say that you have a web page that only contains obfuscated Javascript in the form of an eval(...) function within a script tag.
Dean Edwards' online unpacker (link) correctly unpacks this Javascript.
I would like to write a simple Java class that loads the initial web page (I use HttpClient), extracts the eval(...) function from the HTML, and unpacks it, in order to obtain the de-obfuscated Javascript.
I've tried with Rhino, here's my code :
int start = html.indexOf("<script>eval") + "<script>".length();
int end = html.indexOf("</script>");
javascript = html.substring(start, end);
evaled = eval(javascript);
NativeFunction fEvaled = (NativeFunction) evaled;
String encodedSource = fEvaled.getEncodedSource();
log.info("encodedSource: " + encodedSource);
and the "eval" java function called:
private Object eval(String javascript){
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
Object eval = null;
try {
eval = engine.eval(javascript);
} catch (ScriptException e) {
// TODO Auto-generated catch block
log.error("Exception evaluating javascript " + javascript, e);
}
return eval;
}
But, that doesn't work, the code returned is far from being the correct code (returned by Edwards' unpacker). I've inspected the Rhino variables, found nothing useful.
Am I doing something wrong ?
I'm open to any suggestion, for example if there's a command-line tool that will work I can make a system call.
I'm on Ubuntu.
Thanks.
I've been looking here in stackoverflow how can I search for a String part inside big texts. But I haven't managed to find how to get an specific value of an attribute inside a Script using Java. The goal is read a file (script) line by line, and extract the value of an attribute "src".
For instance, the file has many lines containing this structure:
<script src="js/vendor/modernizr-2.6.2.min.js"></script>
<script data-main="js/" src="js/require.min.js"></script>
<script data-main="js/" src="js/main.js"></script>
<script src="js/vendor/modernizr-2.6.2.min.js"></script>
<script data-main="js/" src="js/require.min.js"></script>
So, using Java I read the file this way using BufferedReader class, I want to get for each line the value of "src", for example, for the first line, I want to get: js/vendor/modernizr-2.6.2.min.js, for the second line, I want to get js/require.min.js and so on, I saw some suggestions like using regex, but I don't know if it is the most effective in this cases:
public Helper(String scriptPath) {
File scriptFile = null;
try {
scriptFile = new File(scriptPath);
String relativePath = scriptFile.getParent();
System.out.println(relativePath);
BufferedReader reader = new BufferedReader(new FileReader(scriptFile));
String readLine;
while ((readLine = reader.readLine()) != null) {
// How to match the src?
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Please, if somebody could help me I will really appretiate it or if someone knows that there's already an answer for this, please let me know in order to close this, but at the time I've been searching, I haven't found this kind of problem yet.
Thank you very much in advance.
Your file looks like html I would consider using an Html Parser.
http://jsoup.org/ is very easy to use with css like selectors
I have been given a task to prevent our website from Cross-site Scripting (XSS). The concept is new to me and I googled a lot and got owasp-java-html-sanitizer. I created my own policy with
public static final PolicyFactory POLICY_DEFINITION = new HtmlPolicyBuilder()
by using .allowAttributes , I designed it .
But now I am clueless how to use it ...I found following code snippet:
System.err.println("[Reading from STDIN]");
// Fetch the HTML to sanitize.
String html = CharStreams.toString(new InputStreamReader(System.in,
Charsets.UTF_8));
// Set up an output channel to receive the sanitized HTML.
HtmlStreamRenderer renderer = HtmlStreamRenderer.create(System.out,
// Receives notifications on a failure to write to the output.
new Handler<IOException>() {
public void handle(IOException ex) {
Throwables.propagate(ex); // System.out suppresses
// IOExceptions
}
},
// Our HTML parser is very lenient, but this receives
// notifications on
// truly bizarre inputs.
new Handler<String>() {
public void handle(String x) {
throw new AssertionError(x);
}
});
// Use the policy defined above to sanitize the HTML.
HtmlSanitizer.sanitize(html, POLICY_DEFINITION.apply(renderer));
}
but how can I apply this to my JSP because I think this is for simple HTML.
Please help.
You could attach the renderer to a StringWriter instead of System.out, but it's probably easier to just use the policy's sanitize convenience method
:
public java.lang.String sanitize(#Nullable
java.lang.String html)
A convenience function that sanitizes a string of HTML.
which returns a string of HTML that is safe to interpolate into your JSP page.
Im trying to populate two separate HTML objects when a change occurs in my webpage - one a dropdown list and one a form.
So in my JSP code I have this:
$('#uSystemList').change(function() {
$.get("/live-application/systemById", {systemid: $("#uSystemList").val()}, displayChangedSystemResults, "html");
});
<script type="text/javascript">
function displayChangedSystemResults(html){
$('#uList').empty();
$('#uList').append(html);
}
</script>
And on the Java side I have this:
#RequestMapping(value = "/systemById", method = RequestMethod.GET)
public void getSystemById(#RequestParam("systemid") String systemid, OutputStream outputStream) throws IOException {
StringBuilder refreshHtml = new StringBuilder();
try {
String html = "";
System system = service.getSystemById(systemid));
for (Value value: inewsSystem.getValues()) {
html = html + "<option value='" + value.getId() + "'> " + value.getName() + "</>";
}
}
refreshHtml.append(html );
outputStream.write(refreshHtml.toString().getBytes());
outputStream.flush();
} catch (Exception e) {
outputStream.flush();
}
}
So that populates my uList dropdown - but how do I tell it to populate something else as well (e.g. a form, but could be anything else as an example...). The OutputStream seems to only let me populate one object per change.
In your case, it is not a bad idea to send two ajax request and have two spring controllers for handling each request. And subsequently, in JSP page you would need two javascript callback to populating different HTML sections.
Or, if you insist to make only one AJAX request; a workaround would be get the spring controller return a JSON, which contains the data for populating those two HTML sections. But with this approach it apparently requires a bit more javascript effort.
This is Javascript not JSP :). You need to update:
<script type="text/javascript">
function displayChangedSystemResults(html){
$('#uList').empty();
$('#uList').append(html);
$('#someOtherElement').empty();
$('#someOtherElement').append(html);
}
</script>
I'm not sure if anyone else has encountered or asked about this before, but for my application I make use of two Yahoo! RSS Feeds: Top News and Weather Forcast. I'm new to the idea of using these in the first place, but from what I've read, I simply need to make an HTTP GET request to a specific URL to retrieve an XML file which I can parse for the information I want. I have the parser working just fine, for I tested it with a sample XML file from each feed; however, a strange error is occuring when I use the AJAX GET call to the urls:
The XML page cannot be displayed
Cannot view XML input using XSL style sheet. Please correct the error and then click the Refresh button, or try again later.
Whitespace is not allowed at this location.
Error processing resource 'http://localhost:8080/BBS/fservlet?p=n'. Line 28, P...
for (i = 0; i < s.length; i++){
-------------------^
Note that I have this applciation "BBS" currently deployed on my local system with Tomcat. I looked into whitespace errors like this, and most seem to point to some line within the XML file itself that's having a problem. In most cases, it had something to do with escaping the "&" symbol, but it appears as though IE is telling me that the error is within a for-loop. I'm no XML expert, but I've never seen a for-loop within an XML. Even so, I've gone to the url directly in my browser and viewed the XML file (its the one I used to test my parsing) and found no such line. In addition, no such loop exists anywhere in my code. In other words, I'm not sure if this is an error on my end, or some configuration setting. Here's the code I'm working with, however:
jQuery Code
// Located in my JSP file
var baseContext = "<%=request.getContextPath()%>";
$(document).ready(function() {
ParseWeather();
ParseNews();
}
// Located in a separate JS file
function ParseWeather() {
$.get(baseContext + "/servlet?p=w", function(data) {
// XML Parser
}
// Data Manipulation
}
function ParseNews() {
$.get(baseContext + "/servlet?p=n", function(data) {
// XML Parser
}
// Data Manipulation
}
Java Code
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.http.HttpServlet;
import java.net.URL;
public class FeedServlet extends HttpServlet {
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
try {
response.setContentType("text/xml");
final URL url;
String line = "";
if(request.getParameter("p").equals("w")) {
// Configuration setting that returns: "http://xml.weather.yahoo.com/forecastrss?p=USOR0186"
url = new URL(AppConfiguration.getInstance().getForcastUrl());
} else {
// Configuration setting that returns: "http://news.yahoo.com/rss/"
url = new URL(AppConfiguration.getInstance().getNewsUrl());
}
final BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream());
final PrintWriter writer = response.getWriter();
while((line = reader.readLine()) != null) {
writer.println(line);
writer.flush();
}
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
My company has a AppConfiguration class that allows for certain variables, like the URL's, to be changed through the configuration page. At any rate, those two calls simple return the urls...
Yahoo! Forcast RSS Feed:
http://xml.weather.yahoo.com/forecastrss?p=USOR0186
Yahoo! News: Top Stories Feed:
http://news.yahoo.com/rss/
Anyway, any help would be incredibly helpful.
for (i = 0; i < s.length; i++){
The error is at the less-than symbol, which means that the XML parser is reading your source code! Use WGET to get the resource and check that actual XML is returned and not source code.