Kamis, 12 Februari 2009

Internet Programming with Java Course

Internet Programming with Java Course
3.9. JSP Custom Tag Libraries

Preface
This tutorial describes how to use and develop JavaServer PagesTM (JSPTM) tag libraries. The tutorial assumes that you know how to develop servlets and JSP pages and are familiar with packaging servlets and JSP pages into Web application archives. For information on these topics, see the resources and technical resources areas on the Sun Microsystems servlet and JSP technology Web sites.
What is a Tag Library?
In JavaServer Pages technology, actions are elements that can create and access programming language objects and affect the output stream. The JSP specification defines 6 standard actions that must be provided by any compliant JSP implementation.
In addition to the standard actions, JSP v1.1 technology supports the development of reusable modules called custom actions. A custom action is invoked by using a custom tag in a JSP page. A tag library is a collection of custom tags.
Some examples of tasks that can be performed by custom actions include form processing, accessing databases and other enterprise services such as email and directories, and flow control. Before the availability of custom actions, JavaBeans components in conjunction with scriplets were the main mechanism for performing such processing. The disadvantage of using this approach is that it makes JSP pages more complex and difficult to maintain.
Custom actions alleviate this problem by bringing the benefits of another level of componentization to JSP pages. Custom actions encapsulate recurring tasks so that they can be reused across more than one application and increase productivity by encouraging division of labor between library developers and library users. JSP tag libraries are created by developers who are proficient at the Java programming language and expert in accessing data and other services. JSP tag libraries are used by Web application designers who can focus on presentation issues rather than being concerned with how to access databases and other enterprise services.
Some features of custom tags are:
• They can be customized via attributes passed from the calling page.
• They have access to all the objects available to JSP pages.
• They can modify the response generated by the calling page.
• They can communicate with each other. You can create and initialize a JavaBeans component, create a variable that refers to that bean in one tag, and then use the bean in another tag.
• They can be nested within one another, allowing for complex interactions within a JSP page.
The next two sections describe the tasks involved in using and defining tags. The tutorial concludes with a discussion of two tag library examples. The examples include complete binary and source code in two Web application archives.
Using Tags
This section describes how a page author specifies that a JSP page is using a tag library and introduces the different types of tags.
Declaring Tag Libraries
You declare that a JSP page will use tags defined in a tag library by including a taglib directive in the page before any custom tag is used:
<%@ taglib uri="/tlt" prefix="tlt" %>
The uri attribute refers to a URI that uniquely identifies the tag library. This URI can be relative or absolute. If it is relative it must be mapped to an absolute location in the taglib element of a Web application deployment descriptor, the configuration file associated with Web applications developed according to the Java Servlet and JavaServer Pages specifications. The prefix attribute defines the prefix that distinguishes tags provided by a given tag library from those provided by other tag libraries.
Types of Tags
JSP custom actions are expressed using XML syntax. They have a start tag and end tag, and possibly a body:

body

A tag with no body can be expressed as follows:

Simple Tags
The following simple tag invokes an action that creates a greeting:

Tags With Attributes
The start tag of a custom action can contain attributes in the form attr="value". Attributes serve to customize the behavior of a tag just as parameters are used to affect the outcome of executing a method on an object.
Tag attributes can be set from one or more parameters in the request object or from a String constant. The only types of attributes that can be set from request parameter values and String constants are those listed in Table 1; the conversion applied is that shown in the table. When assigning values to indexed attributes the value must be an array; the rules just described apply to the elements.
Property Type Conversion on String Value
boolean or Boolean As indicated in java.lang.Boolean.valueOf(String)
byte or Byte As indicated in java.lang.Byte.valueOf(String)
char or Character As indicated in java.lang.Character.valueOf(String)
double or Double As indicated in java.lang.Double.valueOf(String)
int or Integer As indicated in java.lang.Integer.valueOf(String)
float or Float As indicated in java.lang.Float.valueOf(String)
long or Long As indicated in java.lang.Long.valueOf(String)
Table 1. Valid Tag Attribute Assignments
An attribute value of the form <%= scriptlet_expression %> is computed at request time. The value of the expression depends on the type of the attribute's value, which is specified in the object that implements the tag (called a tag handler). Request-time expressions can be assigned to attributes of any type; no automatic conversions will be performed.
The following tag has an attribute named date, which accepts a String value obtained by evaluating the variable today:
">
Tags With a Body
A tag can contain custom and core tags, scripting elements, HTML text, and tag-dependent body content between the start and end tag. In the following example, the date information is provided in the body of the tag, instead of as an attribute:

<%= today %>

Choosing Between Passing Information as Attributes or Body
As shown in the last two sections, it is possible to pass a given piece of data as an attribute of the tag or to the tag's body. Generally speaking, any data that is a simple string or can be generated by evaluating a simple expression is best passed as an attribute.
Tags That Define Scripting Variables
A tag can define a variable that can be used in scripts within a page. The following example illustrates how to define and use a scripting variable that contains an object returned from a JNDI lookup. Examples of such objects include enterprise beans, transactions, databases, environment entries, and so on:

<% tx.begin(); %>
Cooperating Tags
Tags cooperate with each other by means of shared objects.
In the following example, tag1 creates a named object called obj1, which is then reused by tag2. The convention encouraged by the JSP specification is that a tag with attribute named id creates and names an object and the object is then referenced by other tags with an attribute named name.


In the next example, an object created by the enclosing tag of a group of nested tags is available to all inner tags. Since the object is not named, the potential for naming conflicts is reduced. The following example illustrates how a set of cooperating nested tags would appear in a JSP page.



Defining Tags
To define a tag, you need to:
• Develop a tag handler and helper classes for the tag
• Declare the tag in a tag library descriptor
This section describes the properties of tag handlers and tag library descriptors and explains how to develop tag handlers and library descriptor elements for each type of tag introduced in the previous section.
Tag Handlers
A tag handler is an object invoked by a JSP container to evaluate a custom tag during the execution of the JSP page that references the tag. Tag handler methods are called by the JSP page implementation class at various points during the evaluation of the tag.
When the start tag of a custom tag is encountered, the JSP page implementation class calls methods to initialize the appropriate handler and then invokes the handler's doStartTag method. When the custom end tag is encountered, the handler's doEndTag method is invoked. Additional methods are invoked in between when a tag handler needs to interact with the body of the tag.
In order to provide a tag handler implementation, you must implement the methods that are invoked at various stages of processing the tag. The methods are summarized in Table 2.
Tag Handler Type Methods
Simple doStartTag, doEndTag, release
Attributes doStartTag, doEndTag, set/getAttribute1...N
Body, No Interaction doStartTag, doEndTag, release
Body, Interaction doStartTag, doEndTag, release, doInitBody, doAfterBody
Table 2 Tag Handler Methods
A tag handler has access to an API that allows it to communicate with the JSP page. The entry point to the API is the page context object through which a tag handler can access to all the other implicit objects (request, session, and application) accessible from a JSP page. Implicit objects can have attributes associated with them. Such attributes are accessed using the appropriate [set/get]Attribute method.
If the tag is nested, a tag handler also has access to the handler (called the parent) associated with the enclosing tag.
Tag handlers must implement either the Tag or BodyTag interfaces. Interfaces can be used to take an existing Java object and make it a tag handler. For newly created handlers, you can use the TagSupport and BodyTagSupport classes as base classes. You can download documentation that describes these interfaces and classes from the JSP specification download page.
Tag Library Descriptors
A tag library descriptor (TLD) is an XML document that describes a tag library. A TLD contains information about a library as a whole and about each tag contained in the library. TLDs are used by a JSP container to validate the tags and by JSP development tools.
The following TLD elements are used to define a tag library:

- The tag library's version
- The JSP specification version the tag library depends on
- A simple default name that could be used by a JSP page authoring tool to create names with a mnemonic value; for example, shortname may be used as the preferred prefix value in taglib directives and/or to create prefixes for IDs.
- A URI that uniquely identifies the tag library
- Descriptive information about the tag library

...

...

The TLD element required for all tags is the one used to specify a tag handler's class:

classname
...

The following sections will describe the methods and tag library descriptor elements that you need to develop for each type of tag introduced in "Using Tags".
Simple Tags
Tag Handlers
The handler for a simple tag must implement the doStartTag and doEndTag methods of the Tag interface. The doStartTag method is invoked when the start tag is encountered. This method returns SKIP_BODY because a simple tag has no body. The doEndTag method is invoked when the end tag is encountered. The doEndTag method needs to return EVAL_PAGE if the rest of the page needs to be evaluated; otherwise it should return SKIP_PAGE.
The following simple tag:

would be implemented by the following tag handler:
public SimpleTag extends Tag Support {
public int doStartTag() throws JspException {
try {
pageContext.getOut().print("Hello.");
} catch (Exception ex) {
throw new JspTagException("SimpleTag: " +
e.getMessage());
}
return SKIP_BODY;
}
public int doEndTag() {
return EVAL_PAGE;
}
}
TLD bodycontent Element
Tags without bodies must declare that their body content is empty:

...
empty

Tags With Attributes
Defining Attributes in a Tag Handler
For each tag attribute, you must define a property and JavaBeans style get and set methods in the tag handler. For example, the tag handler for the tag

where value1 is of type AttributeClass, must contain the following declaration and methods:
private AttributeClass attr1;
setAttr1(AttributeClass ac) { ... }
AttributeClass getAttr1() { ... }
Note that if your attribute is named id, and your tag handler inherits from the TagSupport class, you do not need to define the property and set and get methods because these are already defined by TagSupport.
A tag attribute whose value is a String can name an attribute of one of the implicit objects available to tag handlers. An implicit object attribute would be accessed by passing the tag attribute value to the [set/get]Attribute method of the implicit object. This is a good way to pass scripting variable names to a tag handler where they are associated with objects stored in the page.
TLD attribute Element
For each tag attribute you must specify whether the attribute is required, and whether the value can be determined by an expression:

...

attr1
true|false|yes|no
true|false|yes|no


