How to have dynamic css files depending on struts session variable - java

I have a webpage in which i want the css file to be the same name as a session variable I have set.
For example;
If the session variable was "blue", i want the page to load the CSS file blue.css.
I tried something below which didnt work, and I'm now stuck. My knowledge of struts is very limited.
<LINK rel="stylesheet" type="text/css"
href="<html:rewrite page='/css/<c:out value="${brand}"/>.css'/>">
This is the full code listing at the top of my jsp page
<%# taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%# taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%# taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%# taglib uri="http://jakarta.apache.org/struts/tags-html-el" prefix="html-el"%>
<html:html lang="true">
<head>
<LINK rel="stylesheet" type="text/css" href="<html:rewrite page='/css/${brand}.css'/>">
<html:base/>
I do not know how to find the version of JSP and JSTL I am using. This was a project picked up from someone else and I have never used them before

It isn't working because you put the c:out tag inside the attribute of the html:rewrite tag. Struts tags don't parse when within attribute values.

href="<html:rewrite page="/css/${brand}.css"/>">

according to another user you cant have html rewrite in the attribute but maybe you can do something like below and rewrite the whole link?
<html:rewrite page='<LINK rel="stylesheet" type="text/css" href="/css/${brand}.css"/>'>

Unfortunatily, I couldnt not get any of your answers working. I think it may be a problem with my versions clashing.
For now I have managed to do it by doing;
<%
String brand = (String) session.getAttribute("brand");
if (brand == null || brand.equals("")) {
skin = "standard";
}
%>
<link href="/css/<%=brand%>.css" rel="stylesheet" type="text/css" />

Try this java script, It will work.
variable code is a hidden field in ur jsp.
var code=(document.getElementById('code')).value;
var url;
// Dynamically loads the Style Sheet according to the user logged in
if(code !== null)
{
url="<link rel='stylesheet' type='text/css' href='css/"+code+".css' title='default'>";
}
else
{
url="<link rel='stylesheet' type='text/css' href='css/commonStyle.css' title='default'>";
}
if(url !== null)
{
document.write(url);
}

Related

JSP couldnt link css files and js files

I am new to jsp. I am using Glassfish server from netbeans. Problem is that i could link my jsp file with css and javascripts. Here's the format of my file structure
Web Pages
--Web-Inf
--assets
--css
--style.css
--js
--jquery.js
--includes
--header.jsp
--footer.jsp
--sidebar.jsp
--pages
--home.jsp
--index.jsp
Here's the code in my index.jsp
<%#include file="includes/header.jsp" %>
<%
if (request.getParameter("page") == null) {
%>
<%#include file="pages/home.jsp" %>
<%
} else {
%>
<%
}
%>
<%#include file="includes/sidebar.jsp" %>
</div>
<!--Latest end-->
<%#include file="includes/footer.jsp" %>
And here's my code in header.jsp
<link href="${pageContext.request.contextPath}/assets/css/bootstrap.min.css" rel="stylesheet">
You can use relative urls to index.jsp
<link href="assets/css/bootstrap.min.css" rel="stylesheet">

JSP Encoder Issue While sending Russian character in QueryString

I have two jsp pages. I am trying to add "Russian" language. Russian characters are shown perfectly on jsp page, but when I try to send this value to another jsp page from parameter then in second jsp page this value is changed to different characters. This problem is only in Russian Language and not in others such as Italy and French.
For example
On demo.jsp page the russian character "приветствие" is shown correctly.
but when I try to send it to another page "test.jsp" then some unknown
characters are shown like "!C<Cä5 Cô>CôCC´OD=Cä5!"
Code:
demo.jsp
String welcometext=langP.get("welcome");
<jsp:include page="<%=test.jsp%>">
<jsp:param name="wlc" value="<%=Encode.hex8Code(welcometext)%>" />
</jsp:include>
In test.jsp
String title = Encode.utfToUnicode(Decode.hex8Decode(request.getParameter("wlc")));
System.out.println(" Russial welcome test "+welcome);
Is there any special code we need to add for Russia while sending them in query parameters??
Please note* the following code are already written else it would have given problem for French and Italy language too..
<%# page contentType="text/html; charset=UTF-8" %>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
Also tried with following but didn't help out!
request.setCharacterEncoding("UTF-8")
Try to add <% request.setCharacterEncoding("UTF-8"); %> to your main jsp page:
Here is my example:
demo.jsp
<%#page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<% request.setCharacterEncoding("UTF-8"); %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Привет</h1>
<jsp:include page="/test.jsp" flush="true">
<jsp:param name="wlc" value="Привет"/>
</jsp:include>
</body>
</html>
test.jsp
<h1>Param values is</h1>
<%
String hello = request.getParameter("wlc");
out.print(hello);
%>
I don't know the better solution but the following code solved this issue. I kept the variable in session attribute.
demo.jsp
session.setAttribute("welcometext", welcometext);
test.jsp
String welcometest=(String) session.getAttribute("welcometext");

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.

