Unusual outcome while writing to file - java

I am having trouble while writing to file using the PrintWriter. Following is my code:
String abc = request.getParameter("textAreaField"); //String is "a b c" (with spaces)
String fileA = dir + "/A";
PrintWriter fileWriterA = new PrintWriter(new FileOutputStream(fileA,true));
fileWriterA.println(abc);
fileWriterA.close();
The problem I am having here is while writing to the file "A" in the directory "dir" only "a" from String abc will be written and the rest after the space is not written. String abc here in the code is coming from a textarea in html and I have the above code in my servlet. I am not able to understand why it won't write the string with spaces to file. I think it should. I have also checked by printing the String abc and it does print the string "a b c" (with spaces). But it won't print that to file. Is there a problem with my code? Any help would be appreciated.
Thanks in advance.

I have used your code and written a servlet . It is working absolutely fine. Here is the code.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println(request.getParameter("ta"));
String abc = request.getParameter("ta");
String fileA = "/A";
PrintWriter fileWriterA = new PrintWriter(new FileOutputStream(fileA,true));
fileWriterA.println(abc);
fileWriterA.close();
}
and here is the jsp:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="Test">
<textarea rows="20" cols="20" name="ta"></textarea><!-- having value -- check some spaces -->
<input type="submit" value="Submit">
</form>
</body>
</html>

Related

Spring MVC Thymeleaf Error: array element type mismatch

The following code is supposed to generate a table of text inputs with the dimensions of a given 2d string array specified as a ModelAttribute. Additionally, each input's placeholder is its respective value in the array. The user then enters their own text values, and upon pressing "Submit Input" those values are outputted, in order, separated by spaces.
InputHolder.java
public class InputHolder {
private String[][] input;
public String[][] getInput() {
return input;
}
public void setInput(String[][] input) {
this.input = input;
}
}
GreetingController.java
public class GreetingController {
#ModelAttribute("string2d")
public String[][] make2dStringArray() {
return new String[][] {{"The", "quick", "brown"}, {"fox", "jumps", "over"}, {"the", "lazy", "dog."}};
}
#RequestMapping(value="/greeting")
public String recieveInput(final InputHolder inputHolder, Model model) {
if (inputHolder == null || inputHolder.getInput() == null)
return "greeting";
String output = "";
for (String[] row : inputHolder.getInput())
for (String str : row)
output += " " + str;
model.addAttribute("output", output);
return "greeting";
}
}
greeting.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Test Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<form action="/greeting" th:object="${inputHolder}" method="POST">
<table>
<tr th:each="row,rowStat : ${string2d}">
<td th:each="string,stringStat : ${row}">
<input type="text" th:field="*{input[__${rowStat.index}__][__${stringStat.index}__]}" th:placeholder="${string}" />
</td>
</tr>
</table>
<button type="submit" name="submitInput">Submit Input</button>
</form>
<p th:text="'Output:' + ${output}"></p>
</body>
</html>
Everything works up until I press "Submit Input", at which point I get the following error:
java.lang.IllegalArgumentException: array element type mismatch
at java.lang.reflect.Array.set(Native Method)
Despite the fact that this is clearly a Java-side error, the error message isn't giving me a specific line number where the error occurred, and it doesn't pause in debug mode when the error occurs either. I don't know why this specific error is occurring since it appears to me that my object types (string, string array, 2d string array) are consistent/correct throughout my code, plus as I said I don't know where exactly the error is supposedly occurring.
Well, I found the error... I forgot to instantiate InputHolder's input field.
Seriously unhelpful debugging though. There was no "type mismatch"; how about "null pointer" or "array index out of bounds"? A line number would have been nice too.

How to pass java string variable to the javascript function by jsp expression tag?