If a tag attribute is not required, a tag handler should provide a default value.
Attribute Validation
The documentation for a tag library should describe valid values for tag attributes. When a JSP page is translated, a JSP container will enforce any constraints contained in the TLD element for each attribute.
The attributes passed to a tag can also be validated at translation time with the isValid method of a class derived from TagExtraInfo. This class is also used to provide information about scripting variables defined by the tag.
The isValid method is passed the attribute information in a TagData object, which contains attribute-value tuples for each of the tag's attributes. Since the validation occurs at translation time, the value of an attribute that is computed at request time will be set to TagData.REQUEST_TIME_VALUE.
The tag has the following TLD attribute element:

attr1
true
true

...
JSP|tagdependent

Body content containing custom and core tags, scripting elements, and HTML text is categorized as JSP; all other types of body content are tagdependent. Note that the value of this element does not affect the interpretation of the body. The bodycontent element is only intended to be used by an authoring tool to present the content of the body.
Tags That Define Scripting Variables
Tag Handlers
A tag handler is responsible for creating and setting the object referred to by the scripting variable into a context accessible from the page. It does this by using the pageContext.setAttribute(name, value, scope) or pageContext.setAttribute(name, value) methods. Typically an attribute passed to the custom tag specifies the name of the scripting variable object; this name can be retrieved by invoking the attribute's get method described in "Defining Attributes in a Tag Handler".
If the value of the scripting variable is dependent on an object present in the tag handler's context it can retrieve the object using the pageContext.getAttribute(name, scope) method.
The usual procedure is that the tag handler retrieves a scripting variable value object, performs some processing on the object, and then sets the scripting variable's value using the pageContext.setAttribute(name, object) method.
The scope that an object can have is summarized in Table 3. The scope constrains the accessibility and lifetime of the object.
Name Accessible From Lifetime
page Current page Until the response has been sent back to the user or the request is passed to a new page
request Current page and any included or forwarded pages Until the response has been sent back to the user
session Current request and any subsequent request from the same browser (subject to session lifetime). The life of the user's session
application Current and any future request from the same Web application The life of the application

Table 3 Scope of Objects
In addition to setting the value of the variable within the tag handler, you must define a class derived from TagExtraInfo that provides information to the JSP container about the nature of the variable. A TagExtraInfo must implement the method getVariableInfo to return an array of VariableInfo objects containing the following information:
• Variable name
• Variable class
• Whether the variable refers to a new or existing object value.
• The availability of the variable
Table 4 describes the availability of the scripting variable and the methods where the value of the variable must be set or reset.

Value Availability Methods
NESTED Between the start tag and the end tag. In doInitBody and doAfterBody for a tag handler implementing BodyTag; otherwise in doStartTag.
AT_BEGIN From the start tag until the end of the page. In doInitBody, doAfterBody, and doEndTag for a tag handler implementing BodyTag; otherwise in doStartTag and doEndTag.
AT_END After the end tag until the end of the page. In doEndTag.

Table 4 Scripting Variable Availability
The JSP container passes a parameter called data to the getVariableInfo method that contains an attribute-value tuples for each of the tag's attributes. These attributes can be used to provide the VariableInfo object with a scripting variable's name and class.
Recall the scripting variable example described in the first section:

<% tx.begin(); %>
The object retrieved from the JNDI lookup is stored as a page context attribute with the name of the scripting variable.
public LookupTag extends TagSupport {
private String type;
private String name;
public int doStartTag() {
return SKIP_BODY;
}
public int doEndTag() throws JspException {
try {
InitialContext context = new InitialContext();
Object obj = (Object)context.lookup(name);
pageContext.setAttribute(getId(), obj);
} catch(javax.naming.NamingException e) {
throw new JspException("Unable to look up " + name
+ " due to " + e.getMessage());
}
return EVAL_PAGE;
}
}
The scripting variable tx is defined in the following tag extra info class. Since the name (tx) and class (UserTransaction) of the scripting variable were passed in as tag attributes, they are retrieved with the data.getAttributeString method and used to fill in the VariableInfo constructor. To allow the scripting variable tx to be used in the rest of the page, the scope of tx is set to be AT_END.
public class LookupTagTEI extends TagExtraInfo {
public VariableInfo[] getVariableInfo(TagData data) {
VariableInfo info1
= new VariableInfo(
data.getAttributeString("id"),
data.getAttributeString("type"),
true,
VariableInfo.AT_END);
VariableInfo[] info = { info1 } ;
return info;
}
}
TLD teiclass Element
The TagExtraInfo class defined for each scripting variable must be declared in the tag library descriptor as follows:

...
LookupTagTEI