Adding a css file to the <head> element in a jsp file?

I have been searching the net for the last hour but I can't see how to add a css file to the <head> element of a page.
Say I have a jsp called shopping.jsp. And inside it I conditionally include a jsp tag file called products.tag.
I want products.jsp to specify a css file to add to the head element of the page. How can this be done?
EDIT
This code is simplified for the sake of example.
// shopping.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="t" tagdir="/WEB-INF/tags" %>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<t:standard_page>
<jsp:body>
<t:products product="${product}"/>
</jsp:body>
</t:standard_page>
// products.tag
// I want to specify a css file in this tag file that will get added to the <head> element of the webpage
<%#tag description="Template for products on the shopping cart page" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%#tag import="com.myapp.Product" %>
<%#attribute name="product" required="true" type="com.myapp.Product"%>
<div class="shopping-cart-row">
<div class="product-name">${product.name}</div>
<div class="product-quantity">${product.quantity}</div>
</div>
According to HTML5, <style> elements can appear inside
Any element that can contain metadata elements, div, noscript, section, article, aside
so you need not put <style> elements inside the <head> the way you do with <link> elements if you want your page to validate.
<style type="text/css">#import url("/path/to/stylesheet.css");</style>
from within the body will load the external stylesheet just fine.
If it's way down in the <body> or there are any long running non-deferred/async <script> elements before it, then those styles may arrive noticably later than styles loaded from the <head>.

how to use jquery autocomplete?

i am creating a web project using JSP, and is trying to implement a simple search for users from my database using jquery autocomplete, however i am having trouble understanding how it works. i have little to no knowledge on jquery and ajax just to let you know. i have done the following code and am stuck.
<%#page contentType="text/html" pageEncoding="UTF-8" import="ewa.dbConnect,ewa.sendEmail,ewa.pwGen,ewa.hashPw,java.sql.*" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/jquery.autocomplete.css" />
<script src="js/jquery.autocomplete.js"></script>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<input type="text" id="search" name="search"/>
<script>
$("#search").autocomplete("getdata.jsp");
</script>
</body>
</html>
getdata.jsp
<%#page contentType="text/html" pageEncoding="UTF-8" import="ewa.dbConnect,java.sql.*" %>
<%! dbConnect db = new dbConnect(); %>
<%
String query = request.getParameter("q");
db.connect();
Statement stmt = db.getConnection().createStatement();
ResultSet rs = stmt.executeQuery("SELECT username FROM created_accounts WHERE username LIKE "+query);
while(rs.next())
{
out.println(rs.getString("username"));
}
db.disconnect
%>
if i am not wrong i read from a website, the parameter q is default and is just there, however how do i display the data? how do i pass the values from getdata.jsp into the autocomplete?
You're calling the autocomplete script tag before jQuery has been included. So, not having jQuery to latch onto (as the jQuery object hasn't been defined), nothing from the jQuery autocomplete plugin will load.
You have
<script src="js/jquery.autocomplete.js"></script>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
It should be
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="js/jquery.autocomplete.js"></script>
Reverse the order, and the Firebug errors you mentioned should disappear; I'm not sure it'll solve everything, but nothing will work until that's resolved.
I don't see jQuery UI being included (that one provides the autocomplete functionality)
http://jqueryui.com/demos/autocomplete/
So you need to include jquery.ui.autocomplete.js
(Or are you using the plugin autocomplete? if so, move to the jquery UI version)
Could also be that the data from getdata.jsp is malformed for the use in autocomplete.
How you tried debugging the javascript in a browser such as chrome or in firefox(with firebug)
I usual give (for jquery UI autocomplete) a JSON formatted answer, while I see your answer loop give a CR delimited list.
In getdata.jsp instead of produce:
jim<cr>
jack>cr>
jhon<cr>
try to return:
[{label: 'jim', value: 'jim'}, {label:
'jack', value: 'jack'}, {label:
'jhon', value: 'jhon'}]

Categories