I am actually working on my graduation project. I have to work with spring boot technology. I have to run a python script from a java code which will use input of a html form. I have prepared my three files HTML, java and python
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Add Info</title>
<link rel="stylesheet" type="text/css" th:href="#{/css/style.css}"/>
</head>
<body>
<h1>Insert an Info:</h1>
<!--
In Thymeleaf the equivalent of
JSP's ${pageContext.request.contextPath}/edit.html
would be #{/edit.html}
-->
<form th:action="#{/index}" method="get">
<input type="text" th:name="Coord1"/> </br>
<input type="text" th:name="Coord2"/> </br>
<input type="text" th:name="Coord3"/> </br>
<input type="text" th:name="Coord4"/> </br>
<input type="text" th:name="datedeb"/> </br>
<input type="text" th:name="datefin"/> </br>
<input type="submit"/>
</form>
<br/>
<!-- Check if errorMessage is not null and not empty -->
<div th:if="${errorMessage}" th:utext="${errorMessage}"
style="color:red;font-style:italic;">
...
</div>
</body>
</html>
the java code:
package com.example.project.controller;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
#Controller
public class MainController {
float Coord1;
float Coord2;
public static String s;
#RequestMapping(value="/index",method=RequestMethod.GET)
public void addAObjectForm(#RequestParam("Coord1") float Coord1,#RequestParam("Coord2")
float Coord2,#RequestParam("Coord3") float Coord3, #RequestParam("Coord4")float Coord4,#RequestParam("datedeb")
String datedeb,#RequestParam("datefin") String datefin) throws IOException {
//System.out.println(Coord1);
try
{
String pathPython = "test1.py";
String [] cmd = new String[8];
cmd[0] = "python";
cmd[1] = pathPython;
cmd[2] = "Coord1";
cmd[3] = "Coord2";
cmd[4] = "Coord3";
cmd[5] = "Coord4";
cmd[6] = "datedeb";
cmd[7] = "datefin";
Runtime r = Runtime.getRuntime();
Process p = r.exec(cmd);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((s=in.readLine()) != null){
System.out.println(s);
System.out.println(Coord1);
}
// BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
}
catch(Exception e){
}
}
}
and python code:
import sys
import os
def getDataFromJava(arg1=(sys.argv[0]),arg2=(sys.argv[1]),arg3=(sys.argv[2]),arg4=(sys.argv[3]),arg5=(sys.argv[4]),arg6=(sys.argv[5])):
cord1=arg1
cord2=arg2
cord3=arg3
cord4=arg4
datedeb=arg5
datefin=arg6
print(cord1)
print(cord2)
#print(arg3_val)
return cord1,cord2,cord3,cord4,datedeb,datefin
when I am trying to be sure that my python script is returning a result, I get the String s in the java code equal to null
Any help please to get a result
Thank you in advance.
# append to your current test1.py
import sys
getDataFromJava( \
str(sys.argv[0]), str(sys.argv[1]), str(sys.argv[2]), \
str(sys.argv[3]), str(sys.argv[4]), str(sys.argv[5]))
Ref
I am a beginner at python. I googled to find what I think is missing in your solution. I think the python function needs to be called, and shell parameters need to be retrieved and passed in to python function.
Update 1
Based on your edit, you have updated the function definition def getDataFromJava(...):. You have not added a function call getDataFromJava(...) below your function definition. I have provided a runnable script below.
import sys
import json
def getDataFromJava(arg1,arg2,arg3,arg4,arg5,arg6):
cord1=arg1
cord2=arg2
cord3=arg3
cord4=arg4
datedeb=arg5
datefin=arg6
return cord1,cord2,cord3,cord4,datedeb,datefin
print(json.dumps(getDataFromJava( \
str(sys.argv[1]), str(sys.argv[2]), str(sys.argv[3]), \
str(sys.argv[4]), str(sys.argv[5]), str(sys.argv[6]))))
$ python test1.py qw er ty ui op as
["qw", "er", "ty", "ui", "op", "as"]
I added json because I saw that you are returning a list of items back to java side. I thought that json will be a good data interchange format between your python side and your java side. Your java code now need to parse the returned json-formatted string. If you are returning a few items and want to skip json usage, you can return something like abc#def#ghi#jkl.
print('#'.join(getDataFromJava( \
str(sys.argv[1]), str(sys.argv[2]), str(sys.argv[3]), \
str(sys.argv[4]), str(sys.argv[5]), str(sys.argv[6]))))
Related
I obviously am missing something here. I have a web app where the input for a form may be in English or, after a keyboard switch, Russian. The meta tag for the page is specifying that the page is UTF-8. That does not seem to matter.
If I type in "вв", two of the unicode character: CYRILLIC SMALL LETTER VE
What do I get? A string. I call getCodePoints().toArray() and I get:
[208, 178, 208, 178]
If I call chars().toArray[], I get the same.
What the heck?
I am completely in control of the web page, but of course there will be different browsers. But how can I get something back from the web page that will let me get the proper cyrillic characters?
This is on java 1.8.0_312. I can upgrade some, but not all the way to the latest java.
The page is this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title>Cards</title>
<link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity = "sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin = "anonymous" />
<link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity = "sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin = "anonymous" />
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity = "sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin = "anonymous">
</script>
<meta http-equiv = "Content-Type" content = "text/html; charset=UTF-8" />
<style>.table-nonfluid { width: auto !important; }</style>
</head>
<body>
<div style = "padding: 25px 25px 25px 25px;">
<h2 align = "center">Cards</h2>
<div style = "white-space: nowrap;">
Home
<div>
<form name="f_3_1" method="post" action="/cgi-bin/WebObjects/app.woa/wo/ee67KCNaHEiW1WdpdA8JIM/2.3.1">
<table class = "table" border = "1" style = "max-width: 50%; font-size: 300%; text-align: center;">
<tr>
<td>to go</td>
</tr>
<tr>
<td><input size="25" type="text" name="3.1.5.3.3" /></td>
</tr>
<td>
<input type="submit" value="Submit" name="3.1.5.3.5" /> Skip
</td>
</table>
<input type="hidden" name="wosid" value="ee67KCNaHEiW1WdpdA8JIM" />
</form>
</div>
</div>
</div>
</body>
</html>
Hm. Well, here is at least part of the story.
I have this code:
System.out.println("start: " + start);
int[] points = start.chars().toArray();
byte[] next = new byte[points.length];
int idx = 0;
System.out.print("fixed: ");
for (int p : points) {
next[idx] = (byte)(p & 0xff);
System.out.print(Integer.toHexString(next[idx]) + " ");
idx++;
}
System.out.println("");
The output is:
start: вв
fixed: ffffffd0 ffffffb2 ffffffd0 ffffffb2
And the UTF-8 value for "В", in hex, is d0b2.
So, there it is. The question is, why is this not more easily accessible? Do I really have to put this together byte-pair by byte-pair?
If the string is already in UTF-8, as I think we can see it is, why does the codePoints() method not give us, you know, the codePoints?
Ok, so now I do:
new String(next, StandardCharsets.UTF_8);
and I get the proper string. But it still seems strange that codePoints() gives me an IntStream, but if you use these things as int values, it is broken.
It was a problem with the frameworks I was using. I thought I was setting the request and response content type to utf-8 but I was not.
I am running a .jsp file on a server and trying to send user input form data to the "doPost" method in the HttpServlet.
When I try to print the vals of user input in doPost, they are null.
I am trying to get the vals by their html ID, but that's not working for some reason. There could be a simple issue in the HTML.
The submit button seems to be working as it is routing properly back to the .java file I am trying to parse the user input data with. It is only the vals that are null.
Here is my code.
Thank you! :)
<%#page import="java.util.Date"%>
<%# page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Binary Encoder</title>
</head>
<body>
<h2>Binary Encoding: Encode any number from 0 to 65535</h2> <br>
<h3>Date=<%= new Date() %>
</h3>
<!-- in this form I need to figure out how to get user input into Binaryencoder.java-->
<form action="../Binaryencoder" method="post">
Input number you want to encode (0 to 65536):<br>
<input type="number" id="toencode"><br>
Input first number for encoding (0 to 255) :<br>
<input type="number" id="mask1"><br><br>
Input second number for encoding (0 to 255) :<br>
<input type="number" id="mask2"><br><br>
<input type="submit" id="submit" value="Submit">
</form>
</body>
</html>
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
//code to process the form...
String toencode = request.getParameter("toencode");
String mask1 = request.getParameter("mask1");
String mask2 = request.getParameter("mask2");
//response is the thing that goes back to HTML page
PrintWriter out = response.getWriter();
String output = String.format("Number to encode is: %s", toencode);
String op1 = String.format("Mask1 is: %s", mask1);
String op2 = String.format("Mask2 is: %s", mask2);
out.println(output);
out.println(op1);
out.println(op2);
}
The issue is with these tags, e.g.,: <input type="number" id="toencode"> The tag needs a name attribute, like this: name="mynumber"
The servlet receives the name-value pairs of the request parameters from the JSP. In your JSP the name is missing. The correct way to code your JSP is: <input type="number" id="toencode" name="mynumber">
In the servlet program access the posted parameter and its value as follows in the doPost method:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String myNumber = request.getParameter("mynumber");
getServletContext().log("# My Number: " + myNumber); // this prints in the log file
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("My Number: " + myNumber); // this prints on the browser page
}
This should show the number you had entered in the JSP in the browser page, like: My Number: 999. You can also refer the server logs.
Add name attribute to your input like below:
<input type="number" name="toencode" id="toencode">
<input type="number" name="mask1" id="mask1">
<input type="number" name="mask2" id="mask2">
request.getParameter does not recognize id attributes.
The type of three input should be text, not number . try it.
In the three form input fields, use the name attribute instead of or in addition to id. Only the values of these input fields are included in the request as parameters.
Your form seems to be missing the name attribute for all the fields.
Try changing this:
<input type="number" id="toencode">
to this (adding the name attribute to the toencode field):
<input type="number" id="toencode" name="toencode">
Obviously, for the other fields (mask1, mask2) the names value would be matching their ids
I am developing a web application in which I which I have a JavaScript array and I want this array in my JSP page and iterate it save the data in database.
var value = response;
for (var key in value) {
if (value.hasOwnProperty(key)) {
alert(key + " -> " + value[key]);
var sample = new Array();
sample=value[key];
console.log(sample);
// document.getElementById('');
}
}
});
I want this data on my JSP page is it possible. If it is possible, then how?
You can have javascript in jsp but that will always execute on client side. So if you want to save some stuff on trigger of some event inside browser you can do that by making ajax call or form submission. Ajax is preferred way because its faster and better experience for user
But if you have intention of execution of javascript on server side thats not possible
Java script client side script whereas jsp is server side script so you can't simply do this.
What you can do is submit the calculated variable from javascript to server by form-submission, or using URL parameter or using AJAX calls and then you can make it available on server to store in database.
Client Side:
<script type="text/javascript">
var n = document.getElementById("data");
var f=new Array( "apple", "orange", "mango" );
n.value = f;
</script>
<form action="Your_JSP.jsp" method="POST">
<input type="hidden" id="data" name="data" value="" />
<input type="submit" />
</form>
Server Side:
<%
String val = request.getParameter("data");
String aa[]=val.split(",");
for(String x : aa )
out.println(x);
//now hereyou can use aa array tostore in database or do whatever you want
%>
Try this if you have two different jsp:
first.jsp
<script>
var response = [];
...
var put = function(form) {
form.resp.value = response.join(','); //using comma as separator
};
</script>
<form onsubmit='put(this)' method='next.jsp' method='post'>
<input type='hidden' name='resp' />
<button>Submit</button>
</form>
next.jsp
<%
String[] resp = request.getParameter("resp").split(",");
%>
Response is: ${param.resp} <!-- debugging -->
yes , its possible to do that. you can show array in HTML tag
<!DOCTYPE html>
<html>
<head>
<script>
var value=response;
for (var key in value) {
if (value.hasOwnProperty(key)) {
alert(key + " -> " + value[key]);
var sample = new Array();
sample=value[key];
console.log(sample);
// do here as
document.getElementById("array").innerHTML = sample;
// here array is <p> tag in html and sample is array which will be shown in jsp page.
}
}
</script>
</head>
<body>
<form action="get.jsp" method="POST">
<p id="array" name="array" type="hidden"></p>
<input type="submit" />
</body>
</html>
in get.jsp you will able to get value from array as:
<%
String []array = request.getParameter("array").split(",");
//this String array you can use to store data in DB
%>
I need to validate HTML using java. So I try with jsoup library. But some my test cases failing with it.
For eg this is my html content. I dont have any control on this content. I am getting this from some external source provider.
String invalidHtml = "<div id=\"myDivId\" ' class = claasnamee value='undaa' > <<p> p tagil vanne <br> <span> span close cheythillee!! </p> </div>";
doc = Jsoup.parseBodyFragment(invalidHtml);
For above html I am getting this output.
<html>
<head></head>
<body>
<div id="myDivId" '="" class="claasnamee" value="undaa">
<
<p> p tagil vanne <br /> <span> span close cheythillee!! </span></p>
</div>
</body>
</html>
for a single quote in my above string is comming like this. So how can I fix this issue. Any one can help me please.
The best place to validate your html would be http://validator.w3.org/. But that would be manual process. But dont worry jsoup can do this for you as well. The below program is like a workaround but it does the purpose.
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
public class JsoupValidate {
public static void main(String[] args) throws Exception {
String invalidHtml = "<div id=\"myDivId\" ' class = claasnamee value='undaa' > <<p> p tagil vanne <br> <span> span close cheythillee!! </p> </div>";
Document initialDoc = Jsoup.parseBodyFragment(invalidHtml);
Document validatedDoc = Jsoup.connect("http://validator.w3.org/check")
.data("fragment", initialDoc.html())
.data("st", "1")
.post();
System.out.println("******");
System.out.println("Errors");
System.out.println("******");
for(Element error : validatedDoc.select("li.msg_err")){
System.out.println(error.select("em").text() + " : " + error.select("span.msg").text());
}
System.out.println();
System.out.println("**************");
System.out.println("Cleaned output");
System.out.println("**************");
Document cleanedOuput = Jsoup.parse(validatedDoc.select("pre.source").text());
cleanedOuput.select("meta[name=generator]").first().remove();
cleanedOuput.outputSettings().indentAmount(4);
cleanedOuput.outputSettings().prettyPrint(true);
System.out.println(cleanedOuput.html());
}
}
var invalidHtml = "<div id=\"myDivId\" ' class = claasnamee value='undaa' > <<p> p tagil vanne <br> <span> span close cheythillee!! </p> </div>";
var parser = Parser.htmlParser()
.setTrackErrors(10); // Set the number of errors it can track. 0 by default so it's important to set that
var dom = Jsoup.parse(invalidHtml, "" /* this is the default */, parser);
System.out.println(parser.getErrors()); // Do something with the errors, if any
So, I have an XHTML document report skeleton that I want to populate by getting Elements of a certain IDs and setting their contents.
I tried getElementById(), and had null returned (because, as I found out, id is not implicitly "id" and needs to be declared in a schema).
panel.setDocument(Main.class.getResource("/halreportview/DefaultSiteDetails.html").toString());
panel = populateDefaultReport(panel);
Element header1 = panel.getDocument().getElementById("header1");
header1.setTextContent("<span class=\"b\">Instruction Type:</span> Example<br/><span class=\"b\">Allocated To:</span> "+employee.toString()+"<br/><span class=\"b\">Scheduled Date:</span> "+dateFormat.format(scheduledDate));
So, I tried some work-arounds because I don't want to have to validate my XHTML documents. I tried adding a quick DTD to the top of the file in question like so;
<?xml version="1.0"?>
<!DOCTYPE foo [<!ATTLIST bar id ID #IMPLIED>]>
But getElementById() still returned null. So tried using xml:id instead of id in the XHTML document in the hopes it was supported, but again no luck. So instead I tried to use getElementsByTagName() and loop through the results checking ids. This worked, and found the correct element (as confirmed by output printing "Found it"), but when I try to call setTextContent on this element I am still getting a NullPointException. Code below;
Element header1;
NodeList sections = panel.getDocument().getElementsByTagName("p");
for (int i = 0; i < sections.getLength(); ++i) {
if (((Element)sections.item(i)).getAttribute("id").equals("header1")) {
System.out.println("Found it");
header1 = (Element) sections.item(i);
header1.setTextContent("<span class=\"b\">Instruction Type:</span> Example<br/><span class=\"b\">Allocated To:</span> "+employee.toString()+"<br/><span class=\"b\">Scheduled Date:</span> "+dateFormat.format(scheduledDate));
}
}
I'm loosing my mind on this one. I must be suffering from some kind of fundamental misunderstanding of how this is supposed to work. Any ideas?
Edit; Excerpt from my XHTML file below with CSS removed.
<html>
<head>
<title>Site Details</title>
<style type="text/css">
</style>
</head>
<body>
<div class="header">
<p></p>
<img src="#" alt="Logo" height="81" width="69"/>
<p id="header1"><span class="b">Instruction Type:</span> Example<br/><span class="b">Allocated To:</span> Example<br/><span class="b">Scheduled Date:</span> Example</p>
</div>
</body>
</html>
I am not sure why its not working , but I have put together example for you and it works !
Note : My example is using following libraries
Apache Commons IO (Link)
Jsoup HTML Parser (Jsoup link)
Apache Commons Lang (Link)
My input xhtml file ,
<html>
<head>
<title>Site Details</title>
<style type="text/css">
</style>
</head>
<body>
<div class="header">
<p></p>
<img src="#" alt="Logo" height="81" width="69" />
<p id="header1">
<span class="b">Instruction Type:</span> Example<br />
<span class="b">Allocated To:</span> Example<br />
<span class="b">Scheduled Date:</span> Example
</p>
</div>
</body>
</html>
The java code that work ! [All comments, read ]
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class Test {
/**
* #param args
* #throws IOException
* #throws InterruptedException
*/
public static void main(String[] args) throws IOException, InterruptedException {
//loading file from project
//When it is exported as JAR the files inside jar are not files but they are stream
InputStream stream = Test.class.getResourceAsStream("/test.xhtml");
//convert stream to file
File xhtmlfile = File.createTempFile("xhtmlFile", ".tmp");
FileOutputStream fileOutputStream = new FileOutputStream(xhtmlfile);
IOUtils.copy(stream, fileOutputStream);
xhtmlfile.deleteOnExit();
//get html string from file
String htmlString = FileUtils.readFileToString(xhtmlfile);
//parse using jsoup
Document doc = Jsoup.parse(htmlString);
//get all elements
Elements allElements = doc.getAllElements();
for (Element el : allElements) {
//if element id is header 1
if (el.id().equals("header1")) {
//dummy emp name
String employeeName = "dummyEmployee";
//update text
el.text("<span class=\"b\">Instruction Type:</span> Example<br/><span class=\"b\">Allocated To:</span> "
+ employeeName.toString() + "<br/><span class=\"b\">Scheduled Date:</span> " + new Date());
//dont loop further
break;
}
}
//now get html from the updated document
String html = doc.html();
//we need to unscape html
String escapeHtml4 = StringEscapeUtils.unescapeHtml4(html);
//print html
System.out.println(escapeHtml4);
}
}
*output *
<html>
<head>
<title>Site Details</title>
<style type="text/css">
</style>
</head>
<body>
<div class="header">
<p></p>
<img src="#" alt="Logo" height="81" width="69" />
<p id="header1"><span class="b">Instruction Type:</span> Example<br/><span class="b">Allocated To:</span> dummyEmployee<br/><span class="b">Scheduled Date:</span> Sat Nov 02 07:37:12 GMT 2013</p>
</div>
</body>
</html>