Showing posts with label jsp. Show all posts
Showing posts with label jsp. Show all posts

Using Scriplt variable in JSTL


<%
List<UserPublicProfile> top3Users = UserUtils.getTop3Users();
    pageContext.setAttribute("top3Users", top3Users);

pageContext.setAttribute("top3Users", top3Users);   

%>

 <c:forEach items="${top3Users}" var="user"> 
                        <td align="left" valign="top" width="76px" >
                        <c:set var="photoUrl" scope="page" value="https://${user.profilePhotoUrl}"/>                       
                           <img class="top_img" src="${photoUrl}" width="73" height="79">
                        </td>
                        <td align="left" valign="top"  class="top_data">
                           <label class="top_name">${user.name}</label><br>
                        <p class="rank_font">Rank :<label class="top_rank">${user.rank}</label></p>
                        <p class="rank_font">Votes :<label class="top_rank">${user.votes}</label></p>
                        </td>
                     </c:forEach>

Encoding non english chars with utf 8 on jsp

Use this in your jsp file as header


<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

why JSTL number format value does not support runtime expressions? or "value" does not support runtime expressions

1. Check the version of the jstl.. it should be jstl 1.1+

(You're using the prehistoric JSTL 1.0 version (or even a prototype). You need to upgrade to at least JSTL 1.1, or if your container supports it (Servlet 2.5 or newer), upgrade to currently latest JSTL 1.2.
You can find JSTL download links in our JSTL wiki page. Don't forget to remove the old JSTL libraries (jstl.jar and standard.jar) and to fix the @taglib declarations to include the /jsp path. Also ensure that your web.xml is declared conform at least Servlet 2.4 for JSTL 1.1 or as at least Servlet 2.5 for JSTL 1.2.)


2. Ensure that your @ taglib directive. Replace:
 
<%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt"%>

for this:
 
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>

The /jsp makes the difference.

Create or Load grid on Button click

<script>

$(document).ready(function () {
    $("#action").click(function () {

      alert('button clicked');
});
});
</script>

<input value="ACTION" name="action" id="action" type="button">

Using Java Function in Jsp Using Jstl

We can use Java functions in jsp using JSTL using the TLD file. This has been covered already.

And another method to use is,

<% pageContext.setAttribute("keyName", RoleMenuEnum.Manageuser.getLabelName()); %>

Like this.

And usage would be,
<c:when test="${some == keyName}"/>...c:when>

Filters for JSP Pages

<filter>
   <filter-name>LogFilter</filter-name>
   <filter-class>LogFilter</filter-class>
   <init-param>
   <param-name>test-param</param-name>
   <param-value>Initialization Paramter</param-value>
   </init-param>
</filter>
 
<filter>
   <filter-name>AuthenFilter</filter-name>
   <filter-class>AuthenFilter</filter-class>
   <init-param>
   <param-name>test-param</param-name>
   <param-value>Initialization Paramter</param-value>
   </init-param>
</filter>
 
<filter-mapping>
   <filter-name>LogFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>
 
<filter-mapping>
   <filter-name>AuthenFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>
 
 
The order of filter-mapping elements in web.xml determines the order in which the web container applies the filter to the servlet or JSP. To reverse the order of the filter, you just need to reverse the filter-mapping elements in the web.xml file.
For example, above example would apply LogFilter first and then it would apply AuthenFilter to any servlet or JSP but the following example would reverse the order:

<filter-mapping>
<filter-name>AuthenFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
 

How to include a JSP or HTML page in another JSP page

<%@ include file="relativeFragment.jsp" %>
 
eg:
<body onload="onLoad();" style="padding-bottom: 0px;">
 <form name="addRoleForm" method="post" action="../Admin/AddRole">
  <%@ include file="/pages/roleslist.jsp" %>     
 </form>
</body>  

Java Script Validation for UserName

Alphabets, numbers and space(' ') no special characters min 3 and max 20 characters.
Starts with an Alpahbet.

var ck_name = /^[A-Za-z][A-Za-z0-9 ]{3,20}$/;

functiuon test()
{
    ck_name.text(username) == true;
}

document.getElementsByName

document.getElementsByName("test");
 
We can get the Element Object by using the above method.
But we should not use this method on any dynamic elements like 
 
1. Radio Buttons
2. Check Boxes
 
etc..
 
If test is a name of Checkbox.
 
document.getElementsByName("test").checked will give 'undefined' output.

Use,

document.getElementById("test").checked will give true or false.
  

Loop through Array in Java Script

var myStringArray = ["Hello","World"];
for (var i = 0; i < myStringArray.length; i++) {
    alert(myStringArray[i]);
    //Do something
}
 
Hello
World 

Using JSP Value in JSTL

JSTL is executed in server side by your servlet container for which Javascript is just a text which would be skipped whereas JavaScript is executed in client side where JSTL is unknown. After the server completes processing JSTL, the generated HTML(if any) from the JSTL along with other JavaScript/HTML will be rendered.

When you pass a JSTL object to a Java Script function , then it will be treated as a String in the Java Script Function. Remember when you pass the values, the total values will be converted as plain String. Or if you send an Object, it will rendered as Object.toString().

So to pass variable to Java Script Function from the JST, Use the following method.

Requirement:

function checkSelection(group,tvalue){
alert(group);
alert(tvalue);
<c:forEach items="${configuredGroupMap}" var="groupMap">
    alert("aa<c:out value="${groupMap.key}"/>");
    <c:if test="${groupMap.key==group}">
        alert("t<c:out value="${groupMap.key}"/>");
        <c:if test="${groupMap.value==tvalue}">
            alert("equal");
        </c:if>
    </c:if>
</c:forEach>
}
 
it wont go inside after
 <c:if test="${groupMap.key==group}">
 
Use like this:

function checkSelection(group,tvalue){ 
alert(group); 
alert(tvalue); 
<c:forEach items="${stringshm}" var="groupMap"> 
    alert("<c:out value="${groupMap.key}"/>"); 
    var groupKey = "<c:out value="${groupMap.key}"/>";

    if (groupKey == group){
        alert("<c:out value="${groupMap.key}"/>"); 

    var groupValue = "<c:out value="${groupMap.value}"/>";
        if (groupValue == tvalue){
            alert("both are equal"); 
    }
    }
</c:forEach> } 
 
 

How to include parameters with Jsp:include

<jsp:include page="callee.jsp" />
    <jsp:param name="param2" value="value2" />
    <jsp:param name="param3" value="value3" />
</jsp:include>

Appending html to div tag using jstl and jquery function

http://stackoverflow.com/questions/6315210/problem-with-appending-html-and-jstl-code-in-a-div-object-using-jquery

Jstl Usage

Hi  Dove :)

