• No results found

Hidden form fields:

In document 6242166-JSPCompleteTutorial (Page 28-53)

HTML forms have an entry that looks like the following: <INPUT TYPE="HIDDEN"

NAME="session" VALUE="...">. This means that, when the form is submitted, the specified name and value are included in the GET or POST data. This can be used to store information about the session. However, it has the major disadvantage that it only works if every page is dynamically generated, since the whole point is that each session has a unique identifier.

Security in JSP -2

The user can also use the html forms to accept the username and password. This helps to establish the application level or module level security in web world. All sites follow the different security policies and standards. It is always better to use the application managed security for better results. Also, when the application is moved to some other servers then it hardly impacts the application managed security. The following example will demonstrate a form and shows the welcome message if user enters the correct username and password.

Example:-<% String action= request.getParameter("action");

if(action != null && action.equals("submit")){

String username=request.getParameter("username");

String password=request.getParameter("password");

if(username != null && password != null &&

username.equals("visualbuilder") && password.equals("test")) {

out.println("<h3>welcome to the page</h3>");

}else{

out.println("<h3>Wrong password!!!!</h3>");

}

}else{

%>

<html>

<form action="formsecurity.jsp" method="post">

<input type="hidden" name="action" value="submit">

Enter the user name :- <input type="text" name="username" ><br>

Enter the password :- <input type="password" name="password"

><br>

<input type="submit" name="submit" value="submit">

</form>

</html>

<%}%>

Security in JSP -1

Security is defined as the condition of being protected against danger or loss. The security is very important in any web application as the web applications are mostly exposed to all the people in the world. The levels of security can be

Transport Level security using HTTPS.

Authentication and Authorization

Role Based Access Control

Container-managed Security

Application-managed Security.

The web application can be configured to use any level of security as per the requirement and criticality of the site.

Container Managed Security Vs Application Managed Implementation For Container Managed

Implementation For Application Managed

Container Managed Application Managed

Authentication and

Authorization are specified in web.xml.

It uses multiple authentication schemes, such as Password Authentication Form-based Authentication Client side Digital Certificates etc..

Redirects are handled automatically.

Internationalization in JSP application

Few years back, the sites were developed using a single language and the developer used to create the sites to their specific languages. As the globalization occured, many frameworks have developed to support the multiple languages at a time. Now this can be achieved by having the multi language text in key/value pair and at runtime the text is read from the key as per the language required. This multilingual support is known as Internationalization. Internationalization is defined as the process of designing an application so that it can be adapted to various languages and regions without engineering changes.

The following classes are used to implement Internationalization to any site.

Locale - The fundamental Java class that supports internationalization is Locale . Each Locale represents a particular choice of country and language, and also a set of formatting assumptions for things like numbers and dates.

ResourceBundle - The java.util.ResourceBundle class provides the fundamental tools for supporting messages in multiple languages.

PropertyResourceBundle - One of the standard implementations of Resource Bundle allows you to define resources using the same

"name=value" syntax used to initialize properties files. This is very convenient for preparing resource bundles with messages that are used in a web

application, because these messages are generally text oriented.

Note:- The fmt is the jstl tag library used to implement the

internationalization in JSP. The below example will tell you "how to use the fmt taglib in the application". The example displays the text coming from the different properties files. The properties file lables.properties is

created with different locale suffix example en is for english, de for Germany etc. We have hello key in both the files. hello=This is german File in de file and hello=This is english File in english file.

Example JSP file Internationalization.jsp file .

<%@ taglib prefix="fmt" uri="/WEB-INF/fmt.tld"%>

Introduction To Expression Language.

A primary feature of JSP technology version 2.0 is its support for an expression language (EL). An expression language makes it possible to easily access

application data stored in JavaBeans components. As the EL is introduced in JSP 2.0, we can also use the page attribute isELIgnored to ignore the EL for a page.

<%@ page isELIgnored ="true|false" %>

The following is the EL operator table which can be used with the EL language.

Note:- and,eq,gt,true,instanceof,or,ne,le,false,empty, not,lt,ge,null,div and mod are reserved words in the EL so user cannot use these words for the identifiers.

Expression

<%-- Compares with

"equals" but returns

Introduction to Tag libraries

JSTL is a component technology within the Java 2 Enterprise Edition (J2EE)

specification and is controlled by Sun Microsystems. JSTL is nothing more than a set of simple and standard tag libraries that encapsulates the core functionality

