Is there any way I can make a connectTodb() function using jstl? - java

Is there any way I could use jstl inside a java function? Basically, what I want is I would just call the connectTodb() function in a jsp page where I need a connection. However, I do not know how.
Can I do this for example?
connectTodo() {
<sql:setDataSource driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/database_name"
var="localSource"
user="database_user"
password="database_password"/>
}
How do I call this method in my jsp file? Or if I can't do this, how do I connect to the database with just a function? Help me out, thank you!

You can write functions in JSP, but that is generally discouraged. Normally you would create tags and/or fragments. You posted one,
<sql:setDataSource driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/database_name"
var="localSource"
user="database_user"
password="database_password"/>
That is made available in a jsp with the <%# %> block like
<%# taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<html>
You could write your own tag file like initDB.tag
<%# taglib prefix="db" tagdir="/WEB-INF/tags" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<sql:setDataSource driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/database_name"
var="localSource"
user="database_user"
password="database_password"/>
and then you can use it like
<db:initDB />
Finally, you might check if your server has a connection pool that you can access from a JNDI name.

Related

jsp command <%=%> being ignored when it is used in a Javascript statement, inside a taglib tag statement?

An example will make this clearer!
The jsp file...
<%# taglib prefix ="jam" uri= "http://jam.tld" %>
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="ISO-8859-1"%>
<%
String targetPage = true ? "toast" : "bread";
%>
<jam:text onmousedown="movePage('<%=targetPage%>');" id="<%=targetPage%>"><%=targetPage%></jam:text>
Note - the taglib is not mine and I have no control over it. (it isn't really called jam either :).
This then creates this HTML...
<td onmousedown="movePage('<%=targetpage%>;');" id="toast">toast</td>
Which as you can see: the <%=targetPage%> was only replaced/parsed in the non-javascript bit?
The compiled jsp file looks like this:
jspx_th_jam_005ftext_005f2.setOnmousedown("movepage('<%=targetpage%>')");
Anyone know what is going on, or how to fix it?
Why is the <%=%> tag being ignored when it is part of JavaScript statement?
:)
Here's a bit of a cheat solution, you dont need the JSP tag in that JS call. In fact, it's tidier this way
<jam:text onmousedown="movePage(this.id);" id="<%=targetPage%>"><%=targetPage%></jam:text>

Struts 2, multiple views and jQuery - How do I reuse common code?