I want to passing a java String variable to the javascript function parameter using jsp expression tag.Below is my jsp page.
First.jsp
<!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=ISO-8859-1">
<title>Insert title here</title>
<script>
function stringGenerate(str){
var x = document.getElementsByTagName("input");
x[0].value = str;
}
function numberGenerate(num){
var x = document.getElementsByTagName("input");
x[1].value = num;
}
</script>
</head>
<body>
<%
String num ="1234567890";
String str = "abcdefghij";
%>
<input type="text" name="string" readonly="readonly"/>
<input type="text" name="number" readonly="readonly"/><br/><br/>
<input type="button" value="String Generate" onclick= "stringGenerate(<%=str %>)" />
<input type="button" value="Number Generate" onclick= "numberGenerate(<%=num %>)" />
</body>
</html>
When I click on the button with value "Number Generate",then the num variable value(1234567890) will display on the textbox(name="number") but when I click on the button with value "String Generate",then there is nothing display on the corresponding text box(name="string").Here both num and str are string type varible but why only num variable value is displayed on textbox and why not str variable value is displayed?
Try using single quote ' when using string in HTML:
onclick= "stringGenerate('<%=str %>')"
^ ^
Full Code:
<input type="button" value="String Generate" onclick= "stringGenerate('<%=str %>')" />
The reason is that when the page is rendered by the browser, it puts the str and num values directly in the code, so it looks like:
<input type="button" value="String Generate" onclick="stringGenerate(abcdefghij)"/>
The browser basically thinks you're trying to reference a Javascript variable called 'abcdefghij'.
You should add the ' chars before and after your string text to let javascript know it should use the value of that text and not search for a variable with that name.
The declaration of str should look like this to make it work:
String str = "\'abcdefghij\'";
Please note, you can't use \" to escape as this would break your code.

How to get the mail-content without the whole source code?