commonly needed when writing dynamic JSP pages. The following are the problems with the

JSPs:-1. Java code embedded within scriptlet tags is ugly and obtrusive.

2. It is very difficult to modify the java code embedded in the JSP files if the file is large.

3. Java code within JSP scriptlets cannot be reused by other JSP pages.

4. Retrieving objects out of the HTTP request and session is cumbersome and type casting to the object's class is required.

The JSTL tags are basically categorized into four libraries:

core:- Basic scripting functions such as loops, conditionals, and input/output.

fmt:- Internationalization and formatting of values such as currency and dates.

xml:- XML processing

sql:- Database access.

Advantages of using

JSTL:-• JSTL tags are XML based tags which are cleanly and uniformly blend into a page's HTML markup tags.

The four JSTL tag libraries include most functionality that would be needed in a JSP page. JSTL tags are easier for non-programmers and inexperienced programmers, because they do not require any knowledge of Java

programming.

JSTL tags encapsulate reusable logic such as formatting dates and numbers.

JSTL tags can reference objects in the request and session without knowing the object's type and no casting is required.

JSP's EL (Expression Language) makes it easy to call getter and setter methods on Java objects. This is not possible in JSP 1.2, but became available in JSP 2.0. EL is used extensively in JSTL.

JSTL Drawbacks:

JSTL can add processing overhead to the server. Both Java scriptlet code and tag libraries are compiled into a resulting servlet, which is then executed by

Introduction To Core Taglib -1

Core taglib is the important taglib in the JSTL. It includes the core concepts of the programming like declaring the variable, decision making tags etc.. The next sections will explain all the core taglib tags, which are generally used in the programming.

Standard Syntax:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

Variable Support Tags

The <c:set> tag sets the value of an EL variable or the property in any of the JSP scopes (page, request, session, or application). If the variable does not exists, it will be created.

The JSP EL variable or property can be set either from the attribute value:

<c:set var="var" scope="session" value="..."/>

OR

<c:set var="var">

...

</c:set>

To remove an EL variable, you use the <c:remove> tag as follows:

<c:remove var="test" scope="session"/>

Conditional Tags

The <c:if> tag allows the conditional execution of its body according to the value of the test attribute. The syntax of the <c:if> conditional block is as follows:-

<c:if test="${condition}"> </c:if>

The <c:choose> tag performs conditional block execution by the embedded

<c:when> tags. It renders the body of the first <c:when> tag whose test condition evaluates to be true. If none of the test conditions evaluates to be true, then the body of <c:otherwise> tag is evaluated, if present. The syntax is as follows :-

<c:choose>

<c:when test="condition1" >

Introduction To Core Taglib -2

Iterator Tags

The <c:forEach> tag allows you to iterate over a collection of objects. You specify the collection via "items" attribute, and the current item is available through a variable named given in the "var" attribute. A large number of collection types are supported by <c:forEach>, including all implementations of java.util.Collection and

java.util.Map. If given collection is of type java.util.Map, then the current item will be of type java.util.Map.Entry, which has the following properties:

key: The key under which the item is stored in the underlying Map

value: The value that corresponds to the key

Arrays of objects as well as arrays of primitive types (for example, int) are also supported. For arrays of primitive types, the current item for the iteration is

automatically wrapped with its standard wrapper class (for example, Integer for int, Float for float, and so on).

<c:forEach var="item" items="collection">

</c:forEach>

or

<c:forEach begin="0" end="10" varStatus="status" step="1" >

</c:forEach>

URL Tags

The <c:url> tag is used to create the URL for the submit actions or the hyperlinks.

The <c:url> tag is used to create the URL variable and <c:param> is used to add the parameters in the <c:url> tag. The syntax is as

follows:-<c:url var="var" value="..." >

<c:param name="param1" value="val1" />

</c:url>

Example:-<%@ taglib uri="/WEB-INF/c.tld" prefix="c" %>

<%

String[] value = new String[10];

value[0]="one";

value[1]="two";

value[2]="three";

value[3]="four";

value[4]="five";

Function Taglib

The function taglib contains the basic String functions for the JSTL functionality.

Standard Syntax:

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

java.lang.Strin g

substring ( java.lang.String

, int, int)

Returns a subset of a

string.

java.lang.String

