jsp buttons through out.println - java

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)

Related

JSOUP - Help getting <IMG SRC> from <DIV CLASS>

I have the HTML snippet below. There are multiple div classes for "teaser-img" throughout the document. I want to be able to grab all the "img src" from all these "teaser-img" classes.
<div class="teaser-img">
<a href="/julien/blog/failure-consciousness-vs-success-consciousness-shifting-focus-become-badass-or-loser">
<img src="http://www.rsdnation.com/files/imagecache/blog_thumbnail/files/blog_thumbs/rsdnatonaustin.jpg" alt="" title=""/>
</a>
</div>
I have tried many things so I wouldn't know what code to share with you guys. Your help will be much appreciated.
final String html = "<div class=\"teaser-img\">\n"
+ " <a href=\"/julien/blog/failure-consciousness-vs-success-consciousness-shifting-focus-become-badass-or-loser\">\n"
+ " <img src=\"http://www.rsdnation.com/files/imagecache/blog_thumbnail/files/blog_thumbs/rsdnatonaustin.jpg\" alt=\"\" title=\"\"/>\n"
+ " </a>\n"
+ "</div>";
// Parse the html from string or eg. connect to a website using connect()
Document doc = Jsoup.parseBodyFragment(html);
for( Element element : doc.select("div.teaser-img img[src]") )
{
System.out.println(element);
}
Output:
<img src="http://www.rsdnation.com/files/imagecache/blog_thumbnail/files/blog_thumbs/rsdnatonaustin.jpg" alt="" title="">
See here for documentation about the selector syntax.

How to pass a parameter from Java method to a div in JSP

I have a class where I have a method that displays data. Each data displayed has a link. When I click on the link I want to pass parameter to a specific div in a JSP page.
eg: The method in my java class has code like:
output += "<td width=\"30%\" " + colorCode + " > " +
"" + testName + "";
And index.jsp has a div:
<div id="testselect" title="Basic try">
</div>
How do I call the div with id testselect from when the link is clicked and how do I pass the parameter also?

liferay : rendering <portlet:renderURL> in custom taglib

want to create a link to other pages of portlet in my own taglib with out.print() but in execution liferay can't render <portlet:renderURL> taglibs :
taglib code :
int counter = 0;
while (rs.next()) {
counter++;
int spcPk = Integer.parseInt(rs.getString("tCommodityGroupSpcPK"));
result = "<tr>" +
" <td id=\"group-"+counter+"\">" +
" <a href=\"<portlet:renderURL><portlet:param name='jspPage'" +
" value='subGroup.jsp?p1="+spcPk+"' /></portlet:renderURL>\" /> " +
" "+rs.getString("xa")+" " +
" </a> " +
" </td> " +
" <td id=\"group-"+counter+"\">"+rs.getString("xx")+"</td> " +
" <td id=\"group-"+counter+"\">"+rs.getString("aa")+"</td> " +
" <td id=\"group-"+counter+"\">"+rs.getString("Result")+"</td> " +
" </tr>";
out.print(result);
}
rs.close();
// out.println(result);
cstmt.close();
in execution of view.jsp and other tags has been rendered successfully but the liferay taglibs don't .. when i click on links i have somthing like this in my url !!
localhost:8081/%3Cportlet:renderURL%3E%3Cportlet:param%20name='jspPage'%20value='subGroup.jsp?p1=3'%20/%3E%3C/portlet:renderURL%3E
can anybody help me in rendering that taglibs in custom taglib class ?
Thats obvious, JSP Engine consider your tag as any other markup.
You have to use the API rather than Tag like mentioned below
PortletURL portletURL = renderResponse.createRenderURL();
portletURL.setParameter("jspPage", "subGroup.jsp?p1="+spcPk);
then inject portletURL.toString() into the markup
UPDATE:
You should have access to both renderRequest and renderResponse implicitly if you define <portlet:defineObjects /> in your JSP.
The other way to get them from normal request object is
PortletResponse portletResponse = (PortletResponse)request.getAttribute(JavaConstants.JAVAX_PORTLET_RESPONSE);
You can refer to the source code of any of the existing Liferay UI Tags like asset-categories-navigation for more information.

retrieve value of arraylist in javascript in same page