Cooperating Tags
Tags cooperate by sharing objects. JSP technology supports two styles of object sharing.
The first style requires that a shared object be named and stored in the page context (one of the implicit objects accessible to both JSP pages and tag handlers). To access objects created and named by another tag, a tag handler uses the pageContext.getAttribute(name, scope) method.
In the second style of object sharing, an object created by the enclosing tag handler of a group of nested tags is available to all inner tag handlers. This form of object sharing has the advantage that it uses a private namespace for the objects, thus reducing the potential for naming conflicts.
To access an object created by an enclosing tag, a tag handler must first obtain its enclosing tag with the static method TagSupport.findAncestorWithClass(from, class) or the TagSupport.getParent() method. The former method should be used when a specific nesting of tag handlers cannot be guaranteed. Once the ancestor has been retrieved, a tag handler can access any statically or dynamically created objects. Statically created objects are members of the parent. Private objects can also be created dynamically created. Such objects can be stored in a tag handler with the setValue method and retrieved with the getValue method.
The following example illustrates a tag handler that supports both the named and private object approaches to sharing objects. In the example, the handler for a query tag checks whether an attribute named connection has been set in the doStartTag method. If the connection attribute has been set, the handler retrieves the connection object from the page context. Otherwise, the tag handler first retrieves the tag handler for the enclosing tag, and then retrieves the connection object from that handler.
public class QueryTag extends BodyTagSupport {
private String connectionId;
public int doStartTag() throws JspException {
String cid = getConnection();
if (cid != null) {
// there is a connection id, use it
connection =(Connection)pageContext.
getAttribute(cid);
} else {
ConnectionTag ancestorTag =
(ConnectionTag)findAncestorWithClass(this,
ConnectionTag.class);
if (ancestorTag == null) {
throw new JspTagException("A query without
a connection attribute must be nested
within a connection tag.");
}
connection = ancestorTag.getConnection();
}
}
}
The query tag implemented by this tag handler could be used in either of the following ways:
...

SELECT account, balance FROM acct_table
where customer_number = <%= request.getCustno()%>




SELECT account, balance FROM acct_table
where customer_number = <%= request.getCustno()%>


The tag library descriptor for the tag handler must indicate that the connection attribute is optional with the following declaration:


connection
false

Examples
The examples described in this section demonstrate solutions to two recurring problems in developing JSP applications: minimizing the amount of Java programming in JSP pages and ensuring a common look and feel across applications. In doing so, they illustrate many of the styles of tags discussed in the first section.
The complete binary and source code for the examples is in two Web application archives iteration.war and template.war contained in the archive examples.zip. You can unpack the Web application archives with the command jar xvf webapp.war.
When an archive is unpacked, its contents are deposited into the directories listed in the following table. This directory layout is required by the Java Servlet specification and is one that you usually will use while developing an application.
Directory Contents
webapp JSP and HTML files
webapp/WEB-INF web.xml (Web application deployment descriptor) and taglib.tld (tag library descriptor)
webapp/WEB-INF/classes classes accessed by JSP files and servlet implementations
webapp/WEB-INF/lib JAR files containing the binary and source of tag library handler and tag extra info classes
Table 5 Web Application Directory Structure
You can run the examples on Tomcat, the freely available implementation of the Java Servlet and JavaServer Pages technologies, by performing the following steps:
1. Install Tomcat.
2. Download the Web application archives into the directory TOMCAT_HOME/webapps. When an archived Web application is accessed, Tomcat 3.2 automatically unpacks it into the directory TOMCAT_HOME/docBase (where docBase is the application directory specified in server.xml) and adds the context for each archive to the server startup file. If you are using an earlier version of Tomcat you will need to add the following lines to the file TOMCAT_HOME/conf/server.xml:


3. Start Tomcat.
4. Invoke the examples by following the links:
http://localhost:8080/iteration

http://localhost:8080/template/example/home

An Iteration Tag
Constructing page content dependent on dynamically generated data often requires the use of flow control scripting statements. By moving the flow control logic to tag handlers, flow control tags reduce the amount of scripting needed in JSP pages.
The iteration tag retrieves objects from a collection stored in a JavaBeans component and assigns them to a scripting variable. The body of the tag retrieves information from the scripting variable. While elements remain in the collection, the iteration tag causes the body to be reevaluated.
JSP Page
The iteration example application contains two JSP pages that uses the iterator tag; one of the pages, index.jsp, is shown below. The page initializes the iteration tag with a collection maintained by a JavaBeans component that represents an organization. The iteration tag populates a table with the names of departments in the organization. The other jsp page, list.jsp, uses the iterator tag to display the members of a selected department.
<%@ taglib uri="/tlt" prefix="tlt" %>


Organization




">







Departments
">
<%= departmentName %>



The following figure shows the result of executing list.jsp:

Tag Handler
The iteration tag uses an iterator initialized from the collection provided via the group tag attribute. If the iterator contains more elements, doStartTag sets the value of the scripting variable to the next element and then indicates that the body should be evaluated.
After the body has been evaluated, the doAfterBody method retrieves the body content and writes it to the out stream. The body content is cleared in preparation for another body evaluation. If the iterator contains more elements, doAfterBody again sets the value of the scripting variable to the next element and indicates that the body should be evaluated again, which causes the reexecution of doAfterBody. When there are no remaining elements, doAfterBody terminates the process by returning SKIP_BODY.
private Iterator iterator;
public void setGroup(Collection members) {
if(members.size() > 0)
iterator = members.iterator();
}

public int doStartTag() {
if(iterator == null) {
return SKIP_BODY;
}
if(iterator.hasNext()) {
pageContext.setAttribute(name, iterator.next());
return EVAL_BODY_TAG;
} else {
return SKIP_BODY;
}
}

public int doAfterBody() throws JspTagException {
BodyContent body = getBodyContent();
try {
body.writeOut(getPreviousOut());
} catch (IOException e) {
throw new JspTagException("IterationTag: " +
e.getMessage());
}

// clear up so the next time the body content is empty
body.clearBody();
if (iterator.hasNext()) {
pageContext.setAttribute(name, iterator.next());
return EVAL_BODY_TAG;
} else {
return SKIP_BODY;
}
}
Tag Extra Info Class
The scripting variable is defined in the following tag extra info class. Since the name (member) and class (Member) of the scripting variable were passed in as tag attributes, they are retrieved with the data.getAttributeString method and used to fill in the VariableInfo constructor.
public class IterationTEI extends TagExtraInfo {
...
public VariableInfo[] getVariableInfo(TagData data) {
VariableInfo info1
= new VariableInfo(
data.getAttributeString("name"),
data.getAttributeString("type"),
true,
VariableInfo.NESTED);
VariableInfo [] info = { info1 };
return info;
}
}
A Template Mechanism
A template mechanism provides a way to separate the common elements that are part of each screen from the elements that change with each screen of an application. Putting all the common elements together into one file makes it easier to maintain and enforce a consistent look and feel in all the screens. It also makes development of individual screens easier since the designer can focus on portions of a screen that are specific to that screen while the template takes care of the rest.
The template is a JSP page, with place holders for the parts that need to change with each screen. Each of these place holders is referred to as a parameter of the template. For example, a simple template could include a title parameter for the top of the generated screen and a body parameter to refer to a JSP page for the custom content of the screen.
Once you have a template, you can generate different presentation screens from it simply by passing it different parameters.
JSP Page
The entry page of the example, main.jsp, is shown below. The first part of the page uses a set of nested tags-definition, screen, and parameter-to define a table of screen definitions for an application and select a specific definition based on the request attribute selectedScreen.
<%@ taglib uri="/tlt" prefix="tlt" %>
">







...

...

The second part of the page uses the insert tag to insert parameters from the
selected definition into the application screen.


<br> <tlt:insert definition="tutorial" parameter="title"/> <br>






The template is instantiated by the Dispatcher servlet. This servlet first gets requested screen and stores as an attribute of the request. This is necessary because when the request is forwarded to main.jsp, the request URL info no longer reflects the original request (/home/example/*.jsp), but instead reflects the path (/template/main.jsp) of the forwarded page. Finally the servlet dispatches the request to main.jsp:
public class Dispatcher extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException {
request.setAttribute("selectedScreen",
request.getPathInfo());
try {
getServletConfig().
getServletContext().getRequestDispatcher(
"/main.jsp").forward(request, response);
} catch(Exception e) {
e.printStackTrace();
}
}
}
The following figures show the home and first pages of the application:


Tag Handlers
The template tag library contains four tag handlers: DefinitionTag, ScreenTag, ParameterTag, and InsertTag. These tag handlers demonstrate the use of cooperating tags. DefinitionTag, ScreenTag, and ParameterTag comprise a set of nested tags handlers in which private objects are shared between parent and child tags. DefinitionTag creates a named object called definition that is used by InsertTag.
In doStartTag, DefinitionTag creates a private object that contains a hashtable of screen definitions. A screen definition consists of a screen identifier and a set of parameters associated with the screen. The table of screen definitions is filled in by ScreenTag and ParameterTag from text provided as attributes to these tags. Table 6 shows the contents of the screen definitions hashtable for the JSP page discussed in the previous section.
Screen ID Title Banner Body
/home Home Page /banner.jsp /home.jsp
/first First Page /banner.jsp /first.jsp
/second Second Page /banner.jsp /second.jsp
Table 6 Screen Definitions
In doEndTag, DefinitionTag creates a public object of class Definition, selects a screen definition based on the URL passed in the request, and uses the definition to initialize the Definition. If the URL passed in the request is /home, the Definition contains the items from the first row of Table 6:
Title Banner Body
Home Page /banner.jsp /home.jsp

public int doStartTag() {
Hashtable screens = null;
try {
// look for the screens object or create if it does not exist
screens = (Hashtable) getValue("screens");
if (screens == null)
setValue("screens", new Hashtable());
else
...
} catch (Exception e) {
...
}
return EVAL_BODY_INCLUDE;
}

public int doEndTag()throws JspTagException {
try {
Definition definition = new Definition();
Hashtable screens = null;
ArrayList params = null;
TagSupport screen = null;
if (getValue("screens") != null)
screens = (Hashtable) getValue("screens");
if (screens != null)
params = (ArrayList) screens.get(screenId);
else
...
if (params == null)
...
Iterator ir = null;
if (params != null)
ir = params.iterator();
while ((ir != null) && ir.hasNext())
definition.setParam((Parameter) ir.next());
// put the definition in the page context
pageContext.setAttribute(
definitionName, definition);
} catch (Exception ex) {
ex.printStackTrace();
}
return EVAL_PAGE;
}
InsertTag uses the Definition object to insert parameters of the screen definition into the response. First it retrieves the definition object from the page context. The isDirect parameter attribute determines whether the parameter value is directly inserted into the response or treated as the name of a JSP file which is dynamically included into the response.
The definition for the URL /home is shown below. The definition specifies that the value of the Title parameter should be inserted directly into the output stream, but the values of Banner and Body should be dynamically included.
Parameter Name title banner body
Parameter Value Home Page /banner.jsp /home.jsp
IsDirect true false false

public int doStartTag() {
// get the definition from the page context
try {
definition = (Definition) pageContext.
getAttribute(definitionName);
} catch (NullPointerException e) {
...
}
// get the parameter
if (parameterName != null && definition != null)
parameter = (Parameter)definition.
getParam(parameterName);
if (parameter != null)
directInclude = parameter.isDirect();
return SKIP_BODY;
}

public int doEndTag()throws JspTagException {
// flush data
try {
pageContext.getOut().flush();
} catch (Exception e) {
...
}
try {
// if parameter is direct, print to out
if (directInclude && parameter != null)
pageContext.getOut().print(parameter.getValue());
// if parameter is indirect,
// include results of dispatching to page
else {
if ((parameter != null) &&
(parameter.getValue() != null))
pageContext.getRequest().
getRequestDispatcher(
parameter.getValue()).include(
pageContext.getRequest(),
pageContext.getResponse());
}
} catch (Exception ex) {
ex.printStackTrace();
}
return EVAL_PAGE;
}
Web Application Deployment Descriptor
The Dispatcher servlet is used to forward requests to the application template. The servlet-mapping element in the Web application deployment descriptor maps all URL patterns of the form /example/* to the dispatcher servlet. The servlet element then maps the dispatcher servlet to an instance of the Dispatcher class. The taglib element maps the logical name /tlt to the absolute location of the tag library descriptor. This allows a page author to use the logical name in the taglib page directive.


dispatcher
/example/*

dispatcher
Dispatcher


/tlt
/WEB-INF/taglib.tld

How Is a Tag Handler Invoked?
The Tag interface defines the basic protocol between a tag handler and JSP page implementation class. It defines the life cycle and the methods to be invoked when the start and end tag of an action are encountered.
The JSP page implementation class invokes the setPageContext, setParent, and attribute setting methods before calling doStartTag. The JSP page implementation class also guarantees that release will be invoked on the tag handler before the end of the page.
Here is a typical tag handler method invocation sequence:
ATag t = new ATag();
t.setPageContext(...);
t.setParent(...);
t.setAttribute1(value1);
t.setAttribute2(value2);
t.doStartTag();
t.doEndTag();
t.release();
The BodyTag interface extends Tag by defining additional methods that let a tag handler access its body. The interface provides three new methods:
setBodyContent - creates body content and adds to tag handler
doInitBody - called before evaluation of tag body
doAfterBody - called after evaluation of tag body
A typical invocation sequence is:
t.doStartTag();
out = pageContext.pushBody();
t.setBodyContent(out);
// perform any initialization needed after body content is set
t.doInitBody();
t.doAfterBody();
// while doAfterBody returns EVAL_BODY_TAG we
// iterate body evaluation
...
t.doAfterBody();
t.doEndTag();
t.pageContext.popBody();
t.release();

Tutorial 2 Network Programming in Java

Tutorial 2 Network Programming in Java


1 Java network programming introduction

Java provides java.net package to support network programming.

1.1 Client and Server

• A client obtains a service via sending a request to a server

• A client initiates a connection, retrieves data, responds user input. For example, web browser, chat program (ICQ)

• A server provides a set of services, such as web server, time server, file server, chat server.

• A server responds to connection, receives requests for data from client, and delivers it to client.

• The protocol between client and server is the communication rule, for example FTP, SMTP, and HTTP.



1.2 Socket

• We use socket to establish the connection between client and server.
• Socket identifies a connection using host address and port number.

• A socket is a bi-directional communication channel

• Java differentiates client sockets from server sockets.

e.g. for client
Socket client=new Socket(“hostname”,portNumber);

for server
ServerSocket server=new SeverSocket(portNumber);



• Well known ports for server
80 web server
21 Ftp server
13 Time server
23 Telnet
25 Email(SMTP)

1.3 The connection between server and client using socket

Socket Operations at Client Side
• create a client socket:
Socket (host, port)
s = new Socket (“java.sun.com”, 13)

• get input / output data streams out of the socket:
in = new DataInputStream(s.getInputStream ());
out = new DataOutputStream( s.getOutputStream());
out = new PrintStream( s.getOutputStream());

• read from input / write to output data streams:
String str = in.readLine();
out.println ( “Echo:” + str + “\r”);

• close the socket:
s.close();


Socket Operations at Server Side

A server is always waiting for being connected. It need not initiate a connection to a host. So a server socket need only specify its own port no.
• create a server socket:
ServerSocket (port)
ServerSocket s = new ServerSocket(8189);
• accept an incoming connection:
Socket snew = s.accept ();
• get input / output data streams out of the socket for the incoming client:
in = new DataInputStream(snew.getInputStream());
out = new PrintStream(snew.getOutputStream());
• close the socket for the incoming client:
snew.close();


1.4 Example : A web Client


import java.net.*;
import java.io.*;

class HttpClient {
public static void main(String[] args ) {
try {
Socket s = new Socket("www.cs.cityu.edu.hk", 80);
DataInputStream in = new DataInputStream(s.getInputStream());
PrintStream out=new PrintStream(s.getOutputStream());
out.println("GET / HTTP/1.0");
out.println();
String line;
while ((line=in.readLine())!=null)
System.out.println("> "+line);
s.close();
} catch (Exception e) { System.out.println(e);}
}
}



2 HTTP introduction

HTTP( Hypertext Transfer Protocol) is an application layer protocol , just like FTP, SMTP, etc. The WWW is based on HTTP, for the communication rule between the browser and web server is HTTP.

You can check following URL for detailed document about HTTP . http://www.w3.org/Protocols/

2.1 Overview

HTTP request

Format: Method URI HTTP Version


For example: GET / HTTP/1.0

There are three most important methods in HTTP 1.0 , include GET, PUT and HEAD


• To request a web page, a browser sends a web server an HTTP GET message

• To send data to a web server, a browser can use an HTTP POST message

• To get information about document size , modification date, but not document itself , you can use HTTP HEAD request.

And there are some other HTTP methods added in HTTP 1.1 , such as PUT, DELETE, OPTIONS, and TRACE.

Also client can send additional information about itself to web server, such as browser type, operation system.

HTTP response

After receiving client’s request, web server will respond. It includes web server HTTP version, HTTP server status code for client’s request, and some information about document, such as Content-Length, Content-Type, Last-Modified date.

2.2 Example

import java.net.*;
import java.io.*;

class HttpClient1 {
public static void main(String[] args ) {
try {
Socket s = new Socket("www.cs.cityu.edu.hk", 80);
DataInputStream in = new DataInputStream(s.getInputStream());
PrintStream out=new PrintStream(s.getOutputStream());
out.println("HEAD /index.html HTTP/1.0");
out.println();
String line;
while ((line=in.readLine())!=null)
System.out.println("> "+line);
s.close();
} catch (Exception e) { System.out.println(e);}
}
}
2.3 URL: Uniform Resource Locator

• The URL standard defines a common way to refer to any web page, anywhere on the web

• format: protocol://web_server_name/page_name
example: http://www.yahoo.com/index.html

• URLs are most commonly used in conjunction with the HTTP protocol to GET a URL, or POST data to a URL

• a URL can refer to many kinds of web page:
plain text, formatted text (usually in HTML…),
multimedia, database, ...

2.4 HTML: HypeText Markup Language


•Specific mark-up language used in the Web

•Many kinds of markups

–low-level appearance (font changes, lists)
–logical structure (title, headings)
–links to other documents
–embedded graphics
–meta-information (language)
–and much more...


• A simple HTML file



<br>A HTML to test applet <br>









3 Java URL class

Java provides URL class to make it much easier to deal with HTTP connection. We don’t need to care about low layer socket connection.

You can find detailed information about them on following URL,
http://java.sun.com/j2se/1.4.2/docs/api/java/net/URL.html

3.1 URL


Constructor
URL(String spec)
Creates a URL object from the String representation.
URL(String protocol, String host, int port, String file)
Creates a URL object from the specified protocol, host, port number, and file.
URL(String protocol, String host, int port, String file, URLStreamHandler handler)
Creates a URL object from the specified protocol, host, port number, file, and handler.
URL(String protocol, String host, String file)
Creates a URL from the specified protocol name, host name, and file name.
URL(URL context, String spec)
Creates a URL by parsing the given spec within a specified context.
URL(URL context, String spec, URLStreamHandler handler)
Creates a URL by parsing the given spec with the specified handler within a specified context.

Excetption
MalformedURLException
Thrown if you try to create a bogus URL
Usually means bad user input, so fail gracefully and informatively

accessor methods

getProtocol(), getHost(), getPort(), getFile(), getRef()


openConnection()

public URLConnection openConnection() throws IOException
Returns a URLConnection object that represents a connection to the remote object referred to by the URL.
If there is not already an open connection, the connection is opened by calling the openConnection method of the protocol handler for this URL.

OpenStream()
public final InputStream openStream() throws IOException
Opens a connection to this URL and returns an InputStream for reading from that connection. This method is a shorthand for:
openConnection().getInputStream()

getContent
public final Object getContent() throws IOException
Returns the contents of this URL. This method is a shorthand for:
openConnection().getContent()


Example 1

import java.net.*;

public class UrlTest {
public static void main(String[] args) {
if (args.length == 1) {
try {
URL url = new URL(args[0]);
System.out.println
("URL: " + url.toExternalForm() + "\n" +
" File: " + url.getFile() + "\n" +
" Host: " + url.getHost() + "\n" +
" Port: " + url.getPort() + "\n" +
" Protocol: " + url.getProtocol() + "\n" +
" Reference: " + url.getRef());
} catch(MalformedURLException mue) {
System.out.println("Bad URL.");
}
} else
System.out.println("Usage: UrlTest ");
}
}


Example 2 was given in Tutorial 1.
Using openStream()

Example 3 Using getContent()

import java.net.*;
import java.io.*;

public class UrlRetriever1 {
public static void main(String[] args) {
checkUsage(args);
try {
URL url=new URL(args[0]);

DataInputStream in= new DataInputStream((InputStream)url.getContent());
String line;
while ((line=in.readLine())!=null)
System.out.println(line);
in.close();
} catch(MalformedURLException mue)
{ System.out.println(args[0]+"is an invalid URL:"+mue);
} catch(IOException ioe) {
System.out.println("IOException: "+ioe);
}
}

private static void checkUsage(String[] args) {
if (args.length!=1) {
System.out.println("Usage: UrlRetriever2 ");
System.exit(-1);
}
}
}

4 Exercises

• Implement a HTTP server (Simulated) using ServerSocket.


• Using URL Class, write a http client to retrieve http://www.cs.cityu.edu.hk/index.html, and return the last modified date, Content-Length, Content-Type of this web page.







Writing your own client/server applications can be done seamlessly using Java

Sockets programming in Java: A tutorial
Writing your own client/server applications can be done seamlessly using Java


his tutorial presents an introduction to sockets programming over TCP/IP networks and shows how to write client/server applications in Java.
A bit of history
The Unix input/output (I/O) system follows a paradigm usually referred to as Open-Read-Write-Close. Before a user process can perform I/O operations, it calls Open to specify and obtain permissions for the file or device to be used. Once an object has been opened, the user process makes one or more calls to Read or Write data. Read reads data from the object and transfers it to the user process, while Write transfers data from the user process to the object. After all transfer operations are complete, the user process calls Close to inform the operating system that it has finished using that object.
When facilities for InterProcess Communication (IPC) and networking were added to Unix, the idea was to make the interface to IPC similar to that of file I/O. In Unix, a process has a set of I/O descriptors that one reads from and writes to. These descriptors may refer to files, devices, or communication channels (sockets). The lifetime of a descriptor is made up of three phases: creation (open socket), reading and writing (receive and send to socket), and destruction (close socket).
The IPC interface in BSD-like versions of Unix is implemented as a layer over the network TCP and UDP protocols. Message destinations are specified as socket addresses; each socket address is a communication identifier that consists of a port number and an Internet address.
The IPC operations are based on socket pairs, one belonging to a communication process. IPC is done by exchanging some data through transmitting that data in a message between a socket in one process and another socket in another process. When messages are sent, the messages are queued at the sending socket until the underlying network protocol has transmitted them. When they arrive, the messages are queued at the receiving socket until the receiving process makes the necessary calls to receive them.
TCP/IP and UDP/IP communications
There are two communication protocols that one can use for socket programming: datagram communication and stream communication.
Datagram communication:
The datagram communication protocol, known as UDP (user datagram protocol), is a connectionless protocol, meaning that each time you send datagrams, you also need to send the local socket descriptor and the receiving socket's address. As you can tell, additional data must be sent each time a communication is made.
Stream communication:
The stream communication protocol is known as TCP (transfer control protocol). Unlike UDP, TCP is a connection-oriented protocol. In order to do communication over the TCP protocol, a connection must first be established between the pair of sockets. While one of the sockets listens for a connection request (server), the other asks for a connection (client). Once two sockets have been connected, they can be used to transmit data in both (or either one of the) directions.
Now, you might ask what protocol you should use -- UDP or TCP? This depends on the client/server application you are writing. The following discussion shows the differences between the UDP and TCP protocols; this might help you decide which protocol you should use.
In UDP, as you have read above, every time you send a datagram, you have to send the local descriptor and the socket address of the receiving socket along with it. Since TCP is a connection-oriented protocol, on the other hand, a connection must be established before communications between the pair of sockets start. So there is a connection setup time in TCP.
In UDP, there is a size limit of 64 kilobytes on datagrams you can send to a specified location, while in TCP there is no limit. Once a connection is established, the pair of sockets behaves like streams: All available data are read immediately in the same order in which they are received.
UDP is an unreliable protocol -- there is no guarantee that the datagrams you have sent will be received in the same order by the receiving socket. On the other hand, TCP is a reliable protocol; it is guaranteed that the packets you send will be received in the order in which they were sent.
In short, TCP is useful for implementing network services -- such as remote login (rlogin, telnet) and file transfer (FTP) -- which require data of indefinite length to be transferred. UDP is less complex and incurs fewer overheads. It is often used in implementing client/server applications in distributed systems built over local area networks.
Programming sockets in Java
In this section we will answer the most frequently asked questions about programming sockets in Java. Then we will show some examples of how to write client and server applications.
Note: In this tutorial we will show how to program sockets in Java using the TCP/IP protocol only since it is more widely used than UDP/IP. Also: All the classes related to sockets are in the java.net package, so make sure to import that package when you program sockets.
How do I open a socket?
If you are programming a client, then you would open a socket like this:

Socket MyClient;
MyClient = new Socket("Machine name", PortNumber);
Where Machine name is the machine you are trying to open a connection to, and PortNumber is the port (a number) on which the server you are trying to connect to is running. When selecting a port number, you should note that port numbers between 0 and 1,023 are reserved for privileged users (that is, super user or root). These port numbers are reserved for standard services, such as email, FTP, and HTTP. When selecting a port number for your server, select one that is greater than 1,023!
In the example above, we didn't make use of exception handling, however, it is a good idea to handle exceptions. (From now on, all our code will handle exceptions!) The above can be written as:

Socket MyClient;
try {
MyClient = new Socket("Machine name", PortNumber);
}
catch (IOException e) {
System.out.println(e);
}
If you are programming a server, then this is how you open a socket:

ServerSocket MyService;
try {
MyServerice = new ServerSocket(PortNumber);
}
catch (IOException e) {
System.out.println(e);
}
When implementing a server you also need to create a socket object from the ServerSocket in order to listen for and accept connections from clients.

Socket clientSocket = null;
try {
serviceSocket = MyService.accept();
}
catch (IOException e) {
System.out.println(e);
}
How do I create an input stream?
On the client side, you can use the DataInputStream class to create an input stream to receive response from the server:

DataInputStream input;
try {
input = new DataInputStream(MyClient.getInputStream());
}
catch (IOException e) {
System.out.println(e);
}
The class DataInputStream allows you to read lines of text and Java primitive data types in a portable way. It has methods such as read, readChar, readInt, readDouble, and readLine,. Use whichever function you think suits your needs depending on the type of data that you receive from the server.
On the server side, you can use DataInputStream to receive input from the client:

DataInputStream input;
try {
input = new DataInputStream(serviceSocket.getInputStream());
}
catch (IOException e) {
System.out.println(e);
}
How do I create an output stream?
On the client side, you can create an output stream to send information to the server socket using the class PrintStream or DataOutputStream of java.io:

PrintStream output;
try {
output = new PrintStream(MyClient.getOutputStream());
}
catch (IOException e) {
System.out.println(e);
}
The class PrintStream has methods for displaying textual representation of Java primitive data types. Its Write and println methods are important here. Also, you may want to use the DataOutputStream:

DataOutputStream output;
try {
output = new DataOutputStream(MyClient.getOutputStream());
}
catch (IOException e) {
System.out.println(e);
}
The class DataOutputStream allows you to write Java primitive data types; many of its methods write a single Java primitive type to the output stream. The method writeBytes is a useful one.
On the server side, you can use the class PrintStream to send information to the client.

PrintStream output;
try {
output = new PrintStream(serviceSocket.getOutputStream());
}
catch (IOException e) {
System.out.println(e);
}
Note: You can use the class DataOutputStream as mentioned above.
How do I close sockets?
You should always close the output and input stream before you close the socket.
On the client side:

try {
output.close();
input.close();
MyClient.close();
}
catch (IOException e) {
System.out.println(e);
}
On the server side:

try {
output.close();
input.close();
serviceSocket.close();
MyService.close();
}
catch (IOException e) {
System.out.println(e);
}
Examples
In this section we will write two applications: a simple SMTP (simple mail transfer protocol) client, and a simple echo server.
1. SMTP client
Let's write an SMTP (simple mail transfer protocol) client -- one so simple that we have all the data encapsulated within the program. You may change the code around to suit your needs. An interesting modification would be to change it so that you accept the data from the command-line argument and also get the input (the body of the message) from standard input. Try to modify it so that it behaves the same as the mail program that comes with Unix.

import java.io.*;
import java.net.*;

public class smtpClient {
public static void main(String[] args) {

// declaration section:
// smtpClient: our client socket
// os: output stream
// is: input stream

Socket smtpSocket = null;
DataOutputStream os = null;
DataInputStream is = null;

// Initialization section:
// Try to open a socket on port 25
// Try to open input and output streams

try {
smtpSocket = new Socket("hostname", 25);
os = new DataOutputStream(smtpSocket.getOutputStream());
is = new DataInputStream(smtpSocket.getInputStream());
} catch (UnknownHostException e) {
System.err.println("Don't know about host: hostname");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: hostname");
}

// If everything has been initialized then we want to write some data
// to the socket we have opened a connection to on port 25

if (smtpSocket != null && os != null && is != null) {
try {

// The capital string before each colon has a special meaning to SMTP
// you may want to read the SMTP specification, RFC1822/3

os.writeBytes("HELO\n");
os.writeBytes("MAIL From: k3is@fundy.csd.unbsj.ca\n");
os.writeBytes("RCPT To: k3is@fundy.csd.unbsj.ca\n");
os.writeBytes("DATA\n");
os.writeBytes("From: k3is@fundy.csd.unbsj.ca\n");
os.writeBytes("Subject: testing\n");
os.writeBytes("Hi there\n"); // message body
os.writeBytes("\n.\n");
os.writeBytes("QUIT");

// keep on reading from/to the socket till we receive the "Ok" from SMTP,
// once we received that then we want to break.

String responseLine;
while ((responseLine = is.readLine()) != null) {
System.out.println("Server: " + responseLine);
if (responseLine.indexOf("Ok") != -1) {
break;
}
}

// clean up:
// close the output stream
// close the input stream
// close the socket

os.close();
is.close();
smtpSocket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
}
When programming a client, you must follow these four steps:
• Open a socket.
• Open an input and output stream to the socket.
• Read from and write to the socket according to the server's protocol.
• Clean up.
These steps are pretty much the same for all clients. The only step that varies is step three, since it depends on the server you are talking to.
2. Echo server
Now let's write a server. This server is very similar to the echo server running on port 7. Basically, the echo server receives text from the client and then sends that exact text back to the client. This is just about the simplest server you can write. Note that this server handles only one client. Try to modify it to handle multiple clients using threads.

import java.io.*;
import java.net.*;

public class echo3 {
public static void main(String args[]) {

// declaration section:
// declare a server socket and a client socket for the server
// declare an input and an output stream

ServerSocket echoServer = null;
String line;
DataInputStream is;
PrintStream os;
Socket clientSocket = null;

// Try to open a server socket on port 9999
// Note that we can't choose a port less than 1023 if we are not
// privileged users (root)

try {
echoServer = new ServerSocket(9999);
}
catch (IOException e) {
System.out.println(e);
}

// Create a socket object from the ServerSocket to listen and accept
// connections.
// Open input and output streams

try {
clientSocket = echoServer.accept();
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());

// As long as we receive data, echo that data back to the client.

while (true) {
line = is.readLine();
os.println(line);
}
}
catch (IOException e) {
System.out.println(e);
}
}
}
Conclusion
Programming client/server applications is challenging and fun, and
programming this kind of application in Java is easier than doing it in other languages, such as C. Socket programming in Java is seamless.
The java.net package provides a powerful and flexibile infrastructure for network programming, so you are encouraged to refer to that package if you would like to know the classes that are provided.
Sun.* packages have some good classes for networking, however you are not encouraged to use those classes at the moment because they may change in the next release. Also, some of the classes are not portable across all platforms.

About the author
Qusay H. Mahmoud is a graduate student in computer science at the University of New Brunswick, Saint John campus, Canada. He is currently working on his master's thesis as well as teaching a computer science course at the University. His thesis concentrates on the Web and Java, and the results of his thesis will be available online as soon as he is finished. He has been working with Java since it was released to the public.
Resources
• Sun's Custom Networking and Security documentation:
http://java.sun.com/books/Series/Tutorial/networking/index.html
• The Java packages API (including java.net):
http://www.javasoft.com:80/products/JDK/1.0.2/api/packages.html




Modul Pelatihan PHP and MySQL

Modul Pelatihan PHP and MySQL

Pendahuluan

Konsep Multi Tier Application

Multi tier application adalah aplikasi yang dibagi menjadi beberapa bagian yang menjalankan fungsi masing-masing. Secara umum, ada tiga bagian utama dari multi tier application:
• Client side presentation
• Server side business logic
• Backend storage

Client Side Presentation
Client side presentation mengatur bagaimana aplikasi berinteraksi dengan user. Yang dimaksud dengan interaksi antara lain adalah: bagaimana data ditampilkan, bagaimana fungsi dan fitur aplikasi ditampilkan.
Dalam aplikasi berbasis web, client side presentation dibuat dengan bahasa HTML, CSS, dan JavaScript. Beberapa tool yang digunakan untuk membuat client side presentation diantaranya Microsoft Frontpage, Macromedia Dreamweaver, dan sebagainya.Client side presentation berbasis web contohnya adalah tampilan aplikasi email yang kita buka dengan browser.

Server Side Business Logic
Server side business logic, sering disebut juga middle tier, adalah bagian yang bertanggung jawab atas cara kerja aplikasi. Di dalamnya kita mengatur bagaimana fungsi dan fitur aplikasi dapat bekerja dengan baik. Dalam aplikasi berbasis web, ada beberapa alternatif yang dapat digunakan, ditentukan oleh jenis platform yang digunakan. Alternatif ini akan dijelaskan lebih detail pada bagian selanjutnya.

Back End Storage
Bagian ini mengatur cara penyimpanan data. Penyimpanan data merupakan materi yang cukup kompleks dalam pembangunan aplikasi. Karena kecepatan, keutuhan, dan keamanan data merupakan faktor kritis dalam aplikasi.
Ada banyak solusi database yang tersedia di pasaran. Pada umumnya, database yang digunakan bertipe relasional (Relational Database Management System – RDBMS). Manajemen data dilakukan dengan bahasa SQL (Standard Query Language).


Perbedaan Web Based Programming dengan System Programming
Pembuatan aplikasi berbasis web berbeda dengan pembuatan aplikasi berbasis windows (visual programming), misalnya Visual Basic, Delphi, atau KDevelop. Dalam visual programming, kita meningkatkan kecepatan dan kinerja aplikasi dengan mengoptimasi penggunaan memori, manajemen proses, dan pengaturan Input-Output. Pada pemrograman berbasis web, faktor yang menentukan kinerja aplikasi adalah kecepatan akses database dan kecepatan akses jaringan dan internet.

Perbedaan kedua, adalah cara aplikasi berjalan. Pada aplikasi visual, aplikasi dibangun dengan menggunakan tool tertentu, kemudian dikompilasi. Hasilnya dapat langsung digunakan dalam komputer. Aplikasi berbasis web tidak dapat dijalankan langsung di komputer. Untuk menjalankannya, dibutuhkan engine tertentu, dalam hal ini web server.

Teknologi Alternatif
Teknologi server side yang akan kita pelajari pada modul ini adalah PHP. Walaupun demikian, perlu diketahui teknologi alternatif yang dapat menjadi bahan pertimbangan :

CGI Script
CGI Script dapat dibuat dengan berbagai bahasa pemrograman, misalnya Perl atau Phyton. Teknologi ini pernah sangat populer di masa awal berkembangnya web based application. Tetapi saat ini banyak ditinggalkan orang karena tidak efisien, tidak fleksibel, dan keamanannya rendah.

Proprietary API
Teknologi ini adalah bahasa pemrograman yang disediakan masing- masing webserver, misalnya ISAPI atau NSAPI. Teknologi ini memiliki kelemahan, yaitu hanya dapat berjalan di webserver tertentu, sehingga mengurangi portabilitas.

ASP
Merupakan solusi server side programming dari Microsoft. Teknologi ini banyak digunakan oleh para programmer yang berlatar belakang Visual Basic. Database pasangannya adalah MS SQL Server. Operating system pasangannya adalah Window 2000 Server yang menjalankan webserver Microsoft IIS.


JavaServlet/JSP
Teknologi server side Java. Mempunyai banyak keunggulan dan kemudahan pemrograman. Tetapi karena murni berorientasi objek, banyak programmer pemula kesulitan menggunakannya. Selain itu, Java juga adalah bahasa pemrograman yang relatif rumit bagi pemula. Keunggulannya, sangat portabel. Dapat dipindahkan dengan mudah dari Windows ke Unix dan sebaliknya.

ColdFusion
Bahasa pemrograman ini mirip dengan HTML, menggunakan tag untuk membentuk blok-blok programnya.


PHP
Banyak digunakan oleh programmer berlatar belakang C/C++ karena kemiripansyntaxnya. Open source,karenanya gratis dan bebas. Database pasangannya biasanya MySQL, dijalankan bersama webserver Apache di atas operating system Linux. Semuanya gratis dan bebas.

PHP Basics
1. Embedding PHP in HTML
a. Using PHP Tags
File welcome.php
?>?>?>
output
…..
b. PHP tag styles
c. PHP statement
Statement
Statement adalah satuan perintah dalam PHP. Statement harus diakhiri dengan tanda semicolon/titik-koma (;).

Contoh statement :
echo(“Selamat Belajar PHP di EEPIS”);

Contoh lainnya :
echo(“7 + 5 = ” . 7+5);

Expression
Expression adalah satu bagian kecil kode yang akan dihitung hasilnya oleh php. Contoh expression :
7 + 5

Penggunaan expression :
echo(“7 + 5 = ” . 7+5);

d. Whitespace
e. Comments
Comment adalah bagian dari kode yang tidak dieksekusi/dijalankan. Comment dibuat untuk memperjelas atau memberi keterangan pada kode program.

Ada dua cara menulis comment : comment satu baris dan comment banyak baris.
Comment satu baris dibuat dengan menggunakan tanda //. Semua statement yang ada di kanan // tidak dijalankan oleh interpreter. Contoh penggunaan:

echo(“4 + 5 = ” . 4+5); // menampilkan hasil 4 + 5

Comment banyak baris dibuat dengan menggunakan pasangan /* dan
*/. Semua tulisan yang dibuat di antara tanda tersebut tidak akan dieksekusi oleh interpreter. Contoh penggunaan :
/*
kode ini akan menampilkan hasil dari
4 + 5
*/
echo(“4 + 5 = ” . 4+5);






2. Adding dynamic Content
3. accesing form variables
4. Identifiers
5. User-declared variables
Variabel digunakan sebagai tempat penyimpanan data sementara. Data yang disimpan dalam variabel akan hilang setelah program selesai dieksekusi. Untuk penyimpanan data yang permanen, kita dapat menyimpan data di database atau di disk. Silahkan mengacu pada Akses Database untuk mendalami penggunaan database, dan Akses File dan Folder untuk penyimpanan data di filesystem.

Variabel di PHP diawali dengan tanda $.
Untuk dapat menggunakan variabel, ada dua langkah yang harus dilakukan,
Deklarasi dan variabel.

a. Deklarasi Variabel.
Deklarasi variabel bisa disebut juga memperkenalkan atau mendaftarkan variabel ke dalam program.
Dalam php, deklarasi variabel seringkali digabung dengan inisialisasi.
Variabel dalam PHP dinyatakan dengan awalan $.
Contoh :
$Nama
$Alamat
$nim

Ada beberapa aturan yang diikuti berkenaan dengan penggunaan nama variabel. Aturan pemberian nama variabel :
• Dimulai dengan tanda $
• Karakter pertama harus huruf atau garis bawah ( _ )
• Karakter berikutnya boleh huruf, angka, atau garis bawah.

b. Inisialisasi Variabel
Inisialisasi variabel adalah mengisi nilai untuk pertama kalinya ke dalam variabel. Contoh inisialisasi :
$nama = “UdinHarun”;
$Alamat = “Computer Network Lab”;
$nip = 123456;
$harga = 1000;

c. Tipe Data
Dalam bahasa pemrograman yang lain, ada bermacam-macam tipe data, misalnya integer(bilangan bulat), float (bilangan pecahan), char(karakter angka dan huruf), string(kumpulan huruf atau kata), dan berbagai tipe lainnya.

PHP mengenal dua tipe data sederhana; numerik dan literal. Ditambah dengan dua tipe data yang tidak sederhana, yaitu array dan object. Tipe Numerik dapat menyimpan bilangan bulat.PHP mampu menyimpan data bilangan bulat dengan jangkauan dari -2 milyar sampai+2 milyar. Contoh bilangan bulat: 3, 7, 20.

Selain itu, tipe numerik juga digunakan untuk menyimpan bilangan pecahan
Tipe literal digunakan untuk menyimpan data berupa kumpulan huruf, kata, dan angka.Tipe boolean, yang dikenal dalam bahasa program yang lainnya, tidak adadalam PHP.

Untuk menguji benar salah (true false), kita menggunakan tipe data yang tersedia. FALSE dapat digantikan oleh integer 0, double 0.0 atau string kosong, yaitu "". Selain nilai itu, semua dianggap TRUE.
Variabel dapat digunakan untuk menyimpan berbagai jenis data. Misalnya data numerik yang dapat dioperasikan secara matematika. Contoh :

$jumlahBarang = 3;
$harga = 1000;
$pembayaran = $jumlahBarang * $harga;

pada contoh di atas, variabel pembayaran akan menyimpan nilai 3000.
Sedangkan data non numerik (disebut juga data literal) tidak dapat dioperasikan secara matematika. Contoh :
$nama = $namaDepan + $namaBelakang;

variabel nama akan menyimpan gabungan dari dua variabel, yaitu
“Endy Muhardin”.

Secara umum, data literal ditandai dengan pasangan “ dan “. Data numerik tidak dikelilingi oleh “ dan “. Tetapi biasanya PHP akan secara otomatis mengubah tipe data sesuai kebutuhan. Contoh :

$jalan = “Gubeng Kertajaya”;
$noRumah = 29;
$blok = 4c;
$jumlahPenghuni = 3;

$alamat = $jalan + $noRumah;
$hasil = $noRumah + $jumlahPenghuni;
$hasilAneh = $blok + $noRumah;

Pada sampel kode di atas, variabel alamat akan menyimpan nilai Gubeng Kertajaya 29. PHP secara otomatis mengubah tipe data variabel noRumah (numerik) menjadi literal. Variabel alamat akan bertipe literal.

Variabel hasil akan menyimpan nilai 32, yaitu penjumlahan dari 29 dan 3.
Perhatikan, konversi otomatis ini kadang berjalan secara tidak semestinya. Ini dapat dilihat dari variabel hasilAneh yang akan menyimpan nilai 7. PHP mengambil nilai numerik dari variabel blok, yaitu 4, kemudian menambahkannya dengan isi variabel jumlahPenghuni. Hasil akhirnya adalah 4 + 3, yaitu 7.


d. Passing Variabel
Variabel dapat di-passing atau diteruskan ke halaman web berikutnya yang diakses user. Ada beberapa teknik untuk meneruskan variabel, diantaranya :
• Melalui URL
• Melalui Form
• Melalui Cookie

URL
Variabel diteruskan melalui URL dengan format sbb
[alamat web]?var1=nilai1&var2=nilai2

Misalnya, untuk memberikan variabel $nama berisi “Endy” dan $alamat =

“Surabaya” ke welcome.php, kita akan menulis :
welcome.php?nama=Endy&alamat=Surabaya

Di kolom address pada explorer. Untuk lebih jelasnya, perhatikan gambar berikut.
Variabel ini dapat diakses di script welcome.php dengan cara sebagai berikut :
?>?>?>

Form
Cara lain untuk mengirim kedua variabel tersebut adalah dengan menggunakan form dengan kode sebagai berikut :



Latihan Variabel 2





Varibel Form



Nama :


Alamat :









Cookies
Penggunaan cookie akan dibahas pada bagian tentang session.

6. Operators
Operator digunakan untuk memanipulasi nilai suatu variabel. Variabel yang nilainya dimodifikasi oleh operator disebut operand. Contoh penggunaan operator misalnya 13 - 3. 13 dan 3 adalah operand. Tanda "-" disebut operator.
• Arithmetic Operator
Arithmetic Operator digunakan untuk melakukan perhitungan matematika. Misalnya
$a = 5 + 3;
Operator "+" berfungsi untuk menambahkan kedua operand (5 dan 3).
Ada beberapa arithmetic operator, yaitu :
a. + : penjumlahan
b. - : pengurangan
c. * : perkalian
d. / : pembagian
e. % : nilai sisa pembagian

contoh :
?>?>?>");
printf("6 + 1 = %d
\n",6 + 1);
printf("6 - 1 = %d
\n",6 - 1);

print("
Perkalian :
\n");
printf("10 * 2 = %d
\n",10 * 2);
printf("25 + 3 = %d
\n",25 + 3);

print("
Pembagian:
\n");
printf("100 / 4 = %d
\n",100 / 4);
printf("25 / 5 = %d
\n",25 / 5);

print("
Modulo :
");
print("6 % 5 ="); print(6 % 5); print("
");
print("6 % 3 ="); print(6 % 3);
//printf("6 % 3 = %d
\n",6 % 1);
?>

• Assignment Operator
Assignment operator digunakan untuk memberi/mengisi nilai ke dalam variabel tertentu
Contoh :
?>?>?>\n");

$bil += 2;
print("Isi Variabel bil = $bil
\n");

$bil += 2;
print("Isi Variabel bil = $bil
\n");

$bil += 2;
print("Isi Variabel bil = $bil
\n");

$bil += 2;
print("Isi Variabel bil = $bil
\n");
?>


• Comparison Operator
Relational operator digunakan untuk membandingkan nilai dari dua operand. Hasil perbandingan dinyatakan dalam nilai boolean. TRUE berarti benar, dan FALSE berarti salah.

a. == : memeriksa apakah operand kanan bernilai sama dengan operand kiri
b. > : memeriksa apakah operand kiri bernilai lebih besar daripada operand kanan
c. < : memeriksa apakah operand kiri bernilai lebih kecil dengan operand kanan d. >= : memeriksa apakah operand kiri bernilai lebih besar atau sama dengan operand kanan
e. <= : memeriksa apakah operand kiri bernilai lebih kecil atau sama dengan operand kanan f. != : memeriksa apakah operand kanan tidak bernilai sama dengan operand kiri contoh : ?>?>?> $b -> %d
\n", $a > $b);
printf("$b > $a -> %d
\n", $b > $a);
printf("$a < $b -> %d
\n", $a < $b); printf("$a == $c -> %d
\n", $a == $c);
printf("$a == $b -> %d
\n", $a == $b);
printf("$a != $c -> %d
\n", $a != $c);
printf("$a <> $b -> %d
\n", $a <> $b);
?>

• Logical Operator
Logical Operator digunakan untuk membandingkan dua nilai variabel yang bertipe boolean. Hasil yang didapat dari penggunaan logical operator adalah boolean.

Contoh :
?>?>?>\n",$kar >= 'A' and $kar <="Z"); printf("$kar adalah huruf kecil : %d
\n",$kar >= 'a' and $kar <="z"); printf("$kar adalah huruf angka : %d
\n",$kar >= '0' and $kar <="9"); ?>
































7. Control Structures
Control flow dalam bahasa Indonesia dapat diartikan sebagai aliran kendali. Maksud sebenarnya dari control flow adalah bagaimana urutan eksekusi perintah di dalam program.
Misalnya, dalam function :
function testFlow()
{
int a = 5;
echo(a);
}
Perintah pertama yang dijalankan adalah mengisi nilai 5 ke dalam variabel a.
Perintah kedua yang dijalankan adalah menampilkan nilai yang tersimpan dalam variabel a (dalam hal ini 5) ke browser.
Control flow di atas merupakan sebuah contoh sederhana. Beberapa control flow yang tersedia dalam PHP :
• Percabangan (branching)
• Perulangan (looping)
• Perpindahan (jumping)

a. Pernyataan if
Pernyataan akan dijalankan hanya kalau bagian ekspresi bernilai benar.
Contoh :
?>?>?>= 100000)
$keterangan = "Dapat Diskon";
print("$keterangan
\n");
?>
b. Pernyataan If-else
Menjalankan suatu tindakan tertentu bila kondisi benar dan menjalankan tindakan yang lain jika kondisi bernilai salah.
Contoh :
Hari ini :

?>?>?>
c. dda
d. Dad
e. Das
f. das

8. Conditionals
9. Ietarion and loops
10. Breaking/continuing loops
PHP Project Stage I


Pengenalan Dasar-Dasar Personal Home Page (PHP)

Pengenalan Dasar-Dasar Personal Home Page (PHP)



BAB I
PENDAHULUAN
1. Latar belakang
Saat ini, penggunaan internet sudah semakin banyak dikenal dan digunakan oleh semua kalangan dari anak-anak sampai orang dewasa, Sekarang pengguna internet sudah banyak yang mempunyai web site pribadi, baik yang meggunakan web hosting secara gratis dari ISP, fasilitas Pendidikan ataupun yang mempunyai domain sendiri. Sebagian Besar situs yang mereka buat adalah web site yang statis, mengapa ?salah satu jawabanya bahwa meraka belum mengatahui cara pembuatan halaman web yang dinamis .
Kita dapat mebuat halaman web yang baik dan atraktif dan hanya dengan menggunakan tag-tag atau sintaks HTML murni, namun rasanya situs belum cukup lengkap dan Profesional tanpa adanya salam dinamis, seperti HIT COUNTER, FEEDBACK FORM, Buku Tamu dan Aplikasi data base lasinnya.
Masih banyak pemakai yang merasa takut terhadap rumitnya sebuah program atau Scripts yang menghasilkan sebuah program dinamis, mempelajari bahasa Scripts pada dasarnya tidak berbeda denga mempelajari bahasa pemrogramman lainnya. Bagi anda yang mempunyai niat dan latar belakang sebagai alhi dalam programmer, tentulah lebih mudah untuk memahaminya dan menguasaiinya dalam waktu singakat.namun bagi anda yang benar-benar ingin mempelajar bagaimana membuat suatu halaman web yang dinamis buku ini dibuat dan disusun sedemikian rupa guna menyederhanakan program yang sedemikian mudah.
Bahasa Scripts sudah sering didingar banyak macamnya, diantaranya seperti CGI Scripts, Java Scripts, VB Scripts, ASP, PHP dan lain-lain.Dialam buku ini, jenis program yang digunakan adalah bahasa PHP, dengan pertimbangan bahwa PHP memiliki beberapa kelebihan yang tidak dimilki oleh bahasa sejenisnya, seperti ;
1.3 PHP mudah dibuat dan cepat dijalankan.
2.3 PHP dapat berjalan pada web server yang berbeda dala sistem operasi yang berbeda pula.
3.3 PHP dapat berjalan pada sistem operasi UNIX, Windows, dan Mancintosh
4.3 PHP adalah salah satu bahasa Serve-side yang paling populer saat ini.

Semoga makalah ini bermanfaat dan berguna untuk kemajuan ilmu komputer dan khusunya dibidang web programming.
Saya juga minta saran dan kritik jika terjadi kesalahan ataupun kekuaran didalam pembuatan makalah ini bisa menghubungi saya di Yahoo Massenger saya danoe315@yahoo.com

Atas segala perhatiannya saya mengucapkan banyak terima kasih

Wasalam’u alaikum wr wb.



Rachmat Hidayat, S.Kom


BAB II
PERSIAPAN
1. PERSIAPAN SEBELUM MULAI
Sebelum memulai Pelajaran PHP ada beberapa hal yang perlu kita lakukan agar proses belajar berjalan lancar, yaitu ;
1. Perangkat Komputer
Kebuthan perangkat komputer yang diperlukan adalah minimal komputer dengan Processor 486 Mhz dengan RAM 256 MB, sedangkan perangkat lunak yang dibutuhkan adalah sistem operasi windows XP serta browser microsoft Inernet 4.01.
2. Instalasi Web Server
Untuk dapat melihat scripts anda harus menga Install web server sendiri seperti Apache, PHP dan MYSQL didalam komputer anda atau anda bisa juga bsa mendowload untuk mendapatkan web server secara Free di situs www.apache.org
Untuk mendapatkan web server apachenya,








BAB III
PENGENALAN DASAR PROGRAM PHP
1. PENGENALAN STRUKTUR PROGRAM PHP
Setelah mempersiapkan semuanya, kini saatnya kita akan memulai belajar menggunakan bahasa pemrogramman PHP, namun sebelum kita mulai ada beberapa aturan-aturan dasar yang harus diperhatikan, misalnya ;
1. Pembuatan scripts PHP sangatlah mudah, kita bisa menggunakan dan membuatnya dengan teks editor : NOTEPAD” atau pun teks editor lainnya.
2. Fungsi –fungsi yang ada telah disediakan oleh PHP, jadi tidak membedakan antara hurf kecil dan huruf besar.
3. Variabel dalam PHP adalah Case Sensitive, kita harus berhati-hati dalam penulisan dan pemakaian variabel. Variabel ditandai dengan tanda Dollar Sign ($)
4. Penulisan Scripts PHP diawali dengan tanda ?>?>?> (Tanda Tanya Lebih besar) sebagai akhir dari penutup Program
5. Perintah untuk mencetak gunakan tanda Kutip “ dan tanda titik koma di akhir Program ;
6. untuk penyimpanan, nama file selalu diakhiri dengan titik PHP (.php)
7. Untuk melihat hasilnya, server lokalnya dalam keadaan aktif atau Running




Bentuk umum sederhana scripts PHP




Latihan 1 :
Buatlah program sederhana dibawah ini dengan tampilan “ Hello, Saya sedang belajar PHP “.
Jawaban 1:
?>?>?>
Setelah selesai simpan program di c:myserver\scripts\nama file(latihan1.php), untuk melihat hasilnya benar atau tidak buka internet explorer dan ketikan di addressnya seperti dibawah ini http://localhost/latihan1.php

Gambar 3.1 Localhost
2. DASAR-DASAR PEMROGRAMMAN PHP
Dalam makalah ini anda akan mempelajari dasar-dasar pemrogramman PHP, tentang item-item, perintah dan fungsi-fungsi yang akan banyak digunakan dalam buku ini guna menjaga kesederhananaan dan tidak membuat pengguna menjadi rumit.
2.1. Variabel
Adalah sebuah tempat untuk menyimpan data yang nilainya dapat berubah-ubah, variabel dalam PHP ditandai dengan tanda Dollar ($) variabel dalam PHP adalah case sensitive artinya penggunaan antara huruf besar dan huruf kecil haruslah benar contohnya : $AbC
?>?>?>
2.2. Type Data
PHP juga mengenal tipe data yakni string, Integer, dan Float, tipe data sting di Apit dengan tanda ” ”contohnya :

Tipe Data string
$nama=”Dani”;
$umur=”8tahun”;

Tipe Data integer
$nilai=80;
$jumlah=5;


Tipe Data floating point(double)
$total=10.00;
$jarak=35.15;
2.3. Konstanta
Adalah variabel yang nilainya berubah-ubah, konstanta ini di deklarasikan dan di beri nilai pada awal program dan nilainya tetap, PHP telah mendefinisikan beberapa konstanta TRUE yang diberi nilai 1 dab FALSE yang diberi nilai 0
2.4. Operator
Adalah simbol-simbol yang digunakan untuk memanipulasi data, seperti Penambahan (+), Pengurangan (-), Perkalian (*), dan lain-lain.
Latihan 2
Buat Program sederhana dibawah ini











Simpan program dan jalankan program seperti pada contoh latihan 1 diatas dan lihat hasilnya.
2.5. Kontrol Percabangan
Percabangan adalah melakukan proses jika kondisi yang ditentukan terpenuhi, didalam PHP dikenal 3(tiga) macam percabangan yaitu ;
• IF
• IF..ELSE
• SWITCH

Contoh program :
?>?>?>$b)
{ echo “A lebih kecil dari B”;}
Else
{echo “A lebih besar dari B”;}
?>
Contoh program sederhana Switch..case
?>?>?>
2.6. Kontrol Perulangan
Didalam membuat program terkadang perintah yang ingin ditampilkan bisa dilakukan secara berulang-ulang dan kita tidak perlu menuliskan perintah sebanyak-banyaknya, kita bisa menggunakan perintah perulangan tersebut dengan perintah :
• FOR
• WHILE
• DO..WHILE

Contoh program sederhana for
?>?>?>\n”;
for ($bil=1; $bil<=10; $bil++) { echo “$bil
”; }
?>

Contoh program sederhana if..else
?>?>?>\n”;
$bil=1
do
{
echo “$bil
”;
$bil++;
}
While($bil<=10); ?>














BAB IV
FUNGSI DASAR
1. FUNGSI DASAR PHP
Selain kontrol percabangan dan kontrol perulangan PHP juga bisa membuat program waktu atau jam dan program tanggal, serta fungsi-fungsi lainnya dimana scripts di dalamnya tidak terlalu sulit seperti contoh dibawah ini :
Contoh program sederhana Fungsi Waktu
?>?>?> Jam sekarang adalah = $waktu[hours].$waktu[minutes].$waktu[seconds]
”;
Echo” Tanggal sekarang adalah = $waktu[mday]-$waktu[month]-$waktu[year]”
;
?>
2.1 Pengoprasian file
PHP juga melengkapi fungsi-fungsi built-in yang melengkapi program seperti ;
1. Membuka file = Integer fopen(string nama_file, string_mode) perintah string_mode diantaranya ada : r, w, a, r+, w+, a+.
2. Menulis file = Boolean fputs (Integer file_handle, string keluaran )
3. Membaca isi file = Boolean gfets ( integer file_handle, integer length)
4. Posisi End of File = Boolean feof ( integer file_handle)
5. Menutup file = Boolean fclose (Integer_handle)


Contoh program Pengoprasian File
?>?>?>
2. PROGRAM SITUS DINAMIS DENGAN PHP
Setelah anda mengetahui aturan-aturan dasar scripts PHP, dasar-dasar pemrograman PHP serta fungsi, maka tibalah saatnya bagi anda untuk membuat berbagai macam program atau scripts PHP yang akan menjadikan situs ini menjadi sebuah situs yang dinamis dan interaktif, diantaranya bagaimana mempelajari menampilkan waktu saat situs di kunjungi oleh orang lain.
Pada tahap selanjutnya, penggunaan fasilitias yang melibatkan pengunjung, pemrosesan file dan e-mail. Pada tahap ini kita akan mempelajari bagaimana membuat form dan melakukan koneksi kedalam database MYSQL dengan menggunakan PHP secara sederhana, sehingga situs yang kesemuanya kita buat menjadi situs yang interaktif.
Didalam makalah ini tidak semua form saya buat hanya contoh sederhana saja yang bisa saya buat untuk selebihnya fungsi dan scripts sama saja.
Perlu di ketahui bahwa pembuatan bisa menggunakan program frontpage karena bahasanya masih menggunakan HTML, agar bisa memudahkan dalam pembuatannya.

Contoh program sederhana Pembuatan Form Login





Silakan Login terlebih
dahulu......


Masukan User name    :


Masukan Password      :






Simpan file seperti latihan yang sudah ada dengan extensien . html dan jika dijalankan hasilnya adalah seperti ini :





Gambar 4.1 Form login

3. MENGGUNAKAN DATABASE DENGAN PHP
Salah satu keunggulan PHP dengan yang lain adalah kemampuannya berhubungan dengan berbagai macam aplikasi database, aplikasi database yang beredar saat ini diantaranya adalah MYSQL, Mssql, Apache, Oracel dan Lain-lain. Pada kesempatan kali ini dalam makalah ini akan mempelajari bagaimana koneksi database MYSQL melalui PHP, secara umum akses kedatabase melalui tiga tahapan :
1. Koneksi database
2. Querry / Permintaan Data
3. Pemutusan Koneksi database

3.1 Koneksi database membutuhkan dua fungsi yaitu mysql_connect() dan Mysql_select_file_db().
• Sintaks Mysql_connec()t adalah =
Mysql_connect(namahost, username database, password database)
• Sintaks Mysql_select_db() adalah =
Mysql_select_db(nama database jika telah dibuat)


3.2 Pembuatan database
Untuk membuat databse baru bisa dilakukan dengan 2 cara, yaitu ;
1. Dengan mengaktifkan mysql dari webserver localhost langsung.
2. atau dengan caru membuat sendiri dari DOS form
untuk sarannya dan kemudahan dalam koneksi database buatlah database baru dari localhost yang sudah ada karena hanya membuat nama database lebih mudah dibandingkan dengan dos From.Hanya tinggal mengetikan pada address yang ada di Internet explorer, dan sebelumnya server yang digunakan sudah dalam keadaan aktif seperti Apache, myserver nya,. Lalu ketikan http://localhost/phpmyadmin. tampilan form mysql akan langsung kebuka dan kita bisa langsung membuat database, lalu klik Create.
Seperti tampilan dibawah ini :

Gambar 4.2 Phpmyadmin
Setelah selesai membuat database, langkah selanjutnya membuat nama tabel dan field data, seperti tampilan di bawah ini


Gambar 4.3 Ruang input Field Dbase pada Phpmyadmin
Latihan :
1. Buatlah database dengan nama karyawan
2. Buatlah tabel dengan nama data dan jumlah fieldnya 3
3. isi tabel data adalah NIP (10)int, NAMA (60)varchar, JABATAN (50)varchar

Jika telah selesai membuat database dan tabel dengan menggunakan PHPMYADMIN dan sekarang kita akan membandingkan cara membuat database dan tabel dengan menggunakan scripts PHP.
Pembuatan database selain dengan menggunakan Phpmyadmin, PHP menyediakan cara pembuatan scripts pemrogramman dengan perintah mysql_create_db(). Berikut adalah scripts untuk membuat database dengan nama databasenya adalah KARYAWAN”.
Contoh program sederhana Pembuatan database
?>?>?>
Database data karyawan berhasil dibuat”; }
Else
{ echo “

Databse data karyawan gagal dibuat”; }
?>

Simpan file dengan karyawan.php












BAB V
DATABASE

1. MENGGUNAKAN DATABASE DENGAN PHP
Pada BAB sebelumnya telah diajarkan pembuatan program dinamis misalnya untuk membuat tempat penyimpanan data yang di masukan kedalam suatu file(txt), Metode tersebut berguna pada saat kita tidak memiliki database, jika telah memiliki database maka akan lebih baik jika penyimpanan datanya masuk kedalam database sebab lebih terorganis / terarsip dengan baik. Kita anggap bahwa database karyawan dan tabel data telah di buat, kita akan membuat suatu aplikasi yang berisikan data karyawan dimana kita akan membuat scripts untuk memasukan(Insert), Menampilkan(Select), mengedit(Update), dan menghapus (Delete) record atau data yang ada.
5.1 Memasukan data (Insert)
Sintaks umumnya adalah = insert into nama_tabel(field 1, field 2,.. field N) values (‘data 1, data 2..., data N’)
Contoh program sederhana
Pembuatan Form data karyawan


NIP            :input type="text" name="nip" size="20">


Nama           :


Jabatan          :











Gambar 5.1 Form input karyawan
Setelah form dibuat selanjutnya buat program penyimpanan database dengan menggunakan PHP dimana contohnya adalah :
?>?>?>”;
echo “
NIP Karyawan :”.$nip;
echo “
Nama Karyawan :”.$nama;
echo “
Jabatan Karyawan :”$jabatan;
}
?>
Jalankan file karyawan.html, kemudian lihat hasilnya di browser file simpan dat

5.2 Menampilkan data karyawan
Sintaks umum = Select nama_field 1, nama_filed 2,...nama_Feld N from nama_tabel where Kriteria order by nama_field asc | desc

5.3 Mengubah data (Update)
Sintaks umumnya = Update nama_tabel set nam_field 1=’isi_baru1’, nama_field2=’is_baru2’,... nama_field N=’isi_baru N’ where kriteria

Dan masih banyak lagi sintaks-sintaks PHP yang tidak bisa semuanya saya jelaskan dalam ini, untuk berikutnya akan dilanjutnkan kembali dalam makalah yg lain.















Referensi :

[1]. Free web server apachenya www.apache.org
[2]. Panduan Membuat Aplikasi Database dengan PHP 5 MySQL
Syafii, M 2005
[3]. PHP Manual http://www.php.net
[4]. PHP tutorial http://www.ilmukomputer.com




























BIOGRAFI PENULIS

Rachmat Hidayat, S.Kom Lahir di jakarta 27 Januari 1977, Menyelesaikan Program Strata 1 (S1) di STMIK PGRI Tangerang tahun 2005 Fakultas Sistem Informasi, Pernah bekerja sebagai Staff Komputer di PT.Sinar Kencana Inti Perkasa anak perusahaan BII pengelola Minyak Mentah CPO Kalimantan Selatan th 1998, Bekerja sebagai Waiters di Rumah makan Kore th 1996, terakhir bekerja sebagai Karyawan Tetap Pengajar Komputer di Akademik Bina Sarana Informatika th 2003 s/d sekarang.