Just wondering, how much am addicted to you.
I mean, you been the total inspiration at each part of the life :)
Lately, i been enjoying all the little pleasures of life and making others happy. Just like you do all the time :)

At each part, each second of life.. you are on my mind.Thanks for the total smiles and inspiration.
And this JSTL, you taught me, how to learn things easily.

Its total your inspiration that lean me to learn Jsp, JSTL, CSS and all. Now am total confident in all these.
I wish i would have that all my life. Yet am lucky to know you in this life.

Love you dove  :)


<%@ page language="java" contentType="text/html"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%@ taglib uri="/resource/tlds/UserActionRoles.tld" prefix="UserActionRoles" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add Users</title>
<script type="text/javascript"
    src="<c:url value="/resource/js/jquery.min.js"/>"></script>
<script type="text/javascript"
    src="<c:url value="/resource/js/jquery-ui.min.js"/>"></script>
<link rel="stylesheet"
    href="<c:url value="/resource/css/overcast/jquery-ui.css"/>"
    type="text/css"></link>
<link href="<%=request.getContextPath()%>/resource/css/layout.css"
    rel="stylesheet" type="text/css">
<link rel="stylesheet" href="<c:url value="/resource/css/style.css"/>"
    type="text/css"></link>

<script type="text/javascript">


   
    $(document)
            .ready(
                    function() {
                        $("input:submit, a, button").button();
                        $(".portlet")
                                .addClass(
                                        "ui-widget ui-widget-content ui-helper-clearfix ui-corner-all")
                                .find(".port-header").addClass(
                                        "ui-widget-header ui-corner-all")
                                //.prepend( "<span class='ui-icon ui-icon-minusthick'></span>")
                                //.end()
                                .find(".portlet-content");
                       
                       
                       
                    });
       
    jQuery(document).ready(
           
            function($){
                    $('#panel').fadeOut('slow', function() {                       
                      });
                $("#imgexp").toggle(function(){
                    $("#panel").hide();
                    $('#main_header').css('margin-top','25px');
                },
                function(){
                    $("#panel").show();
                    $('#main_header').css('margin-top','0');
                    $("#panel").attr('title', 'This is the hover-over text');

                }

                 );
                /* $("#btn-submit").click(function () {
                    $("#roleName_Div").effect("shake", {times: 2, distance: 2}, 50);
                }); */
            }
        );