There is a JSP page in which i have an ArrayList variable. I need these arraylist values(txt1 and txt2) in script tag.I have tried lots of combinations and googling but didnot succeed.
javascript function
function fun1()
{
// how to get arraylist values
}
JSP page:
<body>
<%
ArrayList<String> al= new ArrayList<String>();
al.add("txt1");
al.add("txt2");
out.println("<input type=text id=" + al.get(0) + ">");out.println("<br>");
out.println("<input type=text id= " + al.get(1) + ">");out.println("<br>");
out.println("<input type=button id=btn1 value=click onClick=fun1(); > ");
%>
</body>
Thanks for reply
Inside javascript you can use Scriplets very well
Assume the list 'arrayList' is having [1,2,3,4] in java (JSP)
you can get the array list by this
function fun1()
{
var list = '<%= arrayList %>';
}
if you print the variable list, it will be a string with value '[1,2,3,4]'
You can then split this using Regex or simple string operation
<body>
<%
ArrayList<String> al= new ArrayList<String>();
al.add("txt1");
al.add("txt2");
out.println("<input type=text id=" + al.get(0) + ">");out.println("<br>");
out.println("<input type=text id= " + al.get(1) + ">");out.println("<br>");
out.println("<input type=button id=btn1 value=click onClick=fun1(); > ");
%>
</body>
<script>
// try the script here
</script>
Try something like this.
<script>
var myArray=new Array();
myArray[0] = '<%= al.get(0) %>';
myArray[1] = '<%= al.get(1) %>';
<script>
You could create a script tag which creates an array in js that holds all you values. I'm not familar with jsp but deppending on oyur code it could look like:
out.println("<script type='text/javascript'>");
out.println("var myJsArray = new Array();");
foreach(var arrayMember in al)
{
out.println("myJsArray.push(" + arrayMember + ");");
}
out.println("</script>");
In Js just use the array:
function fun1()
{
var firstArrayMember = myJsArray[0];
// or whatever you want to do
}
You could also use assoziativ arrays if you have a key for a specific array member.
Hope you got the idea
I would have the Java code somewhere else, but if you insist on having it inside your JSP, try having readable HTML and only output Java content using <%=...%> - something like this:
<%
ArrayList<String> list = new ArrayList<String>();
list.add("text1");
list.add("text2");
%>
<body>
<form ...>
<input type="text" id="<%=list.get(0)%>" />
<input type="text" id="<%=list.get(1)%>" />
<input type="button" id="button1" value="Click" onclick="functionOne();" />
</form>
<script type="text/javascript">
function functionOne() {
alert(document.getElementById("<%=list.get(0)%>").value);
}
</script>
</body>

Capture multiple check box selection JSP Parameters

I found this post that shows how to pass multiple check box selections to another JSP page, but it's not working for me. When I try to get the selected values I get:
checked boxes: [Ljava.lang.String;#3f3fbd
Here are my two pages (be gentle, this is my first attempt at JSP!)
createSHAREfile.jsp basically runs a query to find all the terms that have not been processed and show each term with a check box next to it:
<title>Create SHARE Files</title>
</head>
<body>
<jsp:include page="../menu/header.jsp" flush="false" />
<form name='SelectSHARETerms' method='post' action="SHAREProcessing.jsp">
<fieldset><legend>Select Terms to Process for SHARE</legend>
<table align='left'>
<% String termDetail = "", currDate = "";
currentDateTime datetime = new currentDateTime();
datetime.setCurrDate();
currDate = datetime.getCurrDate();
java.sql.Date todayDate = java.sql.Date.valueOf(currDate);
Terms terms = new Terms();
ArrayList<Terms.termsTable> termsObjList = new ArrayList<Terms.termsTable>();
terms.setTermsSql("Select * from Terms where TermDate <= '" + currDate + "' AND VoucherProcessDate Is Null");
boolean indicator = terms.setListOfTerms();
if (indicator == true) {
int size = terms.getListSize();
termsObjList = terms.getTermsList();
for (int i=0; i<size; ++i) {
Terms.termsTable eachTerm = (Terms.termsTable)termsObjList.get(i);
java.sql.Date termDate = eachTerm.TermDate;
%>
<tr><td><input type=checkbox name=SelectedTermDate id='SelectedTermDate<%=i%>' value="<%=i%>"><%=termDate %></td></tr>
<%
}
}
%>
<tr><td align='center'><input type='submit' value='Submit'></input></td></tr>
</table>
</fieldset>
</form>
</body>
</html>
When the submit button is pressed I call SHAREProcessing.jsp. Right now all i'm trying to do on this page is show which termdates the user has selected so I can use them as parameters to a Java Class that will create the files for the selected terms:
<title>SHARE Processing</title>
</head>
<body>
<jsp:include page="../menu/header.jsp" flush="false" />
<table width='50%' align='center' border='1'>
<% String[] SelectedValues = request.getParameterValues("SelectedTermDate");
System.out.println("checked boxes: " + SelectedValues);
%>
</body>
</html>
Here's where I'm trying to use the code shown in the other post but it's not working :(
Thanks for any help!
Leslie
You're trying to print the whole string array with System.out.println, and so you get that. It's probably working fine.
Try this:
System.out.println("checked boxes:");
for (int i = 0; i < SelectedValues.length; ++i)
System.out.println(" " + SelectedValues[i]);
Also, I beg you: in your spare time, find out about a modern web framework (there are zillions for Java) and strive to escape from the painful world of coding Java inside JSP files.
You're just facing the default value of Object#toString().
Either just loop over it and print each item, or use Arrays#toString(). Here's an SSCCE:
package com.stackoverflow.q2426380;
import java.util.Arrays;
public class Test {
public static void main(String... args) {
String[] array = {"foo", "bar" , "waa"};
System.out.println(array); // [Ljava.lang.String;#addbf1
String arrayAsString = Arrays.toString(array);
System.out.println(arrayAsString); // [foo, bar, waa]
}
}
That said, this problem has actually nothing to do with JSP. It's just a view technology. The problem is rather in the basic Java code --which you wrote at the wrong place, in a JSP file instead of a Java class. I strongly agree with the comments that writing raw Java code in JSP files is a bad practice. Start learning Servlets.

Categories

Resources