substringAfte r (

java.lang.String ,

java.lang.String

Database Handling in JSP.

The database interaction with the JSP page is similar to the core JDBC interaction.

The complete JDBC code for the database interaction is to be written in the scriptlet tags. The following example shows the process of database handling with the JSP page. The following example will display the total hit for the current page and update the counter in the database.

<%@page import="java.sql.*" %>

<%

int hitCount=0;

try{

Class.forName("org.gjt.mm.mysql.Driver");

Connection connection =

DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root",

"root");

Statement statement = connection.createStatement();

int changed = statement.executeUpdate("update counters set hitCount = hitCount + 1 " +"where page like '" + request.getRequestURI() +

"'");

if (changed == 0) statement.executeUpdate("insert counters(page) values('" + request.getRequestURI() + "')");

ResultSet rs = statement.executeQuery("select hitCount from counters where page like '" + request.getRequestURI() + "'");

rs.next();

out.println("The hit count is " +hitCount );

%>

Output:-The page prints "Output:-The hit count is 5" as output.

Creating User Defined Custom Tag -1

The most powerful feature of JSP is that - the user can also create their own custom tags. The servlet API contains the

javax.servlet.jsp.tagext.BodyTagSupport class, which is used to create the custom tags. All the tags need to extend the

javax.servlet.jsp.tagext.BodyTagSupport class and override doStartTag(), doEndTag() and doAfterBody() methods. After creating the Java class for the custom tag, the tag library description file is to be created. The extension for the XML description file is .tld. The following example will create a tag, which takes String and prints the reverse of the String when displayed on the browser.

ReverseTag.java

public class ReverseTag extends BodyTagSupport { private static final long serialVersionUID = 1L;

public int doStartTag() throws JspTagException{

return EVAL_BODY_TAG;

}

public int doEndTag() throws JspTagException { try {

public int doAfterBody() throws JspTagException {

Creating User Defined Custom Tag -2

The following is the tag lib descriptor file for the reverse tag.

<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

<taglib>

<tlibversion>1.0</tlibversion>

<jspversion>1.1</jspversion>

<shortname>Visualbuilder</shortname>

<info>Visual builder Tag library</info>

<tag>

<name>stringreverse</name>

<tagclass>com.visualbuilder.taglibrary.ReverseTag </tagclass>

<info>

<%@ taglib uri="/WEB-INF/reverse.tld" prefix="reverse" %>

<html>

<head>

<title>Your Custom Tag library</title>

</head>

Best Practices in JSP

There are some standard practices that can be followed while writing the JSP files. The standards of writing JSP code helps to develop the

application easily and effectively. It reduces the complexity and the debugging time for the JSP application. The following are the best practices, while working on JSP application:-

Separate HTML from Java:- For small JSP files with least of logic, it seems as best to have the Java and html in the same JSP file as all available resources and dependencies are in the same file. As the JSP's go on to higher complexity, this approach fails as the code becomes

complex and less readable and hard to understand.

Place business logic in JavaBeans:- We must write our business logic in JavaBeans as the code will be reused anywhere in the application. Also if any logical change occurs during the development so it requires to change only at one place and hence avoiding rework everywhere.

Factor general behavior out of custom tag handler classes:- If we are using custom tags then we must tend to write the common code in a Java file separately instead of writing inside the customTagHandler. Because Handler classes are not readily used like ordinary Java utility classes rather Handler classes can access the utility classes easily.

Favor HTML in Java handler classes over Java in JSPs:- Sometimes cleanly separating HTML, JSP tags, and HTML-like custom tags from Java requires unnecessarily convoluted code. In these cases, you either include Java scriptlets and expressions in the JSP or put some HTML code in the Java tag handler class.

Use an appropriate inclusion mechanism: - The JSP is a combination of the tags and the Java code. It is very difficult to maintain the two types of code in a single file. JSP gives us the flexibility to create the multiple JSP pages and then call those JSP pages into the complex page wherever required.

Use a JSP template mechanism:- Using templates is the best approach when we can see the total structural changes in the look and feel of the page.

It is not a good way to change each and every JSP page for the html

changes, rather we will define the layout of the page in a JSP and will use the templates mechanism to import the contents of different portions from different JSP's through templates. So, when you want to change the layout, you need to modify only one template file rather making changes in all pages.

Use stylesheets:- We must use CSS to give the styles to different components across the site, providing same CSS styles to similar kind of components. If we want to change the look of a particular type of component throughout the website, we are required to change one style only and it will be reflected everywhere.

In document 6242166-JSPCompleteTutorial (Page 28-53)

Related documents