I read some mails out with javax.
Then I want to save the content of a message.
For example, I read a mail with the simple content of By: Test.
Now I read the content with the .getContent() method:
Object body = message.getContent();
String content = ((body instanceof String) ? (String) body : "NO STRING CONTENT");
But the problem here is, the simple e-mail content of By: Test gets displayed by the whole Outlook-source code of the message:
<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns:m="http://schemas.microsoft.com/office/2004/12/omml" xmlns="http://www.w3.org/TR/REC-html40">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=us-ascii">
<meta name="Generator" content="Microsoft Word 14 (filtered medium)">
<style><!--
/* Font Definitions */
#font-face
{font-family:Calibri;
panose-1:2 15 5 2 2 2 4 3 2 4;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{margin:0cm;
margin-bottom:.0001pt;
font-size:11.0pt;
font-family:"Calibri","sans-serif";
mso-fareast-language:EN-US;}
a:link, span.MsoHyperlink
{mso-style-priority:99;
color:blue;
text-decoration:underline;}
a:visited, span.MsoHyperlinkFollowed
{mso-style-priority:99;
color:purple;
text-decoration:underline;}
span.E-MailFormatvorlage17
{mso-style-type:personal-compose;
font-family:"Arial","sans-serif";
color:windowtext;}
.MsoChpDefault
{mso-style-type:export-only;
font-family:"Calibri","sans-serif";
mso-fareast-language:EN-US;}
#page WordSection1
{size:612.0pt 792.0pt;
margin:70.85pt 70.85pt 2.0cm 70.85pt;}
div.WordSection1
{page:WordSection1;}
--></style><!--[if gte mso 9]><xml>
<o:shapedefaults v:ext="edit" spidmax="1026" />
</xml><![endif]--><!--[if gte mso 9]><xml>
<o:shapelayout v:ext="edit">
<o:idmap v:ext="edit" data="1" />
</o:shapelayout></xml><![endif]-->
</head>
<body lang="DE-CH" link="blue" vlink="purple">
<div class="WordSection1">
<p class="MsoNormal"><span style="font-size:10.0pt;font-family:"Arial","sans-serif"">By: Test<o:p></o:p></span></p>
</div>
</body>
</html>
So how can I read out a mail-content without getting the whole mail source-code?
First, I would start by extracting the content in the <body> section of the String. Afterwards, it depends on your liking, but you could remove every HTML-tag, for example, but beware that any formatting (line breaks!) code is gone and you get only a big chunk of text.
I just remember the simple and better way. You can just take a plain/text piece of the email.
String content = getPlainText((Part)message);
private String getPlainText(Part p) throws MessagingException, IOException {
if (p.isMimeType("text/plain")) {
return (String) p.getContent();
} else if (p.isMimeType("multipart/*")) {
Multipart mp = (Multipart) p.getContent();
for (int i = 0; i < mp.getCount(); i++) {
String s = getPlainText(mp.getBodyPart(i));
if (s != null) return s;
}
}
return null;
}

Why isn't JSP out.print() function working properly

I've been working with a JSP+Java+Html, and I've encountered a problem with out.print() function, in a for cycle.
My function getGeneAvailableTaxonomies() returns a list of integer numbers (of type List<Integer>), and I want to print these numbers in an interface.
Here's my code:
for(Integer i : ApplicationExtender.getApplicationExtender(application).getGeneAvailableTaxonomies())
{
out.print(String.format("<option value=\"%1$d\">%2$s</option>", i, TaxonId.getOrganismFromId(i)));
}
The doce %1$d should stand for the i integer value, while %2$s should stand for the other parameter, the taxonomy id value as String.
But, unfortunately, this is what appears:
While I would like to see something like:
There's surely an error on my out.print() function call... but what's wrong?
Many thanks
You dont need the "$" in your format String. As you may know, using scriptlets is not a good way to do Java Web Development. I think that using JSTL is far better, as you won't mix Java code with markup in your JSP's.
Edit: The printf method is not present in out object as I said earlier, since it is a JspWriter and JspWriter not inherit from PrintWriter (that have printf). Sorry. So, try this (it worked for me).
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<select>
<%
String[] strings = new String[]{ "aaa", "bbb", "ccc", "ddd" };
for ( int i = 0; i < strings.length; i++ ) {
out.print( String.format( "<option value='%d'>%s</option>", i, strings[i] ) );
}
%>
</select>
</body>
</html>
If you want to use a PrintWriter as in Servlets, so this will work:
<%#page import="java.io.PrintWriter"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<select>
<%
PrintWriter writer = new PrintWriter( out );
String[] strings = new String[]{ "aaa", "bbb", "ccc", "ddd" };
for ( int i = 0; i < strings.length; i++ ) {
writer.printf( "<option value='%d'>%s</option>", i, strings[i] );
}
%>
</select>
</body>
</html>
Your print/format code seems OK when I run it on http://ideone.com/u8fDT. You probably just need to have the JSP recompiled (should probably happen automatically but may sometimes require server restart).
Also, mixing HTML and Java code like this is a pretty painful way to work. JSTL or a templating system like FreeMarker would make your life easier.
try this as much i have understood :
String option = "<option value=\""+d+"\">"+s+"</option>";
out.print(option);
using String.format
out.print(String.format("<option value=\"%d\">%s</option>", i, TaxonId.getOrganismFromId(i)));
Updated
as you have mentioned in comments that TaxonID.getOrganismFromId(i) is returning int so the there is only one change in your original code %2$s to %2$d thats it...
out.print(String.format("<option value=\"%1$d\">%2$d</option>", i, TaxonId.getOrganismFromId(i)));

Confused with Java Servlets and HTML

Part of my homework for tomorrow is to search and add entries using Java EE. If the search is not existing, an add item option will show as follow:
Supposedly, when the Stock ID is not existing, It will be transfered to the Add Item Text Field of StockID. But I have no idea how to do it. My code is as follows:
Servlet:
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Item item = (Item) request.getAttribute("invenItem");
if (item != null) {
out.println("<html><title>Inventory Item</title>");
out.println("<body><h1>Inventory Item Details:</h1>");
out.println("Stock ID : " + item.getStockID() + "<br/>");
out.println("Name : " + item.getItemName() + "<br/>");
out.println("Unit Price: " + item.getUnitPrice() + "<br/>");
out.println("On Stock : " + item.getOnStock() + "<br/>");
out.println("</body>");
out.println("</html>");
} else {
RequestDispatcher rd = request.getRequestDispatcher("/DataForm.html");
rd.include(request, response);
out.println("Sorry Item not found..");
rd = request.getRequestDispatcher("AddEntry.html");
rd.include(request, response);
}
}
}
HTML:
<html>
<head>
<title>Add Entry</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h2>Add Item:</h2>
Stock ID: <input type ="text" name ="stockId" value="???"> <br> <--how to get it?
Item Name: <input type ="text" name ="name"> <br>
Unit Price: <input type ="text" name ="unitPrice"> <br>
On Stock : <input type ="text" name ="stock"> <br><br>
<input type ="submit" value ="Add Item">
</body>
</html>
You're approaching this the wrong way. HTML belongs in JSP files, not in Servlet classes. Also, EL ${} doesn't run in plain HTML files at all, but in JSP files only. Rename your .html files to .jsp. This way EL like ${param.id} will then also work, even though you still have a XSS attack hole open.
See also:
Our JSP wiki page
Our Servlets wiki page
(please read them, they contains hello world examples which should turn on some lights in your head)
You can't use the expression language (i.e. ${param.id}) in plain HTML files. It'll only be interpreted in JSPs (files with a .jsp extension).

Categories