</script>

<c:set var="uarVariableNames" scope="page" value="${UserActionRoles:getNames()}"/>
<c:set var="uarVariableValues" scope="page" value="${UserActionRoles:getVariables()}"/>
<c:set var="EditFlag" scope="page" value = "${param.EditAction}" />
<c:set var="EditRoleName" scope="page" value = "${param.RoleName}" />

<script type="text/javascript">

function beforeSubmit()
{
    if(document.getElementById('roleName') != null)
    {
        var roleName = document.getElementById('roleName').value;
        if(roleName == null || roleName == "")
        {
            document.getElementById('roleName').value = 'Plz enter Role Name';
            document.getElementById('roleName').style.color = "red";
           
            return false;
        }
    }
   
    var atleastOne = false;
   
    <c:forEach var="i" begin="0" end="${fn:length(uarVariableValues) -1}" >       
        <c:set var="variable_name" value="${uarVariableValues[i]}" />
        var temp = document.getElementById("${variable_name}").checked;
       
        /* <c:if test="fn:containsIgnoreCase(variable_name, 'delete') == true" >
            <c:set var="deleteRole" value = "true" />
        </c:if> */
       
        if(temp == true)
        {
            document.getElementById('tempValue').value = 1;
            atleastOne = true;
        }
        else
        {
            document.getElementById('tempValue').value = 0;   
        }
       
        /*
        <jsp:useBean id='UserActionRoles' class='com.arrayshield.sdk.asas.adminRoles.UserActionRolesTable'>
            <c:set target='${UserActionRoles}' property='${uarVariableValues[i]}' value=''/>
        </jsp:useBean>
        */
       
    </c:forEach>
   
/*     if('${deleteRole}' == true)
    {
        alert('here');   
    }
 */
     if(atleastOne == false)
     {
        var answer = confirm ("Add role with no roles at all?");
        if (answer)   
        {
            document.addRoleForm.submit();
        }
       
        return false;
     }
   
    document.addRoleForm.submit();
}

function focus()
{
    if("${EditFlag}" == 0)
    {
        document.getElementById('roleName').value = "";
        document.getElementById('roleName').autocomplete = "off";
        document.getElementById('roleName').focus();
    }
    else
    {
        document.getElementById('EditAction').value = "EditAction";
        document.getElementById('roleName').value = "${EditRoleName}";
        document.getElementById('roleName').readOnly = true;
        document.getElementById('btn-submit').value = "Update Role";
    }
}

function onFocus()
{
    document.getElementById('roleName').value = "";
    document.getElementById('roleName').style.color = "brown";
}