I've read most of the online resources for building a simple "Hello World" app using Java and Struts 2. I understand the simple stuff. My problem is that I'm trying to expand that learning and build a large scale app, and I just don't see how to connect the dots.
Scenario:
I've got three views to begin with: Home.jsp, MyAccount.jsp, Contact.jsp. Each has the following HTML:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="js/common.js"></script>
...
</head>
<body>
<!-- If logged in, says "hello <s:property name="username">"
Else displays link to .show() #loginPane -->
<div id="accountHeader">...</div>
<!-- Displays <s:textfield> tags and <s:submit> tag to accept username and password -->
<div id="loginPane" style="display: none">...</div>
<header>...</header>
<nav>...</nav>
<!-- Displays view-specific content that includes Struts 2 tags -->
<div id="content">...</div>
<footer>...</footer>
</body>
</html>
So, obviously there is a lot of code common to each view (anything not in #content div).
How do I architect these views for code reuse?
What I've tried:
Placing common code in common.js and using jQuery .html() calls to populate <div>s. [Doesn't work because jQuery cannot generate code with <s:> tags.]
Using only one .jsp view file and placing view-specific code in common.js to be generated with jQuery .html() calls. [Doesn't work for the same reason -- jQuery cannot generate code with <s:> tags.]
Placing all view components in .jspf files and loading each with jQuery .load() calls from common.js. [Doesn't work -- I'm guessing the .jspf files need the Struts 2 <%taglib ...%> included in each, but jQuery .load() treats the <%taglib ...%> as text to be displayed in the <div>... and also fails to properly generate the <s:> tags.]
What is the proper way to do this? How do I architect my view(s) for code reuse?
My apologies if this isn't the proper forum to ask for architecture help, but I'm really struggling here... Perhaps point me to a more appropriate forum or an online tutorial that addresses this type of architecture?
Thanks in advance!
I've used several methods to accomplish this type of re-use of code including Tiles and tooling around with Sitemesh and other template frameworks. What I've found is that, much as Steven Benitez, in the end I preferred to use JSP taglibs, native Struts2 taglibs, and JSTL to essentially build out my own templating routines. The main reason I prefer this is that there tends to be less overhead and it's been a lot easier to maintain and extend in the long run.
Generally What I do is define my base template, index.jsp for example, and then in each independent Struts controller class I will define what page fragment is used. I try to split my controllers up in such a way that each page or function is handled by a single controller and I implement the Preparable interface. This way I can set a parameter for the page to reference. Sometimes I set it as a variable in the controller class, sometimes a sessions variable depending on what type of stating I need for the application.
Once I have a variable with the page to reference, I can just use a JSTL import or Struts include tag to load the page fragment.
The controller class would look something like this:
#Results({
#Result(name = "success", location = "/WEB-INF/content/index.jsp")
})
public class IndexController extends RestActionSupport implements Preparable{
private String page;
private String pageTitle;
#Override
public void prepare() throws Exception {
page = "home";
pageTitle= "My Home Page";
}
...
}
And then the JSP would look something like this:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%# taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title> ${pageTitle}</title>
</head>
<body>
<c:import url="${page}.jsp" />
</body>
</html>
EDIT: Fragment page example:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%# taglib prefix="s" uri="/struts-tags"%>
<div>
<h1>Welcome Home!</h1>
</div>
<script type='text/javascript'>
$(document).ready(function() {
// page specific scripting if needed
);
</script>
You can encapsulate common template code in JSP tag files, as explained in this answer or you can also use decorator frameworks such as Tiles or SiteMesh to do this.
Personally, I prefer JSP tag files. Do not attempt to write out HTML with jQuery or to put all of your code into a single JSP.

Why my included JSP file won't get processed correctly?

I am trying (and learning) to build a java web framework, and in the process of developing its' code generator based on the content of the database. In the view making process, I stumble in a difficulty, which I don't know how to solve it.
Firstly, I want all the pages to be created using the following index.jsp :
<body>
<%# include file="header.jsp" %>
<hr/>
<%# include file="body.jsp" %>
<hr/>
<%# include file="footer.jsp" %>
</body>
And, in the body.jsp, I want it to be like this :
<jsp:include page="${application_modul}" %>
Where application_modul is an attribute defined in its' controller this way :
request.setAttribute("application_modul","user_account\\view_user_account.jsp");
It can find the file correctly, but the processed jsp is not what I expected. Here :
<c:forEach items="[application.models.UserAccountModel#18a49e0, application.models.UserAccountModel#1f82982]" var="item" varStatus="status" >
<tr>
....
You can see the items attribute of jstl forEach, got its variable name (toString())...
Any Idea what the problem is????
I hope I describe my problem correctly
Many thanks!
PS :
I already create a quick fix for this, but not what I want it though. In the generated view_user_account.jsp, I do it like this :
<body>
<%# include file="header.jsp" %>
<hr/>
<c:forEach items="${row}" var="item" varStatus="status" >
<tr>
....
<hr/>
<%# include file="footer.jsp" %>
</body>
You can see that I create the whole file here...
EDITED:
PS : ${row} is an ArrayList populated with data from certain table
So, to summarize your problem in a single sentence, JSTL tags are not been parsed and they end up plain in generated HTML output?
You need to declare JSTL taglib in top of the JSP page where you're using JSTL tags to get them to run. For the JSTL core taglib, that'll be
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
I am not sure but, Try this...
index.jsp
<jsp:param name="parameterName" value="{parameterValue | <%= expression %>}" />

JSP, can it work similar to yield, layout, content_for in Ruby/Rails/Erb

I am trying to figure out how to most effectively reuse JSP code.
I love the way Rails/erb works in that way ... with yield, layout, content_for
Example:
main_layout.erb.html
<html>
<head><%= yield :head %></head>
<body><%= yield %></body>
</html>
use
<% content_for :head do %>
<title>A simple page</title>
<% end %>
<p>Hello, Rails!</p>
in controller
layout "main_layout"
What is the closest I can get to this with JSP (without using extra frameworks)? I know about JSP include but that's not really the same as yield.
Any suggestions?
Thanks
I'm not familiar with what yield and content_for provide, but JSP tag files allow you a more robust way to template pages than JSP includes.
Example:
layout.tag
<%# tag body-content="scriptless" %>
<%# attribute name="pageTitle" required="true" type="java.lang.String" %>
<html>
<head>
<title>${pageTitle}</title>
</head>
<body>
<jsp:doBody/>
</body>
</html>
An individual JSP
<%# taglib prefix="z" tagdir="/WEB-INF/tags" %>
<z:layout pageTitle="A simple page">
<p>Hello, JSP!</p>
</z:layout>
Just place your layout.tag in the /WEB-INF/tags directory. You can use any available prefix you want, I just used "z" for the example.
While you mentioned wanting no frameworks on top of stock jsp, the Layout functionality of the Stripes Framework does pretty much exactly what you're asking for.

Passing an ArrayList from a Servlet to JSP

my model returns an arraylist of strings to servlet in the form
ArrayList<String> currentCustomer = model.getAllCustomers();
i want to pass this arraylist from the servlet to the jsp page. how do i do this? below is what i tried
req.setAttribute("currentCustomer", currentCustomer);
and in the jsp page, i want to use JSTL to loop over each value and display it. how do i do that? its frustrating me to no end. ive scoured the web but to no avail. any help is greatly appreciated.
here is the jsp code
<%# taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<body>
<div>
<c:forEach var="customer" items="currentCustomer">
${customer}
</c:forEach>
</div>
</body>
Let's make it work :)
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<c:forEach var="customer" items="${currentCustomer}">
<c:out value="${customer.name}" />
<c:out value="${customer.age}" />
</c:forEach>
P.S. jsp:useBean is another way to go...
P.P.S. I also made a correction in the taglib import. That's one of these hard-visible mistakes when you can look on two different entries and think they are the same :)
its allrite guys, i solved the problem.. thanks for your help..
apparently the code i was using was outdated (thanks internet!) i was writing this on the header:
<%# taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
while it should have been
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
It will be smt like
<c:forEach var="currentCustomer" items="${customers}">
${currentCustomer.name}
${currentCustomer.age}
</c:forEach>

Categories