Submit form with action="." - forms

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.)

Related

Cannot get form data within a textarea using scala-play post request

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.

Execution of Form actions in a Frameset with JSP

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?

Problems with i18n with Play App 2.4.6

I have one simple project with Play Framework 2.4.6 that have internationalization configured as documentation on Play describe.
My files are that:
1) Controller:
package controllers
import play.api._
import play.api.mvc._
import play.api.i18n.{I18nSupport,MessagesApi,Messages,Lang}
import play.api.i18n.Messages.Implicits._
import play.api.Play.current
import javax.inject.Inject
class Application #Inject()(val messagesApi: MessagesApi) extends Controller with I18nSupport {
def index = Action { implicit request =>
Ok(views.html.index("Your new application is ready."))
}
}
2) Message resource file:
application.name = Orthoclinic
welcome = Welcome to play!
3) Main template:
#(title: String)(content: Html)(implicit messages: Messages)
<!DOCTYPE html>
<html lang="en">
<head>
<title>#title</title>
<link rel="stylesheet" media="screen" href="#routes.Assets.versioned("/assets/stylesheets/main.css")">
<link rel="shortcut icon" type="image/png" href="#routes.Assets.versioned("/assets/images/favicon.png")">
<script src="#routes.Assets.versioned("/assets/javascripts/hello.js")" type="text/javascript"></script>
</head>
<body>
#Messages("application.name")
#content
</body>
</html>
4) Index template:
#(message: String)
#main("Welcome to Play") {
#play20.welcome(message)
}
5) routes file:
# Home page
GET / controllers.Application.index
# Map static resources from the /public folder to the /assets URL path
GET /assets/*file controllers.Assets.versioned(path="/public", file: Asset)
6) Application conf file:
play.crypto.secret = "k1mIneaPlay_pRoJ"
play.i18n.langs = [ "en", "en-us", "pt-br", "es" ]
Calling ./activator reload compile run my result is that:
[error] /home/josenildo/scala-ide/workspace/orthoclinic-app/app/views/main.scala.html:13: could not find implicit value for para
meter messages: play.api.i18n.Messages
[error] #Messages("application.name")
I have followed the documentation for i18n last version on Play Documentation here.
What's the problem on that implementation?
You just need to add the implicit messages argument to your index.scala.html template:
#(message: String)(implicit messages: Messages)
#main("Welcome to Play") {
#play20.welcome(message)
}
An implicit Messages instance needs to be in-scope whenever you use i18n via #Messages("my.key"), which has a corresponding implicit messages argument that will be supplied by the compiler (see the signature here).
Also, you may want to get rid of import play.api.i18n.Messages.Implicits._, since it shouldn't be required if your controller extends I18NSupport, and indeed may cause an error concerning ambiguous implicit values.

what options can be passed to flashing in play framework

Hello there Grammarians,
The documentation only shows:
flashing("success")
Do failures never happen if I use play? I've tried "failure" & "error" they don't do anything
You can either pass in a Flash instance or tuples of Strings. It doesn't have to be a specific String. Important is that you handle whatever you stick into the flash scope.
consider this example (Play 2.3.4):
Application.scala
package controllers
import play.api.mvc._
object Application extends Controller {
def index = Action { implicit req =>
Redirect(routes.Application.flash()).flashing("something" -> "show this text")
}
def flash = Action { implicit req =>
Ok(views.html.index("Flash!"))
}
}
index.scala.html
#(title: String)(implicit flash: Flash)
<!DOCTYPE html>
<html>
<head>
<title>#title</title>
</head>
<body>
<h1>#flash.get("something")</h1>
</body>
</html>
routes
# Home page
GET / controllers.Application.index
GET /flash controllers.Application.flash

need an example of using SWFUpload with java

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.