</script>
        <body onload="focus();" style="padding-bottom: 0px;">
            <form name="addRoleForm" method="post" action="../Admin/SaveOrUpdateRole">
   
   
                    <input type="hidden" id="tempValue" name="tempValue" >                   
                    <input type="hidden" id="EditAction" name="EditAction" >
                   
                <!-- Expander Help Text -->
                <!-- <img id="imgexp" style="float:left;" alt="Expand Div" src="../resource/images/inlinehelp1.png"/>
                <div id="panel" class="expander_text">
                    <font size="-1" id="fonttext" face="Arial">This feature enables you to add
                        role into the IDAS system.</font>
                </div> -->
               
                <!-- Main Header -->
                <!-- <div id = "main_header" class="port-header ui-widget-header ui-corner-all" style="width:30%; text-align:center;margin:20px auto;">Add Role</div> -->
                                           
                <div id="roleName_Div" style="background-color: #E7E6E6;margin-bottom: 13px;margin-left: 23%;margin-top:
                            40px;padding: 16px; width: 50%;border-radius:10px">
                    <font style="font-size:19px;padding-right:30px;">Role Name</font>
                    <input class= "input_role" type="Text" id="roleName" name="roleName" size="50" maxlength="50"
                            onfocus="onFocus()" />
                </div>
                      <div id="user_management_roles" class="expander_text" style="margin-left:10%;height:50%">
                      <table style="margin-left: 125px;width:100%">   
                        <c:forEach var="i" begin="0" end="${fn:length(uarVariableNames) -1}" >                     
                            <c:set var="flag" scope="page" value="${!flag}" />
                              <c:if test = "${flag eq true }">
                                  <tr>
                              </c:if>   
                              <c:choose>
                                  <c:when test='${flag eq "true"}' >
                                        <td >
                                          <input type="checkbox" id="${uarVariableValues[i]}" value="1" >
                                        <font style="font-size:17px;padding-right:30px;"><c:out value="${uarVariableNames[i]}"/></font>
                                    </td>
                                </c:when>
                                <c:otherwise>
                                    <td>
                                          <input type="checkbox" id="${uarVariableValues[i]}" value="1" >
                                        <font style="font-size:17px;padding-right:30px;"><c:out value="${uarVariableNames[i]}" /></font>
                                    </td>
                                </c:otherwise>
                            </c:choose>
                            <c:if test = "${flag eq false }">
                                  </tr>
                              </c:if>
                          </c:forEach>
                    </table>       
                    </div>               
               
                <div style="margin: 0 auto;padding-top: 15px;width: 13%;">
                <input type="button" value="Add Role" id="btn-submit" class="submit_button" onclick="return beforeSubmit();">
                </div>
                               
            </form>
        </body>
   
</html>

Regular Expressions

Always use PROPER Regular Expression for Validations both in JSP and Servlet.
This saves time, efficiency and Code.

Before passing to the regEx just check the null validation and that's it. Yours all.

public boolean isNumeric(String stringValue) {
if(stringValue != null)
{
Pattern pattern = Pattern.compile( "\\d+" );
Matcher matcher = pattern.matcher(stringValue);
return matcher.matches();
}
else
{
return false;
}
}

RegEx for checking a String is Numeric or not.

Table Width

Few points to note:

Always mention the table width as percentage. like 100%
And then we can divide that 100% equally with the Td width

like
We can define the a single td, if we want using colspan.
This way it is easy to manage the widths.

Fade Out : Label fades out

Using JQuery:
$("#elementId").fadeOut(time, ActionFunction);

$("#errorMessage3").fadeOut(10000, null);

use this one, to fadeout any lable or element.

Using Java Script:



Autocomplete

Autocomplete=off is used to set for the input fields inhtml. But this shows a warning like attribute not defined. this is not defined by w3c standards. So it throws the warning. This is introduced by MS.

Use it like document.getElementById("elementId").setAttribute("autocomplete", "off");

this will not throw any warning.