I'm trying to send email using velocity templates here is my template
#set ($subject = "new message in system $message.mode")
#set ($adress = "#email.com")
#set ($from = "$user.login$adress")
#set ($to = "$interlocutor.login$adress")
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<h3>hi you have new message.</h3>
</body>
</html>
and how i add elemts to model
model.put("user", interviewer);
model.put("interlocutor", interlocutor);
model.put("message", mode);
everything is great except when i print it with
System.out.println((String)velocityContext.get("to") + " " + (String)velocityContext.get("subject") +" " + (String)velocityContext.get("from")+ " ");
i recive
$interlocutor.login#email.com new message in system $message.mode testlogin#email.com
So it looks like velocity coudl handle only one object in model, others are invisible for engine, do you have clue whats wrong?
Related
I have a jsp file and using java i am adding html code to it through the use of out.println
there is a <button onclick = <% ( java function )%>
however when running button shows and everything just doesnt run java code
but when adding button code directly to jsp without using out.println works.
(this is not possible to add the html code directly to jsp file.
ive tried using the <% %> tag for inputting in java
tried to use javascript but couldnt use function( p1) cause p1 is in the form of java string and vice versa
jsp file:
<div class="container">
<div class="menu">
<h2 class="menu-group-heading">pizza</h2>
<div class="menu-group">
<%
out.println(Menu.getMenu("Pizza"));
%>
</div>
</div>
</div>
public String getMenu(String Category) throws SQLException, IOException, ClassNotFoundException {
Connection connection = Database.connectToDatabase();
Statement st = connection.createStatement();
String sql = "SELECT Name, Cost " +
"FROM MenuTable " +
"WHERE category = '" + Category + "';";
//<% Order.inputIntoCtable(\""+rs.getString(0)+"\", 1);
ResultSet rs = st.executeQuery(sql);
String categoryMenu = "";
while (rs.next()) {
categoryMenu += "<div class=\"menu-item\">"+ "\n"+
"<div class=\"menu-item-text\">"+ "\n"+
"<h3 class=\"menu-item-heading\">"+ "\n"+
"<button onClick = <% THE JAVA CODE %>"+
"<span class=\"menu-item-name\">"+rs.getString(1)+"</span>"+ "\n"+
"<span class=\"menu-item-price\">£"+rs.getString(2)+"</span>"+ "\n"+
"</button>"+
"</h3>"+ "\n"+
"</div>"+ "\n"+
"</div>" +"\n";
}
return categoryMenu;
}
I think you can define a JavaScript function, like:
function handleButtonClick(){
alert( "btn clicked");
}
and then add the name of your function in the JSP, similar to this:
...
"<button onClick ='handleButtonClick()'>"+
" <span class=\"menu-item-name\">"+rs.getString(1)+"</span><br/>"+
" <span class=\"menu-item-price\">£"+rs.getString(2)+"</span><br/>"+
"</button>"+
...
Having said that, this is very old-school and outdated way of building dynamic web pages. If you are doing it just to learn, it's ok but I would not recommend building anything other than a hobby page with this approach as there are much better ways to do it today.
For example, do not embed HTML in your Java code. Build the HTML in the JSP and add the dynamic parts with JSTL tags (as suggested in the comments)
I have html input in utf-8. In this input accented characters are presented as html entities. For example:
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>árvíztűrő<b</body>
</html>
My goal is to "canonicalize" the html by replacing html entities with utf-8 characters where possible in Java. In other words, replace all entities except < > & " '.
The goal:
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>árvíztűrő<b</body>
</html>
I need this to make it easier to compare htmls in tests, and to be easier to read for the naked eye (lots of escaped accented characters makes it very hard to read).
I don't care cdata sections (there's no cdata in the inputs).
I have tried JSOUP (https://jsoup.org/) and Apache's Commons Text (https://commons.apache.org/proper/commons-text/) unsuccessfully:
public void test() throws Exception {
String html =
"<html><head><META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">" +
"</head><body>árvíztűrő<b</body></html>";
// this is not good, keeps only the text content
String s1 = Jsoup.parse(html).text();
System.out.println("s1: " + s1);
// this is better, but it unescapes the < which is not what I want
String s2 = StringEscapeUtils.unescapeHtml4(html);
System.out.println("s2: " + s2);
}
The StringEscapeUtils.unescapeHtml4() is almost what I need, but it unfortunately unescapes the < also:
<body>árvíztűrő<b</body>
How should I do it?
Here is a minimal demonstration: https://github.com/riskop/html_utf8_canon.git
Looking into the Commons Text source it is clear that StringEscapeUtils.unescapeHtml4() delegates work to an AggregateTranslator, which is composed of 4 CharSequenceTranslator:
new AggregateTranslator(
new LookupTranslator(EntityArrays.BASIC_UNESCAPE),
new LookupTranslator(EntityArrays.ISO8859_1_UNESCAPE),
new LookupTranslator(EntityArrays.HTML40_EXTENDED_UNESCAPE),
new NumericEntityUnescaper()
);
I need only three of the translators to fullfill my goal.
So this is it:
// this is what I needed!
String s3 = new AggregateTranslator(
new LookupTranslator(EntityArrays.ISO8859_1_UNESCAPE),
new LookupTranslator(EntityArrays.HTML40_EXTENDED_UNESCAPE),
new NumericEntityUnescaper()
).translate(html);
System.out.println("s3: " + s3);
Whole method:
#Test
public void test() throws Exception {
String html =
"<html><head><META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">" +
"</head><body>árvíztűrő<b</body></html>";
// this is what I needed!
CharSequenceTranslator UNESCAPE_HTML_EXCEPT_BASIC = new AggregateTranslator(
new LookupTranslator(EntityArrays.ISO8859_1_UNESCAPE),
new LookupTranslator(EntityArrays.HTML40_EXTENDED_UNESCAPE),
new NumericEntityUnescaper()
);
String s3 = UNESCAPE_HTML_EXCEPT_BASIC.translate(html);
System.out.println("s3: " + s3);
}
Result:
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>árvíztűrő<b</body>
</html>
This question already has answers here:
Generate an HTML Response in a Java Servlet
(3 answers)
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I want to pass some parameters from my java servlet to my html form to be shown. I have read some things about jsp but I was wondering if I can do it directly, using something like this :
<script> var temp = "${param['CookieServlet0.First_Name']}"; </script>
<input type = "text" name = "First_Name" id = "First_Name" value = "temp" > <br>
where First_Name is a parameter of my servlet CookieServlet0. I know that the code example is wrong, is there a way to fix it so that I won't have to use jsp?
EDIT : ok since there is no way around I am starting with jsp, I've checked what you guys sent about JSTL and I do not need the extras that it offers so I am trying to keep it simple since I am just starting. So I have written the code below but I get java.lang.NullPointerException. It must be something really obvious but I cannot see what I do wrong...all the tutorials I have seen use the exact same commands...
java servlet :
public void doGet( HttpServletRequest request, // reaction to the reception of GET
HttpServletResponse response )
throws ServletException, IOException
{
String First_Name = request.getParameter("First_Name");
String Last_Name = request.getParameter("Last_Name");
String Phone_Number = request.getParameter("Phone_Number");
String Address = request.getParameter("Address");
PrintWriter output;
Cookie cookies[];
cookies = request.getCookies(); // get client's cookies
if ( cookies.length != 0 ) {
String departure = cookies[0].getValue();
String destination = cookies[1].getValue();
}
request.setAttribute("First_Name",First_Name);
String strViewPage="formB.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(strViewPage);
dispatcher.forward(request, response);
}
formB.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>
</head>
<body>
<label for = "First Name"> First Name </label>
<input type = "text" name = "First_Name" id = "First1_Name" value = "${First_Name}"
"> <br>
</body>
</html>
No, you can't do it directly, unless you write your own parser/injector.
However, using beans gets as close as you can get. Just use the <jsp:useBean> and replace the html with the values of the bean's attributes.
A quick google search yielded this site which contains examples on how to use the beans and jsp: http://www.roseindia.net/jsp/simple-jsp-example/UsingBeanScopeApplication.shtml
If you want to use JSTL, as Luiggi mentioned, here is a good website: http://www.journaldev.com/2090/jstl-tutorial-with-examples-jstl-core-tags
Try Using:
RequestDispatcher dispatcher = request.getRequestDispatcher(strViewPage);
Instead of:
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(strViewPage);
I have the following html (sized down for literary content) that is passed into a java method.
However, I want to take this passed in html string and add a <pre> tag that contains some text passed in and add a section of <script type="text/javascript"> to the head.
String buildHTML(String htmlString, String textToInject)
{
// Inject inject textToInject into pre tag and add javascript sections
String newHTMLString = <build new html sections>
}
-- htmlString --
<html>
<head>
</head>
<body>
<body>
</html>
-- newHTMLString
<html>
<head>
<script type="text/javascript">
window.onload=function(){alert("hello?";}
</script>
</head>
<body>
<div id="1">
<pre>
<!-- Inject textToInject here into a newly created pre tag-->
</pre>
</div>
<body>
</html>
What is the best tool to do this from within java other than a regex?
Here's how to do this with Jsoup:
public String buildHTML(String htmlString, String textToInject)
{
// Create a document from string
Document doc = Jsoup.parse(htmlString);
// create the script tag in head
doc.head().appendElement("script")
.attr("type", "text/javascript")
.text("window.onload=function(){alert(\'hello?\';}");
// Create div tag
Element div = doc.body().appendElement("div").attr("id", "1");
// Create pre tag
Element pre = div.appendElement("pre");
pre.text(textToInject);
// Return as string
return doc.toString();
}
I've used chaining a lot, what means:
doc.body().appendElement(...).attr(...).text(...)
is exactly the same as
Element example = doc.body().appendElement(...);
example.attr(...);
example.text(...);
Example:
final String html = "<html>\n"
+ " <head>\n"
+ " </head>\n"
+ " <body>\n"
+ " <body>\n"
+ "</html>";
String result = buildHTML(html, "This is a test.");
System.out.println(result);
Result:
<html>
<head>
<script type="text/javascript">window.onload=function(){alert('hello?';}</script>
</head>
<body>
<div id="1">
<pre>This is a test.</pre>
</div>
</body>
</html>
Can anyone help with extraction of CSS styles from HTML using Jsoup in Java.
For e.g in below html i want to extract .ft00 and .ft01
<HTML>
<HEAD>
<TITLE>Page 1</TITLE>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<DIV style="position:relative;width:931;height:1243;">
<STYLE type="text/css">
<!--
.ft00{font-size:11px;font-family:Times;color:#ffffff;}
.ft01{font-size:11px;font-family:Times;color:#ffffff;}
-->
</STYLE>
</HEAD>
</HTML>
If the style is embedded in your Element you just have to use .attr("style").
JSoup is not a Html renderer, it is just a HTML parser, so you will have to parse the content from the retrieved <style> tag html content. You can use a simple regex for this; but it won't work in all cases. You may want to use a CSS parser for this task.
public class Test {
public static void main(String[] args) throws Exception {
String html = "<HTML>\n" +
"<HEAD>\n"+
"<TITLE>Page 1</TITLE>\n"+
"<META http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n"+
"<DIV style=\"position:relative;width:931;height:1243;\">\n"+
"<STYLE type=\"text/css\">\n"+
"<!--\n"+
" .ft00{font-size:11px;font-family:Times;color:#ffffff;}\n"+
" .ft01{font-size:11px;font-family:Times;color:#ffffff;}\n"+
"-->\n"+
"</STYLE>\n"+
"</HEAD>\n"+
"</HTML>";
Document doc = Jsoup.parse(html);
Element style = doc.select("style").first();
Matcher cssMatcher = Pattern.compile("[.](\\w+)\\s*[{]([^}]+)[}]").matcher(style.html());
while (cssMatcher.find()) {
System.out.println("Style `" + cssMatcher.group(1) + "`: " + cssMatcher.group(2));
}
}
}
Will output:
Style `ft00`: font-size:11px;font-family:Times;color:#ffffff;
Style `ft01`: font-size:11px;font-family:Times;color:#ffffff;
Try this:
Document document = Jsoup.parse(html);
String style = document.select("style").first().data();
You can then use a CSS parser to fetch the details you are interested in.
http://www.w3.org/Style/CSS/SAC
http://cssparser.sourceforge.net
https://github.com/corgrath/osbcp-css-parser#readme