I have a webapp that uses a frameset.
p.html:
<!DOCTYPE HTML SYSTEM>
<html>
<head>
<meta charset="utf-8"/>
<title>Übersicht</title>
</head>
<frameset border="2" frameborder="1" framespacing="0" cols= "850,*">
<frame src="/servlets/servlet/P" name="left">
<frameset border="2" frameborder="1" framespacing="0" rows="25%,*">
<frame src="right-top.html" name="right-top">
<frame src="nothing.html" name="right-bottom">
</frameset>
</frameset>
</html>
right-top.html:
<HTML>
<TITLE>Info</TITLE>
<HEAD>
</HEAD>
<p><h1>right-top</h1></p>
</BODY>
</HTML>
nothing.html:
<HTML>
<TITLE>Nothing</TITLE>
<BODY BGCOLOR="#ffffff" ONLOAD="nothing">
<HEAD>
<meta charset="utf-8"/>
</HEAD>
<SCRIPT>
<!--
function nothing(ev) {
return true
}
//-->
</SCRIPT>
</BODY>
</HTML>
The left frame is filled by a JSP (servlet running in Tomcat) with some FORMs and buttons with actions:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class P extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("Text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html><html lang=\"de\">");
out.println("<head>");
out.println("<meta http-equiv=\"Content-type\" content=\"text/html; charset=utf-8\" />");
out.println("<title>Frames Test</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Frame left</h1></body></html>");
out.println("<form id=\"alles\" action=\"#\">" +
"<input form=\"alles\" type=\"hidden\" name=\"erl\" value=\"true\"/>" +
"<button target=\"left\" type=\"submit\" form=\"alles\">" +
"Get SystemTimeAndDate</button></form><form id=\"update\" " +
"target=\"right-top\" action=\"/servlets/servlet/U\">" +
"<button type=\"submit\" form=\"update\">" +
"SVN-Update</button></form></div>");
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
out.println(sdf.format(cal.getTime()));
}
}
I added the printing of date and time to see when the action is performed.
The action for the upper right frame is in the following JSP:
import java.io.*;
import java.util.*;
import java.text.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.lang.Runtime;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/*
* This is a simple example of an HTTP Servlet. It responds to the GET
* and HEAD methods of the HTTP protocol.
*/
public class U extends HttpServlet
{
public void doPost (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
//value chosen to limit denial of service
if (req.getContentLength() > 8*1024) {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<html>\n");
out.println("<title>Too big</title>");
out.println("<body><h1>Error - content length >8k not allowed"
);
out.println("</h1></body></html>");
} else {
doGet(req, res);
}
}
/**
* Handle the GET and HEAD methods by building a simple web page.
* HEAD is just like GET, except that the server returns only the
* headers (including content length) not the body we write.
*/
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
Runtime runner= Runtime.getRuntime();
PrintWriter out = response.getWriter();
String commandline=request.getRequestURI();
String cmd;
response.setContentType("text/html");
out.println("<html><body><pre>");
out.flush();
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
out.println( sdf.format(cal.getTime()) );
out.close();
}
}
Now things don't work as I want them to do. First off: When I load the fameset freshly into the browser (open a new tab and enter the URL), the left frame is filled with the two buttons and date is printed as the code prescribes. Also the right-top frame prints its src, name "right-top" as in right-top.html. Doing the frame reload repeatedly works fine as expected.
When I then klick the button "GetSystemTimeAndDate", the time and date are updated as expected in the left frame. But clicking the button a second time results in no action being performed.
But when I klick SVN-Update the getdate.bat is executed and the original frame src is overwritten. And so it does on every klick.
The other thing I don't understand is, why the action for SVN-Update is already executed when I just reload the frameset. One can see this with the time being updated in the right top frame.
So in sum:
Why does the action fire on every frame reload once the SVN-Update button has been clicked once?
Why does button GetSystemTimeAndDate only fire once after a fresh frameload?
Related
I have a form with a text area inside it:
<form action='postCode' method='post' id="code">
<fieldset>
<legend>Integrated Development Environment</legend>
<p>Write your assembly code here then hit the compile button.</p>
<p>If there are errors it will return them; if not it will send you a file.</p>
<textarea id="example_1" style="height: 550px; width: 99%;" name="asmCode" form="code">
// This is an IDE (Integrated Development Environment) for the EV3 robot's assembly language.
vmthread main {
// Put code inside here
// This is an example:
DATA16 C4
MOVE16_16(262,C4)
SOUND(TONE,50,C4,300)
SOUND_READY
}
</textarea>
<br>
<p>Commands:
<input type='submit' value='Compile' />
<input type='button' value='Get Binary' />
</p>
</fieldset>
</form>
And I am trying to get the input from the user using a post request but whenever I try to do so I just get the text already inside the textarea. My controller looks like this:
import javax.inject._
import play.api._
import play.api.mvc._
import akka.stream.Materializer
import akka.stream.scaladsl.Source
import play.api.http.ContentTypes
import play.api.libs.Comet
import play.api.libs.json._
import scala.sys.process._
import java.io._
import scala.language.postfixOps
/**
* This controller creates an `Action` to handle HTTP requests to the
* application's home page.
*/
#Singleton
class HomeController #Inject()(val controllerComponents: ControllerComponents) extends BaseController {
/**
* Create an Action to render an HTML page.
*
* The configuration in the `routes` file means that this method
* will be called when the application receives a `GET` request with
* a path of `/`.
*/
def index() = Action { implicit request: Request[AnyContent] =>
Ok(views.html.index())
}
def getCode() = Action { request =>
var code = request.body.asFormUrlEncoded
code.map { args =>
val code = args("asmCode").head
val pw = new PrintWriter(new File("asm.lms"))
pw.write(code)
// if(("java -jar assembler.jar asm"!!).length() > 30) {
// if (("java -jar assembler.jar asm"!!).substring(0,30).contains("bytes")) {
// println("Yeah")
// }
// } else if (("java -jar assembler.jar asm"!!).contains("bytes")) {
// println("Yeah")
// } else {
// println("no")
// }
println("java -jar assembler.jar asm"!!)
if(("java -jar assembler.jar asm"!!).length() > 10){
println("java -jar assembler.jar asm"!!)
}
}.getOrElse(Ok("An unknown error has occured. Whoops!"))
Ok("")
}
}
And my routes file looks like this:
GET / controllers.HomeController.index()
+ nocsrf
POST /postCode controllers.HomeController.getCode()
GET /assets/*file controllers.Assets.versioned(path="/public", file: Asset)
I am just trying to get the form data within the textarea but it always sends the same thing even after I edit the contents of the textarea before sending it in the web page.
Whoops, my print to file function was not working properly.
I am looking at an example from Spring In Practice. I have the following controller:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping("/users")
public class AccountController {
private static final Logger LOG = LoggerFactory.getLogger(AccountController.class);
#RequestMapping(value = "/new", method = RequestMethod.GET)
public String getRegistrationForm(Model model) {
model.addAttribute("account", new AccountForm());
return "users/registrationForm";
}
#RequestMapping(value = "", method = RequestMethod.POST)
public String postRegistrationForm(AccountForm form) {
LOG.info("Created registration: {}", form);
return "redirect:/users/registration_ok.html";
}
}
The URL "/main/users/new" in this controller creates a new AccountForm object and returns it to the view /main/users/registrationForm. Here is that jsp:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1 /DTD/xhtml1-strict.dtd">
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>New user registration</title>
</head>
<body>
<h1>New user registration</h1>
<form:form cssClass="main" action="." modelAttribute="account">
<p>All fields are required.</p>
.... Form fields here ....
</form:form>
</body>
</html>
The book indicates to use action="." to post the form submission to /main/users. I am wondering if the reason action="." posts to /main/users is because this form was 'called' by a method in a controller mapped to /main/users and the "." specifies to post to this URL? The book does not explain this. Thank you in advance.
. is a relative URI like any other; it points to the current “directory”. In /main/users/new, that’s /main/users/. .. would be /main/.
Consider the case when the action is create instead; you’d end up with /main/users/create. . makes it /main/users/. According to section 5.2.4 of RFC 3986, that becomes /main/users/. (You can find a full description of every step in resolving a relative URI there, too.)
I have to work with SVG elements using some DOM operation in Dart. After adding and changing some elements under the "svg" tag, I want to export the final SVG elements to a static file. Is there any API can do it?
Thanks!
You can use the download attribute on <a> elements. This tells the browser to download the resource instead of navigating to it.
You can get the contents of the SVG with innerHtml.
Here is an example.
First, the HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Svgtest</title>
<link rel="stylesheet" href="svgtest.css">
</head>
<body>
<h1>Svgtest</h1>
<div id="container">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<circle cx="100" cy="50" r="40" stroke="black"
stroke-width="2" fill="red"/>
</svg>
</div>
<script type="application/dart" src="svgtest.dart"></script>
<script src="packages/browser/dart.js"></script>
</body>
</html>
Next, the Dart code:
import 'dart:html';
void main() {
Element container = query('#container');
String contents = container.innerHtml;
Blob blob = new Blob([contents]);
AnchorElement downloadLink = new AnchorElement(href: Url.createObjectUrlFromBlob(blob));
downloadLink.text = 'Download me';
downloadLink.download = 'svg_contents.svg';
Element body = query('body');
body.append(downloadLink);
}
Here is the browser coverage: http://caniuse.com/#feat=download At the time of this writing, Firefox, Chrome, and Opera support the download attribute.
(Note: there is no way to directly save a file to the native OS filesystem with HTML5.)
For IE 10+:
import 'dart:html';
import 'dart:js';
import "package:js/js.dart";
#JS("navigator.msSaveBlob")
external void msSaveBlob(blob, filename);
void main() {
Element container = query('#container');
String contents = container.innerHtml;
Blob blob = new Blob([contents]);
if (js.context['navigator']['msSaveBlob'] != null) {
msSaveBlob(blob, 'svg_contents.svg');
} else {
AnchorElement downloadLink = new AnchorElement(href: Url.createObjectUrlFromBlob(blob));
downloadLink.text = 'Download me';
downloadLink.download = 'svg_contents.svg';
Element body = query('body');
body.append(downloadLink);
}
}
For my RAP-project I need to show some charts. Because I haven't found any widget for this purpose, my plan was to use the browser widget, so I can use JavaScript-Plugins like Highcharts or Chartsjs. But I can't get it working. If I set an HTML-File in browser.setUrl, the browser widget don't show anything, not even simple HTML. The JavaScript-Console in Chrome says
Not allowed to load local resource
If I enter the HTML-Code with the setText method it shows the HTML, but JavaScript is not working, it don't load external JS-File like the jQuery-library.
Can't this be done this way? Or where is my failure? (Sorry for my bad englisch, I'm not native speaker.)
Here's the Java-Code I tried:
browser = new Browser(composite, SWT.NONE);
browser.setTouchEnabled(true);
browser.setBounds(10, 10, 358, 200);
browser.setUrl("D:\\STATS\\statistiken.html");
Or this:
File file = new File("D:\\STATS\\statistiken.html");
browser = new Browser(composite, SWT.NONE);
browser.setTouchEnabled(true);
browser.setBounds(10, 10, 358, 200);
browser.setUrl(file.toURI().toString());
I tried also some other things, there were not working to.
With HTML in setText-method (I tried external libraries and local libraries in same folder):
browser = new Browser(composite, SWT.NONE);
browser.setBounds(10, 10, 358, 200);
browser.setText(
"<html>" +
"<head>" +
"<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js\"></script>" +
"<script src=\"http://code.highcharts.com/highcharts.js\"></script>" +
"<script src=\"http://code.highcharts.com/modules/exporting.js\"></script>" +
"</head>" +
"<body>" +
"<p>Test</p>" +
"<div id=\"container\" style=\"min-width: 400px; height: 400px; margin: 0 auto\"></div>" +
"</body>" +
"</htm>");
Hope someone can help me with this problem.
Local links will not be resolved and external links will not be loaded(Cross Domain problem) in your case.
I could suggest you 2 Solutions.
Solution 1:
This is useful when you have very few resources(html, javascript, css) to render on Browser and no Hyperlinks(which when cliked will load a different page).
You can use Velocity. Read this to start using Velocity.
You can have all the static content in Velocity Template and inject Dynamic content into it at Runtime.
Here is the excerpt from one of my Projects.
init.vm
<html dir="ltr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style type="text/css">
.transcript {
background-color: #d2d2d2;
}
.messageBlock {
margin-left: 4px;
margin-bottom: -15px;
}
.message {
margin-left: 115px;
word-wrap: break-word;
white-space: -moz-pre-wrap;
_white-space: pre;
white-space: pre-wrap;
}
</style>
</head>
<script type="text/javascript">
function resizeChatWindow() { var divT = document.getElementById("divTranscript"); divT.style.height = (document.body.clientHeight - getTopAreaHeight()) + "px"; divT.style.width = (document.body.clientWidth) + "px"; divT.style.overflow = "auto"; divT.style.position = "absolute"; divT.style.left = "0px"; divT.style.top = getTopAreaHeight() + "px";}
function getTopAreaHeight() { var chatAlert = document.getElementById("chatAlert"); if (chatAlert) { return chatAlert.clientHeight; } return document.getElementById("divBody").clientHeight;}
isChat=false; window.onresize=resizeChatWindow;
</script>
<script type="text/javascript">
$scriptText
</script>
<script type="text/javascript">
function addChat(chatText){
$("#divTranscript").append(chatText);
$("#divTranscript").animate({ scrollTop: $("#divTranscript")[0].scrollHeight }, "slow");
}
</script>
<body onload="resizeChatWindow();">
<div id="divBody"></div>
<div id="divTranscript">$history</div>
</body>
</html>
VelocityUtils
private void init() throws Exception {
ve = new VelocityEngine();
Properties velocityProperties = new Properties();
velocityProperties.put("resource.loader", "class");
velocityProperties.put("class.resource.loader.description", "Velocity Classpath Resource Loader");
velocityProperties.put("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
ve.init(velocityProperties);
//ve.init();
}
public String getInitHtml(String history) throws ResourceNotFoundException, ParseErrorException, Exception {
/* now render the template into a StringWriter */
StringWriter writer = null;
/* next, get the Template */
Template t = ve.getTemplate("templates/init.vm","UTF-8");
/* create a context and add data */
VelocityContext context = new VelocityContext();
String script = IOUtils.toString(VelocityUtils.class.getResourceAsStream("script/jquery.min.js"), "UTF-8");
context.put("scriptText", script); //You can even have all the script content in init.vm rather than injecting it at runtime.
context.put("history", StringUtils.defaultIfBlank(history, StringPool.BLANK));
writer = new StringWriter();
t.merge(context, writer);
/* show the World */
String returnMe = writer.toString();
return returnMe;
}
set the returned String in Browser.setText()
Solution 2:
I explained it here.
i am new to SWFUpload , and i am reading the documentation now, and i need an example using SWFUpload with java please, thank you.
Example implementation for SWFUpload, jQuery, JSP, Java and Spring
First the jsp:
<%# page language="java" pageEncoding="UTF-8" %>
<head>
<script type="text/javascript" src="<c:url value="/public/js/swfupload/swfupload.js"/>"></script>
<script type="text/javascript" src="<c:url value="/public/js/jquery-plugins/ jquery.swfupload.js"/>"></script>
<script type="text/javascript">
$(function(){
$('.swfupload-control').swfupload({
// Backend Settings
upload_url: "<c:url value="/upload;jsessionid=${pageContext.session.id}"/>", // Relative to the SWF file (or you can use absolute paths)
// Flash Settings
flash_url : "<c:url value="/public/js/swfupload/swfupload.swf"/>",
//IMPORTANT: you need to set file_post_name otherwise flash sets it as Filedata, which does not conform to bean naming conventions.
file_post_name: "file",
// File Upload Settings
file_size_limit : "102400", // 100MB
file_types : "*.*",
file_types_description : "All Files",
file_upload_limit : "10",
file_queue_limit : "0",
// Button Settings
button_image_url : "<c:url value="/public/js/swfupload/XPButtonUploadText_61x22.png"/>", // Relative to the SWF file
button_placeholder_id : "spanButtonPlaceholder",
button_width: 61,
button_height: 22
});
// assign our event handlers
$('.swfupload-control')
.bind('fileQueued', function(event, file){
// start the upload once a file is queued
$(this).swfupload('startUpload');
})
.bind('uploadComplete', function(event, file){
alert('Upload completed - '+file.name+'!');
// start the upload (if more queued) once an upload is complete
$(this).swfupload('startUpload');
});
});
</script>
<head>
<body>
<div id="file_upload"></div>
<div class="swfupload-control">
<span id="spanButtonPlaceholder"></span>
</div>
</body>
Controller:
#Controller
public class UploadController {
Logger logger = LoggerFactory.getLogger(this.getClass());
#RequestMapping(value="/upload", method=RequestMethod.POST)
public String addMultiple(
final HttpServletRequest request
, final HttpServletResponse response
, #RequestParam("file") MultipartFile file //NOTE: `#RequestParam("file")` matches `file_post_name: "file"`
){
logger.debug(uploadedFile.getOriginalFilename());
}
}
Also, make sure you've got this in your configs:
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
If you are not using spring you might be able to cast the HttpServeletRequest as a MultiPartRequestWrapper use:
File[] files = ((MultiPartRequestWrapper)request).getFiles("Filedata");
This solution doesn't require COS (Com O'Reilly Servlet). Instead it just uses the more common javax.servlet.http.HttpServletRequest
Sources (stackoverflow wouldnt let me post links):
swfupload.org/forum/generaldiscussion/1087
demo.swfupload.org/Documentation/#setFilePostName
blogs.bigfish.tv/adam/2009/06/14/swfupload-jquery-plugin/
webdeveloperplus.com/jquery/multiple-file-upload-with-progress-bar-using-jquery/ (prettier implemenation of jquery uploader)
http://e-blog-java.blogspot.com/2011/03/upload-using-swfupload-component.html
He had also given a sample source code to see it in action.