Вы находитесь на странице: 1из 80

SAP Library BI Content Getting Started Glossary Help on Help Feedback Advanced

Creating a BSP Application


You create your Web application in the form of a BSP application.

For information about creating BSP applications, see the various tutorials (Creating Web
Applications with BSPs) and the documentation on Web Application Builder, specifically the
sections under Basic Functions.

Extending Security Aspects with BSP Applications


So that a BSP application can function correctly, there must be a node that corresponds to
each BSP application in the service tree (Transaction SICF) of the Internet Communication
Framework (ICF).

From SAP Web AS 6.20, when you create a BSP application in the Web Application Builder,
this type of node is created and activated in the appropriate part of the ICF service tree (see
also Creating an ICF Service). If necessary, you can add permissions for this node (see
also Service Options).

For BSP applications that were created before SAP Web AS 6.20 and which therefore do not
have any nodes in the ICF service tree, this node is generated automatically by the system as
soon as you branch to the corresponding BSP application in change mode.

There may be conflict with old BSP applications with names that are
longer than 15 characters. Before SAP Web AS 6.20 you could
create BSP applications whose names could exceed the length of the
service name in Transaction SICF. In this case, we recommend that
you copy all of the old BSP application to a new BSP application with
a shorter name, so that the node is automatically created.

BSP Tutorials
Purpose
To learn how to create Web applications with Business Server Pages, you can work
through the simple tutorials that build on each other. You should be able to run
through all of the steps described here in your own system.
If you want to develop Web applications with BSPs, your system must meet the
following requirements: Prerequisites for Creating Web Applications.
The following tutorials are available:
1. • First Tutorial: First Steps with Business Server Pages…
2. • Second tutorial: A Small BSP Application and A Small BSP Application with
HTMLB
3. • Third tutorial: Our First Online Bookshop
4. • Fourth tutorial: Further Developing the Bookshop
5. • A small Tutorial is also available for your first steps with the Model View
Controller design pattern.
6. • For a more complex MVC tutorial based on the third tutorial, see: Our Little
Online Bookshop Using MVC and HTMLB

When creating BSP applications, note the browser dependencies described in


Note 598860.
See also:
For reference documentation about the BSP programming model, see Business Server
Pages.

Getting Started with Business Server Pages


Introductory Comments
Welcome to the Getting Started tutorial! In this tutorial, you will use SAP Web
Application Server to create a basic Web application with the SAP Web Application
Server in the form of Business Server Pages (BSPs). This basic application is the
basis of all the tutorials, and will be re-used and enhanced as the tutorials progress.
This tutorial presents you with a number of topics with sample code, which you can
use when creating your own application.
Integration
Each tutorial builds on the information presented in the previous one.
Below are links to the other tutorials:
• Tutorial 2
• Tutorial 2 with HTMLB
• Tutorial 3
• Tutorial 4
• MVC Tutorial
• Our Little Online Bookshop Using MVC and HTMLB

You can also read the reference documentation on the SAP Web AS
Architecture, which explains the system’s architecture and components:
Features
In this tutorial you will learn how to:
• Create a BSP Application with one page
• Create HTML code with dynamic script in ABAP
• Insert a graphic (MIME object)
• Display the activated page in the Web browser

Let’s get started!

Application Class of a BSP Application


Overview
A BSP application can include a multitude of different development objects. One of these
objects is the application class of the BSP application.

The application class is a regular ABAP Objects class. As such, the application class can
include any methods, attributes, and events the developers wants.

The application class is usually used to store data and make it available across BSP pages.
This data is stored as attributes. In addition, the application class encapsulates BSP
application logic in methods. This allows several BSP applications to use the same
application class and provide one business application that contains different interfaces, such
as for various devices, without having to replicate the business or application logic.

This also means the global Object application can be used in the BSP application to access
the attributes and methods of the application class.

You do not have to use an application class in your BSP application. It is an optional way for
you to structure your BSP application.

You use the Web Application Builder in transaction SE80 to assign an application class to a
BSP application.
A simple example of where an application class could be useful would be a
class for controlling dialog logic and maintaining data consistency in a BSP
application for shopping. This application class would include a shopping
basket (internal table or other object) as an attribute. There would also be
methods for changing and processing the shopping basket, such as to add,
change, or delete articles. Methods for determining prices, creating offers,
and posting orders would also be helpful.

For an example of the use of an application class, see Extending the Online
Bookshop.

In many cases, the application class is only used to encapsulate existing


application functions, such as from SAP Customer Relationship Management
(SAP CRM), and then access the function through BAPI interfaces. Using an
application class to encapsulate the functions ensures that the BSP
application functions are stored in a central location (in the application class)
and that both implementation and distribution are transparent (local method
call but remote BAPI call internally). If a customer or developer wants to
change or adapt a BSP application or use the application for an additional
device, they have the full functions of the original BSP application available in
the interface of the application class.

Runtime Behavior
Any ABAP Objects class can potentially be used as an application class of a BSP application.
However, the BSP runtime environment must treat the class as a singleton, that is, a class for
which there is only one instance per session.

The lifetime of an application class depends on the state model of the BSP application. A BSP
application can be stateful or stateless.

Stateful BSP Application


In Stateful BSP Applications the only instance of the application class, the application object,
is generated at the first request sent to the BSP application. The object is then available for
the entire lifetime of the session. The end lifetime of the application object ends when the
session ends.

In stateful mode, the application class provides local buffering for data sets that are difficult to
determine.

Stateless BSP Application

In Stateless BSP Applications, the application context (roll area) is only available for the
lifetime of a single request and is released at the end of the request. When the application
context is released, all data and objects held by the session on the application server are also
released. This includes the application object.

This means the lifetime of the application object starts when the request is received and ends
when a response is sent. The application objects is not available across several pages. Each
page and each request interacts with a different instance of the application class.

In stateless mode, the application object cannot hold data across requests. For stateless
applications, application classes are usually used to store the business logic in methods, but
do not buffer data.

Accessing the Application Object


To access the application object, you use a typed object reference that is stored as the
parameter application in all event handlers of a BSP. Of course, you must ensure, however,
that the parameter only exists if an application class is defined for a BSP application.

Requirements for an Application Class


The only requirement for an application is that the constructor is parameter-less. If not, the
application class cannot be generically instantiated by the BSP runtime environment.

Otherwise there are no other restrictions. You do need to ensure that the internal
implementation of methods is chosen correctly, depending on the state mode where the class
is implemented. For stateless applications, for example, it would be useless to implement
expensive data gathering routines as these would be lost after every request. Instead, just get
the exact data you need at that time. In stateful applications, you can implement an
initialization phase where you get a large amount of data at one time, which can improve
performance.

Application Events: The IF_BSP_APPLICATION_EVENTS


Interface
In stateless BSP applications, an application often needs centralized control at certain times
in the lifetime of the application. The BSP model provides this function for the application
class in the predefined interface IF_BSP_APPLICATION_EVENTS.

When an application class implements the optional interface


IF_BSP_APPLICATION_EVENTS, the BSP runtime environment calls the interface methods
at the relevant times. The following describes the methods and times:

IF_BSP_APPLICATION_EVENTS~ON_START This method is called by the BSP runtime


environment when the corresponding
BSP application is first started at the start
of the BSP session. This applies to both
stateless and stateful applications.

Typically, this time point is used to carry


out authorization checks that apply to the
entire application, or for preliminary data
retrieval (in stateful applications).

IF_BSP_APPLICATION_EVENTS~ON_STOP This method is called by the BSP runtime


environment when the corresponding
BSP application is explicitly ended. This
applies to both stateless and stateful
applications.

Please note that this time point is not


available after every request in stateless
BSP applications. In addition this time is
not evaluated if the session is implicitly
terminated by a timeout. Consequently, in
this method it is only possible to execute
optional operations that are not critical.

Typically, this is a good time for cleanup


operations such as deleting browser
cookies or server-side cookies, if the
application generated them.

IF_BSP_APPLICATION_EVENTS~ON_REQUEST This method is called by the BSP runtime


environment for every incoming request
to a BSP before the BSP is given control
(in the OnRequest event handler).

This time can be used by the application


class, for example, to restore attributes
that were rescued in client- or server-side
cookies in a previous request.

IF_BSP_APPLICATION_EVENTS~ON_RESPONSE This method is called by the BSP runtime


for every outgoing response of a BSP
after the BSP has been processed (after
the OnManipulationevent handler).

This time can be used by a stateless


application class for tasks such as
rescuing attributes in client-side or
server-side cookies.

See also:

You can find details of interface IF_BSP_APPLICATION_EVENTS in the reference


documentation: Interface IF_BSP_APPLICATION_EVENTS
Application Basis Class CL_BSP_APPLICATION
If an application class does not already have a super class, it can be derived from the
predefined base class CL_BSP_APPLICATION. This class provides methods that are
typically required by a BSP application for embedding in a Web environment. This is how
information about the current BSP application (such as session timeout, current URL of BSP
application, state mode, and so on) can be called or set.

As the application object is an application attribute in every BSP event handler, the
methods of the CL_BSP_APPLICATION class are also available with the corresponding
inheritance. This makes it easy to provide the relevant functionality to lower application levels
using a single object reference.

See also:

You can find details of basis class CL_BSP_APPLICATION in the reference documentation:
Class CL_BSP_APPLICATION

BSP Components
Business Server Pages (BSPs) are HTML pages that contain the actual application logic and
presentation logic. BSPs define the Web user interface and determine the elements of user
interaction.

BSPs consist of the following components:


Server-side scripting determines the presentation logic as part of layout processing. In the
preview, you can check the appearance of your pages, without having to call up the browser.

Page attributes are visible in the layout processing as well as in the event handlers of a page.
They can be used to store data obtained in the standard handler OnInitialization, and to make
this data accessible for the layout processing and the other event handlers.

Predefined event handlers are available for the different events.

You can use type definitions to define local types.

Similar to every object in the SAP System, BSPs also have different administration attributes.

BSP Directives
Overview
BSP directives are enclosed in tags: <% Directive %>

The directives described in the following sections are supported by Business Server Pages
(BSP). The syntax is compatible with the familiar server page technology.

The following BSP directives are available:

• Page Directive
• Inline Code
• Comments
• Include Directive
• OTR Directives
• Extension Directive

You use the Tag Library to add BSP directives to your code using
Drag & Drop.
For more information see Transferring Variables.
Special Programming Features
The following code sections for the layout of a BSP are not equivalent:
<% read table itab index lv_index. %>
<% if sy-subrc ne 0. clear workarea. endif. %>
and:
<% read table itab index lv_index.
if sy-subrc ne 0. clear workarea. endif. %>
The first code extract above contains a function module call between the two ABAP
commands. The second code extract does not:
....
* BSP SCRIPT source
read table itab index lv_index.
* BSP STATIC source
* HTML begin: #### ######
CALL METHOD %_IF_PM->ADD_STATIC_REF
exporting
encoding = 0
source = %_HTML_POOL
offset = 0000018407 length = 0000000039 .

* BSP SCRIPT source


if sy-subrc ne 0. clear workarea. endif.
....
This means that the sy-subrc set when the internal table is read is overwritten by the
function module call. The two pieces of code therefore behave differently.

Page Directive
Definition
This directive is used to specify the script language.

ABAP and JavaScript are currently supported.

<%@ page language=("ABAP" | "JAVASCRIPT") %>

otrTrim

From SAP Web AS 6.20 Support Package 7, the attribute otrTrim is also available for the
page directive.

<%@ page language=("ABAP" | "JAVASCRIPT")


otrTrim=("TRUE" | "FALSE") %>

This attribute is a boolean value, that is, it can have the values TRUE and FALSE. The default
value is FALSE. If it is set to TRUE, all OTR texts on a page are condensed by removing all
blank characters from the start and end of a string.

An example of switched on attribute (otrTrim=true):

<%@page language="abap" otrTrim="true" %>


<%
DATA: s TYPE STRING VALUE 'test'.
%>
[<otr> test line </otr>]<br>
[<otr> before <%= s%> middle <%= s%> end. </otr>]<br>
[<%= otr(sbsp_test/it00_otr_1) %>]

The output generated using this coding then looks as follows:


[test line]
[before test middle test end.]
[This is a test for an alias text]

Example of the case when otrTrim is switched off (otrTrim=false):

<%@page language="abap" otrTrim="false" %>


<%
DATA: s TYPE STRING VALUE 'test'.
%>
[<otr> test line </otr>]<br>
[<otr> before <%= s%> middle <%= s%> end. </otr>]<br>
[<%= otr(sbsp_test/it00_otr_1) %>]

The output generated using this coding then looks as follows:

[ test line ]
[ before test middle test end. ]
[This is a test for an alias text]

Inline Code
Definition
With this directive you can embed the script code into the page.

The inline code is written in the language specified with the Page directive.

<% inline code %>

<%@ page language="javascript"%>… <% inline code


javascript %>…
Comments
Definition
You can write comments on the code on the server.

Unlike code that includes HTML comments, server-side comments are not included in the
page sent to the client /browser.

When you use HTML comments, however, they require longer processing times as well as
larger bandwidths. This is why you should not use HTML comments with BSPs or views.

<%-- code comments or text --%>

Include Directive
Definition
With this directive you can paste in existing pages or pages fragments into the page.

Enter the URL of the page to be pasted in relative to the URL of the current page.

<%@ include file="relative URL"%>

OTR Directives
Definition
The Online Text Repository (OTR) is a repository for all HTML texts, which are accessed
using an alias. OTR texts can be translated into other languages using translation tools. At
runtime, the OTR directive is replaced by the text defined for the logon language.

Use
There are two ways of using the OTR.

1. You can first write the text in the OTR and give it an alias that should be as
meaningful as possible.

Then you can display the text with the following syntax: <%=otr(alias)%>.

2. You can however also specify the text in the page layout:

<otr> HTML text, can also contain scripting code </otr>


This is an auto-OTR text that is automatically transferred to the OTR and
translated there. If the user logs on in a different language, they see the
translated text.

The text is only automatically transferred if it was entered in the


original language.
See also:
Internationalization and Translation
Online Text Repository (OTR)

Extension Directive
Definition
You can use the extension directive to import a BSP extension into your BSP. As a result you
can access all elements of the extension in your BSP. The extension directive is always
located immediately after the page directive.

<%@extension name="<Name>" prefix="<Präfix>"%>

The prefix is used as the namespace for all elements in the BSP extension. The prefixes sap
and bsp are reserved.

See also:

BSP Extensions

Business Server Pages


Security Aspects for BSP
User Concepts
Programming Model
What is a BSP Application?
Structure of a BSP Application
Accessing a BSP Application
Starting and Ending a BSP Application
System-Specific URL Parameters
Processing a BSP Application
Creating a BSP Application
Application Class of a BSP Application
BSP Components
BSP Directives
Page Directive
Inline Code
Comments
Include Directive
OTR Directives
Transferring Variables
Extension Directive
Classes and Interfaces
Global Objects
BSP Extensions
Model View Controller (MVC)
Session Handling
Control Flow of BSPs
Caching BSPs
Page Layout
Accessibility
Programming Environment
SAP Enterprise Portal
Administration
BSP Tutorials
Getting Started with Business Server Pages
A Simple BSP Application
A Simple BSP Application with HTMLB
Online Bookshop
Further Developing the Online Bookshop
Model View Controller Tutorial
Our Little Online Bookshop Using MVC and HTMLB
FAQ

Classes and Interfaces


The following classes and interfaces are central components of the BSP programming
model.
Classes:
• Class CL_BSP_APPLICATION
• Class CL_BSP_MESSAGES
• Class CL_BSP_SERVER_SIDE_COOKIE
• Class CL_BSP_GET_TEXT_BY_ALIAS
• Class CL_BSP_CONTROLLER2
Interfaces:
• Interface IF_BSP_APPLICATION
• Interface IF_BSP_APPLICATION_EVENTS
• Interface IF_BSP_NAVIGATION
• Interface IF_BSP_PAGE
• Interface IF_BSP_RUNTIME
• Interface IF_BSP_PAGE_CONTEXT
• Interface IF_HTMLB_TABLEVIEW_ITERATOR
Many of these classes and interfaces are the basis for their associated global objects.

To develop BSP applications with the focus on representing Web pages on


different mobile end devices, you can use interface IF_CLIENT_INFO.

Global Objects
Certain global objects can be accessed from all parts of a BSP (initialization, layout, input
processing). For example, the request and response object, the application object (if an
application class was defined for the BSP application), the navigation object, and the runtime
object, can be accessed.

The following global objects are available:

• Object application
• Object navigation
• Object messages
• Object runtime
• Object request
• Object response
• Object page
• Object page context

This is described in more detail below.

The objects and their signatures for the individual event handlers are
displayed if you choose in the Web Application Builder.
Example:
Class CL_BSP_APPLICATION
Overview
Class CL_BSP_APPLICATION is an optional superclass for BSP application classes. Each
application has the option of deriving its own application class from CL_BSP_APPLICATION .
If the application class has not already been derived in an inheritance hierarchy, we
recommend that it is derived from CL_BSP_APPLICATION .

Class CL_BSP_APPLICATION has methods that are typically required by a BSP application
for embedding in a Web environment. This is how information about the current BSP
application (such as session timeout, current URL of BSP application, state mode and so on)
can be called or set.

All of the methods of class CL_BSP_APPLICATION can be accessed via the


interface IF_BSP_APPLICATION and are described in the corresponding
reference documentation.

See Also:

• IF_BSP_APPLICATION
• Object application
Class CL_BSP_MESSAGES
Overview
You can use class CL_BSP_MESSAGES in BSPs for outputting error and information
messages.

You can flag each message with a condition that serves as a key for the message. The effect
of this is that a message is only output in a BSP if the pertinent condition is fulfilled. This
makes it easy to place input-specific messages directly beside the relevant input fields.

Each BSP has an instance of this class that contains the current messages of the class. The
object is reset after every HTTP request/response cycle. The object is accessed from a BSP
via the parameter page of the event handler as page->messages or via the self-reference
me in the form of interface qualification me->if_bsp_page~messages.

Inheritance Hierarchy/Interface Composition

Implemented Interface

Superclass

Attributes

Attribute Name Declaration Type Description

co_severity_error Constants Error severity: error

co_severity_fatal_error Constants Error severity: Fatal error

co_severity_info Constants Error severity: Information

co_severity_success Constants Error severity: Confirmation of


success

co_severity_warning Constants Error severity: Warning

Methods

Method add_message

Signature method add_message


importing
condition type string
message type string optional
otr_alias type string optional
severity type i default co_severity_error
.

Description This method inserts the message on the


condition specified into the list of messages. If
there is already a message with the condition, it
is overwritten.

One of the two parameters message or


otr_alias must be specified (exclusive or). If
message is used, the message text is
transferred directly, if otr_alias is used, the
alias name of an OTR text is transferred. This
makes it easy to address language-dependent
messages from the OTR.

Parameters CONDITION Message condition

MESSAGE Message text (if


otr_alias-parameter
is not used)

OTR_ALIAS Alias name of an OTR


text to be used as
message text (if
message parameter
is not used)

SEVERITY Message severity (see


constants
co_severity_...)

Return Values/Exceptions -

Cross References See also: assert, assert_message,


assert_severity

Method assert

Signature method assert


importing
condition type string
returning
index type i
.

Description This method returns the message index (1..n)


for the condition specified or 0 if there is no
message for this condition.

Thus, you can use this method in BSPs in if


statements if, for example, you want to insert
HTML areas in the output on a message-
dependent basis.

Example:

...
<% if page->messages->assert( 'invaliduser' )
<> 0. %>
<img src="stop.gif">
<%= page->messages->assert_message(
'invaliduser' ) %>
<% endif %>

Parameters CONDITION Message condition

Return Values/Exceptions INDEX =0: no message for


condition

>0: Message index

Cross References See also: assert_message,


assert_severity

Method assert_message

Signature method assert_message


importing
condition type string
returning
message type string
.

Description This method returns the message for a specified


condition. If there is no message for the
condition, it returns an empty string.

Parameters CONDITION Message condition

Return Values/Exceptions MESSAGE Message

Cross References See also: assert, assert_severity

Method assert_severity

Signature method assert_severity


importing
condition type string
returning
severity type i
.

Description This method returns the message severity (see


constants co_severity_... ) for the
specified condition, or 0 if there is no message
for the condition.

Parameters CONDITION Message condition

Return Values/Exceptions SEVERITY =0: no message for


condition

>0: Message severity


(see constants
co_severity_...)

Cross References See also: assert, assert_message

Method get_message

Signature method get_message


importing
index type I
exporting
severity type I
condition type string
message type string
.

Description This method returns information about the


message for the specified index (1..n). If there is
no message for the index, in other words, if
index > num_messages(), this is indicated
by severity = 0 .

Parameters INDEX Message index


(1..num_messages())

Return Values/Exceptions message Message text

condition Message condition

severity Message severity (see


constants
co_severity_...)

Cross References See also: add_message, num_messages

Method num_messages

Signature method num_messages


returning
count type I
.

Description This method returns the number of messages


that were defined using add_message().

Parameters -

Return Values/Exceptions count Number of currently


existing messages

Cross References See also: add_message

Class CL_BSP_SERVER_SIDE_COOKIE
Overview
Class CL_BSP_SERVER_SIDE_COOKIE provides methods for setting, getting, deleting, and
managing cookies on the server.

Server-side cookies are persistent data, similar to the usual client-side cookies. However,
while on the client-side, there are restrictions that limit the size of cookies to around 4
kilobytes per cookie, the number of cookies to 300 in total and 20 per server or domain,
server-side cookies are subject to no such restrictions. A server-side cookie is stored on the
database.
For technical reasons, each individual cookie can be stored in one of the following ways:

• as a field or
• as a structure or
• as an internal table

When you get a cookie, please note that it must be returned to the
same data structure. Otherwise, an error will occur, which you can
query using an error method.
The parameters username and session_id deserve special attention. Setting username
to sy-user is ambiguous in cases where an application is started by an anonymous user
stored on the server. It would be better to use session_id (see example) since runtime-
>session_id indicates the browser session.
When you design an application, you should give careful consideration to whether the
application should be stateless and the required context data be retained from page to page
in cookies (client-side or server-side), or whether the application should be stateful. A stateful
application makes sense when there is a large amount of context data that would otherwise
have to be read from or written to the database using cookies and thus slow down
performance (see also Stateful or stateless programming?).
The program BSP_SHOW_SERVER_COOKIES provides an overview of all of the cookies set in
the system. The program BSP_CLEAN_UP_SERVER_COOKIES deletes all expired cookies to
the day.
The system administrator should schedule the program
BSP_CLEAN_UP_SERVER_COOKIES to run in the background on a
regular basis.
Class CL_BSP_SERVER_SIDE_COOKIE is contained in the package SBSP_RUNTIME.
Inheritance Hierarchy/Interface Composition
Implemented Interface
-
Superclass
-
Attributes
Attribute Name Declaration Type Description

CC_OK Constants Action was successful.

CC_WRONG_DATA_OBJECT Constants The data object of the cookie


to be read does not match the
data object of the set cookie.

CC_PARAMETER_MISSING Constants Call parameters are missing.

CC_NOT_EXISTS Constants Cookie does not exist.

Methods

All of the methods are in the visibility section public section.


Method get_server_cookie
Signature method GET_SERVER_COOKIE
exporting
NAME
EXPIRY_TIME
EXPIRY_DATE
SESSION_ID
USERNAME
APPLICATION_NAMESPACE
APPLICATION_NAME
DATA_NAME
DATA_VALUE

Description This method gets a server cookie.


Parameters EXPIRY_TIME Validity date (time):
to time

EXPIRY_DATE Validity date (date):


to date

DATA_NAME Data object name

SESSION_ID Session ID

USERNAME Name of user

APPLICATION_NAMESPACE Name space of BSP


application

APPLICATION_NAME Name of BSP


application

NAME Name of cookie

DATA_VALUE Data object content

data: sorders type sales_orders,


edate type d,
etime type t,
usr type string.
clear sorders.
call method
cl_bsp_server_side_cookie=>get_server_cookie
exporting
name = 'SALESORDER_GETLIST'
application_namespace = runtime-
>application_namespace
application_name = runtime->application_name
username = usr
session_id = runtime->session_id
data_name = 'SORDERS'
importing
expiry_date = edate
expiry_time = etime
changing
data_value = sorders.
Method delete_server_cookie
Signature method DELETE_SERVER_COOKIE
exporting
NAME
APPLICATION_NAME
APPLICATION_NAMESPACE
USERNAME
SESSION_ID

Description This method deletes a server cookie.


Parameters NAME Name of cookie

APPLICATION_NAME Name of BSP


application

APPLICATION_NAMESPACE Name space of BSP


application

USERNAME Name of user

SESSION_ID Session ID

data: usr type string.


call method
cl_bsp_server_side_cookie=>delete_server_cookie
exporting
      name = 'SALESORDER_GETLIST'
      application_namespace = runtime-
>application_namespace
      application_name = runtime->application_name
      username = usr
      session_id = runtime->session_id.
Method set_server_cookie
Signature method SET_SERVER_COOKIE
  importing
    DATA_VALUE
  exporting
    EXPIRY_DATE_ABS
    EXPIRY_TIME_ABS
    DATA_NAME
    SESSION_ID
    USERNAME
    EXPIRY_TIME_REL
    EXPIRY_DATE_REL
    APPLICATION_NAMESPACE
    APPLICATION_NAME
    NAME

Description This method sets a server cookie.


Parameters DATA_VALUE Data object content

EXPIRY_DATE_ABS Valid to date

EXPIRY_TIME_ABS Absolute validity


duration

If you do not specify


a value, the system
sets the absolute
validity duration to
23.59.

DATA_NAME Data object name

SESSION_ID Session ID if
required

USERNAME Name of user, and e-


mail address

EXPIRY_TIME_REL Relative validity


duration in seconds

If you do not specify


a value, the system
sets the relative
validity duration to
23.59.

EXPIRY_DATE_REL Validity duration in


days

APPLICATION_NAMESPACE Name space of BSP


application

APPLICATION_NAME Name of BSP


application

NAME Name of cookie

data: sorders type sales_orders,


      edate type d,
      usr type string.
call function 'BAPI_SALESORDER_GETLIST' destination
'ABC'
  exporting
    customer_number = '0000001000'
  tables
    sales_orders = sorders.
edate = sy-date.
add 1 to edate.   "valid for one day
call method
cl_bsp_server_side_cookie=>set_server_cookie
  exporting
    name = 'SALESORDER_GETLIST'
    application_namespace = runtime-
>application_namespace
    application_name = runtime->application_name
    username = usr
    session_id = runtime->session_id
    expiry_date_abs = edate
    expiry_time_abs = sy-uzeit
    data_name = 'SORDERS'
    data_value = sorders.
Method get_last_error
Signature method GET_LAST_ERROR
  importing
    RC

Description This method returns the return code of the last


call.

Parameters RC Returncode

data: rc type i,
      txt type string.
rc = cl_bsp_server_side_cookie=>get_last_error( ).
Method get_last_error_name
Signature method GET_LAST_ERROR_NAME
  importing
    NAME

Description This method returns the internal name of the


exception of the last call.

Parameters NAME Internal error text

data: rc type i,
      txt type string.
rc = cl_bsp_server_side_cookie=>get_last_error( ).
if rc ne 0.
  txt =
cl_bsp_server_side_cookie=>get_last_error_name( ).
endif.
Method get_server_cookie_info
Signature method GET_SERVER_COOKIE_INFO
  exporting
    COOKIES
    APPLICATION_NAMESPACE
    APPLICATION_NAME
    SESSION_ID
    USERNAME
    NAME

Description This method returns information about server cookies.

Parameters COOCIES List of all cookies.

APPLICATION_NAMESPACE Name space of BSP


application

SESSION_ID Session ID

USERNAME Name of user

NAME Name of cookie

APPLICATION_NAME Name of BSP


application

data: usr type string,


      cookie_info type tsscookiei.
call method
cl_bsp_server_side_cookie=>get_server_cookie_info
  exporting
    application_name = runtime->application_name
    username = usr
  importing
    cookies = cookie_info .

Class CL_BSP_GET_TEXT_BY_ALIAS
Overview
Class CL_BSP_GET_TEXT_BY_ALIAS provides a method to fetch OTR alias texts.

Inheritance Hierarchy/Interface Composition

Implemented Interface

Superclass

Attributes
-
Methods

Method GET_TEXT

Signature method GET_TEXT


importing
LANGUAGE
ALIAS
returning
ALIAS_TEXT.

Description This method fetches an OTR alias text for a specified OTR
alias name.

Parameters LANGUAGE Current language of SAP


System

ALIAS Name of alias in form


’<Paket>/<Aliasname>’

ALIAS_TEXT Text of the alias

Cross References See also:

Internationalization and Translation

Method GET_OTR_TEXT of IF_BSP_RUNTIME

report OTRTEST.

class CL_BSP_RUNTIME definition load.


data TEXT type STRING.
TEXT = CL_BSP_RUNTIME=>GET_OTR_TEXT(
ALIAS = 'sbsp_test/it00_otr_1' ).

write / TEXT.

Class CL_BSP_CONTROLLER2
Overview
Class CL_BSP_CONTROLLER2 is used to create controllers and components. Every controller
class automatically inherits all methods and attributes from this central basic class.
If the basic class of your controller class displays
CL_BSP_CONTROLLER instead of CL_BSP_CONTROLLER2, change
the inheritance hierarchy accordingly.

Class CL_BSP_CONTROLLER2 enables you to:

• Retain a list of sub-controllers


• Create unique IDs for the sub-controllers, where the sub-controller is assigned the
controller ID prefix
• Use models
• Forward data to the correct controller as well as fill model classes (if they exist)

Methods
Below you can find an overview of all methods in a controller class. Processing Process
provides details on the most important methods.
The individual methods can be separated into different categories:
Functions where overwriting is required
DO_REQUEST is the central method in a controller class.

You must overwrite this method.


In DO_REQUEST you specify the request processing, that is, this method is called for every
request. This method does the "main work"; in particular it should branch to the correct view.
DO_REQUEST can be used in two different areas:

• If it is the top-level controller of a component, then this method handles both input
and output processing.

• If it is a sub-controller of a component, then this method only handles output


processing.

Functions where overwriting is recommended


You should overwrite these methods in order to determine input processing.
Method Description

DO_HANDLE_DATA Reacts to user input.


Processes data input for this component.

DO_HANDLE_EVENT Reacts to user input.


Processes events if the component contains them.

Exactly one view controller is called to handle the


event, which contains an event such as a save button,
for example.

DO_FINISH_INPUT Ends the input processing.

Functions where overwriting is possible


You can overwrite these methods in order to determine input processing.
Method Description
DO_INIT This method is called once at the start and is used for
initialization.

This method behaves like a constructor method.

DO_INITATTRIBUTES This method is called with every request and is used


to initialize the attributes. The parameters are read
from the request. In this method, you can also
execute initializations that are required for each
request.

You can also use this method to set additional


attributes. This method is not absolutely necessary,
since you can use DO_REQUEST to solve everything
that you can (theoretically) handle here.

Service functions
You can call these methods:
Method Description

CREATE_VIEW Creates or fetches a view instance

Use either the name of the view, or the object


navigation.

A view must always belong to the same BSP


application as its controller.

CALL_VIEW Calls the request handler of the view instance.

CREATE_CONTROLLER Creates or fetches a controller instance

CALL_CONTROLLER Calls the request handler (method DO-REQUEST) of


the controller instance.

GET_ATTRIBUTE Returns the specified page attributes.


Generic method for reading an attribute value.

GET_LIFETIME Returns the lifetime of this page (only for the top-level
controller)

GET_PAGE_URL Returns the URL of the page or the current controller

SET_ATTRIBUTE Sets the specified page attributes.


Generic method for setting an attribute value.

SET_LIFETIME Changes the lifetime of this page (only for the top-
level controller)

TO_STRING Creates a formatted string

WRITE Writes a formatted string in the output


GET_OUT Fetches the current output writer

SET_MIME_TYPE Changes the MIME type of the page or the content


type of the header field

INSTANTIATE_PARAMETER Instantiates the parameter from the request using the


request data

SET_CACHING Changes the caching values

There are two types of caching:

• Browser cache

• Server cache

See also Caching BSPs.

You can only use limited caching here.


Note that the server cache is not user-specific.
If you change the page, you should reset the cache
that may be set.

DISPATCH_INPUT Dispatches the input processing (only for the top-level


controller).
For each input, DISPATCH_INPUT calls the correct
methods in the correct sequence.
This method fetches data from the request.

This method does not have any attributes.

GET_ID Calculates the ID from the specified ID and the


component ID

SET_MODEL Creates and registers a model instance

CREATE_MODEL Creates and registers a model instance

GET_CONTROLLER Fetches a sub-controller

CONTROLLER_SET_ACTIVE Sets a controller to active/inactive.


This is relevant with input processing, since you can
use it to hide a controller.
See also Lifetime

DELETE_MODEL Deletes a model instance

FILL_MODEL_DATA Fills the model data

DELETE_CONTROLLER Deletes a sub-controller

GET_MODEL Fetches a model instance

IS_TOPLEVEL Is this controller a top (main) controller (0: no, 1: yes)?


IS_NAVIGATION_REQUESTED Has a controller requested a navigation (0: no, 1:
yes)?

Framework functions
These methods are provided as part of the framework and are only included here for the sake
of completeness. They are not usually relevant for application development.
Method Description

IF_BSP_DISPATCHER~REGISTER Registers a sub-components

IF_BSP_CONTROLLER~FINISH_INPUT_PROCESSING Processes or dispatches: end of input


processing.

IF_BSP_CONTROLLER~FILL_VALUES Processes or dispatches: handling values

IF_BSP_CONTROLLER~HANDLE_EVENT Processes or dispatches: Handle event

GET_FIELD_COMPONENT Finds components for a field name

GET_FIELD_MODEL Finds model for a field name

Methods DO_DESTROY and SUBSCRIBE are not relevant.

Examples of Architecture
Previous BSP Application
With SAP Web AS 6.10, normal BSP applications usually consisted of an application class
and several BSPs. Navigation between the pages was controlled using redirects.
This is how it looks with SAP Web AS 6.20: BSP Application with Controllers and Views

Model View Controller Tutorial


Uses

In this tutorial you can use a simple example to run through the first steps with the Model
View Controller design pattern for BSP.

The general bookshop tutorial for BSP contains a more extensive


MCV tutorial: Our Online Bookshop Using MVC and HTMLB.

Prerequisites
• You are in an SAP Web AS 6.20 system
• You know how to use MVC for BSPs

Functions
Creating a Controller
Creating a View
Calling a Controller
Creating a Controller
Prerequisites
You have created an empty BSP application for this tutorial.

Procedure
1. Create a controller within your BSP application.

To do this, choose Create → Controller.

2. On the following dialog box, give the controller a name and add a short description.

3. Choose .
4. On the following screen, assign a class name to the controller.

The class does not have to exist yet.


5. You navigate to the Class Builder by double-clicking on the controller class.

If the class does not already exist, the system asks you if you want to create it.
Choose Yes so that you create a class with the specified name that is derived from
CL_BSP_CONTROLLER2.

Each controller class must be derived directly or indirectly from


CL_BSP_CONTROLLER2.

6. Choose the symbol to branch to the change mode in your class.


7.

Select method DO_REQUEST and choose symbol to overwrite the methods.

8. Generate the required output.

In this example, it is simple HTML:

method DO_REQUEST .

write( '<html><body><H1>' ).

write( 'This is my very first controller' ).

write( '</H1></body></html>' ).

endmethod.

9. Activate your class and your BSP application.


10. Before you can test the controller, in Transaction SICF you must also activate the
new entry that was automatically created for your BSP application (see also
Activating and Deactivating an ICF Service).
In Transaction SICF, select the entry for your BSP application and choose
Service/Virt.Host → Activate.

Confirm the following confirmation prompts.

11. You can now test the new controller page that you have created.

Result

Continue by creating a view.


Creating a View
Use

If you do not always want to use the write function to create the HTML page
content (as described in Creating a Controller), and you want to create it as pure
HTMLO layout instead, then create a view that you can call from the controller.

Procedure
...

1. Begin as if you are creating a normal page with flow logic in your BSP application.
To do this, choose Create → Page.

2. In the following dialog box, enter a name and short description of the view and
select View as the page type:

3. Choose .
4. Create the attributes for the variable parts of the view.

You cannot define auto-page attributes, since views cannot be called directly from the
browser.
Create the following attribute:

5. Define the layout as usual:


<%@ page language="abap" %>

<html>

<head>

<link rel="stylesheet"
href="../../sap/public/bc/bsp/styles/sapbsp.css">

<title> Layout for Controller </title>

</head>

<body class="bspBody1">

<H1>View Example</H1>

<H3>Hello, user <%= name%></H3>

</body>

</html>
6. Activate the view.
7. Finally, adjust the DO_REQUEST method to the controller class.
Here, the schema is always the same. First you create the view, then you set the
attributes, and then you call the view. (For the time being you can ignore the warning
concerning exception CX_STATIC_CHECK, or you can set a try-catch block around
the calls):
method DO_REQUEST .

data: myview type ref to if_bsp_page.

myview = create_view( view_name = 'view_test.htm' ).

myview->set_attribute( name = 'name' value = sy-uname ).

call_view( main_view ).

endmethod.
8. Activate your class and test your controller.
Result

You have created your own view for the layout.

Continue by Calling the Controller.

Creating a View
Use

If you do not always want to use the write function to create the HTML page
content (as described in Creating a Controller), and you want to create it as pure
HTMLO layout instead, then create a view that you can call from the controller.

Procedure
...

1. Begin as if you are creating a normal page with flow logic in your BSP application.
To do this, choose Create → Page.
2. In the following dialog box, enter a name and short description of the view and
select View as the page type:

3. Choose .
4. Create the attributes for the variable parts of the view.

You cannot define auto-page attributes, since views cannot be called directly from the
browser.
Create the following attribute:

5. Define the layout as usual:


<%@ page language="abap" %>

<html>

<head>

<link rel="stylesheet"
href="../../sap/public/bc/bsp/styles/sapbsp.css">

<title> Layout for Controller </title>

</head>

<body class="bspBody1">

<H1>View Example</H1>

<H3>Hello, user <%= name%></H3>

</body>

</html>
6. Activate the view.
7. Finally, adjust the DO_REQUEST method to the controller class.
Here, the schema is always the same. First you create the view, then you set the
attributes, and then you call the view. (For the time being you can ignore the warning
concerning exception CX_STATIC_CHECK, or you can set a try-catch block around
the calls):
method DO_REQUEST .

data: myview type ref to if_bsp_page.

myview = create_view( view_name = 'view_test.htm' ).

myview->set_attribute( name = 'name' value = sy-uname ).

call_view( main_view ).

endmethod.
8. Activate your class and test your controller.

Result

You have created your own view for the layout.


Continue by Calling the Controller.

Calling a Controller
Use
You can call a controller from a page with flow logic, or from a view.

Procedure
1. Create a page within your BSP application.

Ensure that you select Page with Flow Logic as the page type.

2. In the Tag Browser, select BSP extension bsp and drag it to the second line of your
BSP’s layout under the page directive.
3. Now drag the <bsp:goto> directive of BSP extension bsp to the body of the HTML
layout and add the URL parameter.

The source now looks as follows:

<%@page language="abap"%>

<%@ extension name="bsp" prefix="bsp" %>

<html>

<head>
<link rel="stylesheet" href="../../sap/public/bc/bsp/styles/sapbsp.css">
<title> Initial page </title>
</head>

<body class="bspBody1">
<bsp:goto url="example.do"></bsp:goto>
</body>

</html>

4. You can now activate and test the page.

The page looks as follows:


Ensure that the page you have tested looks exactly the same as when you tested the
controller. The URL is different, however. You can use View Source in the browser to
see that nothing remains of the HTML text from the BSP, but that only the content of
the view is displayed:

<html>

<head>

<link rel="stylesheet" href="../../sap/public/bc/bsp/styles/sapbsp.css">

<title> Layout for Controller </title>

</head>

<body class="bspBody1">

</head>

<body class="bspBody1">

<H1>View Example</H1>

<H3>Hello, User GREBEL</H3>

</body>

</html>

5. You can now try out the difference between the <bsp:goto> element and the
<bsp:call> element.
If you use the <bsp:call> element instead of the <bsp:goto> element, the calling
page text remains the same. In the view that is inserted, you should therefore delete
the HTML text available on the outline page, otherwise these texts will be transferred
twice.

6. You can add another attribute to the controller. This is a public class attribute.

It is set using the <bsp:parameter> element. You can use it for example to control
which view is called, or this value can be passed to the view.

Online Bookshop
The BSP application that you create in these tutorials is an online bookshop. The first page
(entry page) of the bookshop should look like this:
In this application you will learn to create BSPs as page fragments and to include them in
other BSPs using include statements. This ensures that all the headers in your BSPs are
identical. You will also learn to work with ABAP methods for data retrieval. The methods used
here are part of the package SBOOKSHOP, which is described in the section Data Model.

You can do the following from the first page:

• Go to the catalog from the second tutorial


• Search for a book
• Call up information about the bookshop

To go to the catalog, choose the link catalog (from last tutorial):


This takes you to the list of authors from the second tutorial:

To search for a book, the user chooses the link search book:

On the following page, criteria can be specified:


If the user searches for the author "Keller", the results list shown below appears. Note that
this search is an OR search. The user can also search by title, publisher, keyword, or ISBN
number. If the user enters an invalid ISBN number, an error message appears.
To get detailed information on a book, click on the book title:
You can now choose to order this book.
For general information about this tutorial, choose about.

The following information page appears:


The method for processing this BSP application is described in
section Processing Procedure.
For information on the data model in the SAP System, see the
section Data Structures.
For background information about the structure and functions of BSP
Applications see What Is a BSP Application?.

Go to Processing Procedure, to Data Structures, or to Creating BSP Applications and


Pages.

Processing Process
The internal structure illustrated below underlies the BSP application with the interface just
described:
The arrows represent navigation paths between the pages.

For information on the data model in the SAP System, see section Data Structures.

For information on "clean" and efficient programming, see the section Separation of Data
Retrieval, Evaluation, and Output.

Now you can get started with creating your BSP application.

Get started!

Separation of Data Retrieval, Evaluation, and


Output
To give the BSP application a clear and transparent structure, it makes sense to store logical
and functional elements in Event Handlers (these contain only program code). In the HTML-
based layout part, dynamic scripting code should only be used to display data on the page in
question.

In this tutorial, the book search facility demonstrates the advantages of clearly separating
data retrieval, evaluation, and output:

• The page attributes for the results page are set in the OnInputProcessing of the
search page. If nothing was input, the results page should not be opened.

• In the initialization part (OnInitialization) of the results page results.htm, the


method search_book is called to search for book titles that match the criteria
entered. If an invalid ISBN is entered, the page invalid_isbn.htm opens. If
another type of error occurs, the error page opens. If no errors occur, the titles of the
books found are written to the internal table bookcat_tab.

• The layout part, then, simply checks whether or not this table is empty. If it is empty,
this means that no matching entries were found. If the table is not empty, the results
are output in a HTML table.

This ensures that functionality and logic (error handling) are kept out of the layout part.

Data Model for the Bookshop Tutorials


The data model described here in the basis of the bookshop tutorials.

In the package SBOOKSHOP in your system, you will find the following database tables and
other objects used in the tutorials. Only the most important objects are listed here. For a
complete list, see the Object Navigator in your system.

Database Tables
SBOOKSHOP contains the following database tables:

Table Name Key Fields Other Fields Meaning

BSAUTHORS MANDT AUTHFNAM In addition to the client


for each book, this
ISBN AUTHLNAM table also contains the
ISBN and the first and
last names of the
AUTHFNAME
author, written once in
standard case and
AUTHLNAME once in upper case.

BSBOOK MANDT TITLE This table contains the


titles of the books
ISBN SUBTITLE available in the
bookshop.
ISBN and client are the
key fields.
SERIES The other fields are
title, sub-title, book
series, publisher, year
PUBLISHER
of publication, number
of pages, the
PUBLYEAR recommended retail
price, the currency
BOOKPAGES (euro), and the country
code.
PRICE_RAW

CURRENCY

COUNTRY

BSCATALOG MANDT CURRENCY This table represents


the book catalog.
CATA_ID OUR_PRICE Each book has a
unique number, the
CATA_ID. The
ISBN DELIVERY
CATA_ID and the
ISBN number are the
COVER_URL
key fields for this table.

The other fields are


currency (euro), price
in our shop, expected
delivery time, and the
URL of a picture of the
book cover.

BSCUSTOMER MANDT TITLE This is the customer


table. All customer
CUSTOMERID SURNAME data is stored here.
The customer’s e-mail
address (this must be
FIRSTNAME
unique) and the client
are used as the key
COMPANY field.
The other fields are
STREET title, first name and
surname of the
ZIP customer, customer
address (street,
CITY postcode, city, and
country), details of any
discount arrangement
COUNTRY
with the customer, and
the customer’s
DISCOUNT password.

USRPWD

BSKEYWORD MANDT In addition to the client


this table contains a
keyword for an ISBN.
ISBN

KEYWORD

BSORDER MANDT ORDERDATE This table contains all


the orders.
CUSTOMER AMOUNT The key fields are the
client, the customer ID
(that is, the e-mail
ORDER_ID STATUS
address), the order ID
(assigned when the
ISBN order is placed), and
the ISBN.
Other fields are the
date of the order, the
number of books
ordered, and the order
status.

BSTEXTS MANDT ISBN This is the table for


long texts in the
RELID TEXT_TYPE bookshop.
The key fields are the
client, the area in the
SRTFD REVIEW_NO
import/export data
table, the user-defined
SRTF2 INPUTDATE key part of the table
INDX, and the next
CLUSTR record counter in the
import/export data
CLUSTD table.

The other fields are


ISBN, the type of a
long text in the
bookshop, an internal
field, the date, a field
length for user data,
and a database field
for the
IMPORT/EXPORT
tables.

Classes and Methods


The bookshop has the class CL_BOOK_SHOP. This class includes the following methods:

Method Parameter Description

SEARCH_BOOK Book search

TITLE Book title


AUTHOR Surname of author

PUBLISHER Publisher

KEYWORD Key words

ISBN ISBN

ISBN_TAB Table of ISBNs

GET_BOOK_DATA Reading the book table

ISBN_TAB Table of ISBNs

BOOKCAT_TAB Table of books

MAINTENANCE_SCREEN Input and output of book data


on the screen

NEW_ENTRY Indicator

ISBN ISBN

GET_ITEM Reading a catalog entry

CAT_ID Bookshop index

BOOK_DATA Structure for transferring all


relevant data for a book

CHECK_ISBN ISBN check

ISBN ISBN

Flag Indicator

Symbol Meaning

Import parameter

Export parameter

Return parameter

Creating Page Fragments


Use
Page fragments help ensure that the appearance of your Web application is consistent.
Similarly to frames, you can use page fragments to implement the same layout for different
parts of your page. In this tutorial, you will use a page fragment to implement a consistent
header for all BSPs in your BSP application. You simply include the page fragment in all your
BSPs.

Procedure
Take the following steps to create a page fragment for your BSP application:

1. In the Web Application Builder, open your application (tutorial_3), position your
cursor on the highest-level hierarchy node in the left-hand navigation tree, and, using
the right mouse button, choose Create → Page .
2. In the popup that appears, enter a meaningful name (the system will propose the
extension .htm) and a description, and select the page type Page Fragment.

3. Choose .
4. Create the code for your page fragment.

<%@ page language="abap" %>

<html>

<head>
<title>mySAP Bookshop</title>
</head>

<body BGCOLOR="#B5E1D2" >

<h2> <img height="80" width="80" src="book2.jpg"> &nbsp;&nbsp;mySAP


Bookshop
</h2>

<hr>
5.
6. Make sure that you do not include the end tags </body> and </html> in this code,
as this is a page fragment, and page fragments are always located at the beginning
of the HTML page. Correspondingly, page that include the fragment head.htm have
no start tags, only end tags.
7. This ensures that the headers that are included in every BSP by means of the steps
outlined below always look the same:

8.
9. This also sets the background color for the whole page.
10. Choose .

Result
In the Web Application Builder your entire BSP application with the pages, images, and page
fragment are displayed:
Layout for the First Page

Layout for the First Page


The layout for the first page (default.htm), which you set using the tab page Layout, looks
like this:

<%@ page language="abap" %>


<%@ include file="head.htm" %>

<h3> Welcome to our small bookshop! </h3>

It offers the following small features:


<p>

<a href="../tutorial_2/results.htm">catalogue (from last tutorial)</a><br>

<p>

<a href="search.htm">search book</a><br>

<p>

<a href="about.htm">about</a><br>

</body>

</html>

This code uses HTML to create three links, and uses the include directive (see below). The
first link links to the list of authors, which you created in the previous tutorial (see A Simple
BSP Application). The second link links to the search page, and the third link links to an
information page.

The Include Directive


In the code for this page, the following line comes after the page directive:

<%@ include file="head.htm" %>

This directive includes the page fragment head.htm in the page default.htm. This has the
effect that the first page gets the header defined in head.htm.

The syntax of the page directive is as follows:

<%@ include file="relative URL" %>

The include directive includes existing pages and page fragments in the BSP. Make sure
that you always use a relative URL when specifying the page to be included.

If you view the page default.htm in the browser and choose View
Source, you will see that the HTML code simply consists of
head.htm and default.htm.
Layout for the Info Page

Layout for the Info Page


The layout for the information page about.htm, which you set using the tab page Layout,
looks like this:

<%@ page language="abap" %>

<%@ include file="head.htm" %>

<p>

<img height="100" src="blind.gif">

<table>
<tr><td> <h3>Demo bookshop for BSP tutorial</h3></td></tr>
<tr><td> <h4> &copy; by SAP AG 2000.</h4></td></tr>
<tr><td> <img height="10" src="blind.gif"></td></tr>
</table>

</body>

</html>

The page fragment head.htm is also included in this page.

Layout for the Search Page

Layout for the Results Page


The layout for the page results.htm, which you set using the tab page Layout, looks like
this:

<%@ page language="abap" %>

<%@ include file="head.htm" %>

<% IF bookcat_tab IS INITIAL. %>

No books were found to match your query.


<p>
<a href="search.htm">Go back to the search form</a>

<% ELSE. %>

<table width="590" cellpadding="3">


<tr> <td><b> Title </td>
<td><b> Author(s) </td>
<td><b> Delivery </td>
<td><b> Our Price </td>
</tr>

<% DATA bookcat TYPE bsbookdata.

LOOP AT bookcat_tab INTO bookcat. %>

<tr>

<td><a href="showbook.htm?s_cata_id=<%= bookcat-cata_id %>">

<%= bookcat-title %><br><small><%= bookcat-subtitle


%></small></a></td>
<td><small><% DATA author_wa TYPE bsauthors.

LOOP AT bookcat-authors INTO author_wa. %>

<%=author_wa-authfname %>&nbsp;<%=author_wa-authlname %>

<% ENDLOOP. %>

</small></td>

<td><%= bookcat-delivery %></td>


<td><%= bookcat-our_price %><%= bookcat-catal_curr %></td>
</tr>

<% ENDLOOP. %>

</table>

<% ENDIF. %>

</body>

</html>

The page fragment head.htm is also included in this page.

First, this code checks whether there are any entries in the structure bookcat_tab that
match the search criteria. If there are not, an error message is output. The user can then click
on a link on the error page to return to the search page.

If there are matching entries in the bookcat_tab structure, the results are output in a four-
column table.

The output is then processed in detail:

A loop statement writes the content of the internal table bookcat_tab line by line into a
help variable. When this happens, the title and sub-title for each book are stored along with a
link. The variable ?s_cata_id is included in the link after the page details.

<a href="showbook.htm?s_cata_id=<%= bookcat-cata_id %>">

Next, the first name and surname of the author, the delivery time, and the price are retrieved,
and all this data is written to the table. The variable s_cata_id contains the unique ID
number of a book in the catalog. This ID number is the primary key of the database table
bscatalog in the SAP System (see Data Model).

Attributes for the Results Page


Page Attributes for the Results Page
Use the tab page Page Attributes to define the required page attributes for the results page
(results.htm).

These attributes are the fields that are used to search on the search page. They also
correspond to the import parameters of the method search_book in the SAP System (see
also Data Model). These attributes are flagged as automatic, as they were set using
navigation->set_parameter on the search page, and now variables of the same name
are being used again. There is also the page attribute bookcat_tab. This is the table in the
Data Dictionary that contains the book and catalog data for the tutorials. This table is not
flagged as an automatic page attribute, as it is being used for the first time.

Auto page attributes can have various data types, structures or tables
but no references.

Event Handlers for the Results List

Event Handlers for the Results Page


Two event handlers are required for the processing procedure of the results page
(results.htm), OnInitialization and OnInputProcessing.

OnInitialization
data: isbn_tab TYPE isbn_tab.

CALL METHOD cl_book_shop=>search_book


EXPORTING
author = author
title = title
publisher = publisher
ISBN = ISBN
keyword = keyword
IMPORTING isbn_tab = isbn_tab
EXCEPTIONS
no_search_parameter = 2
invalid_isbn = 4.

if sy-subrc = 4.
navigation->goto_page( 'invalid_isbn.htm' ).
elseif sy-subrc <> 0.
navigation->goto_page( 'error.htm' ).
endif.

IF sy-subrc = 0.
CALL METHOD cl_book_shop=>get_book_data
EXPORTING
isbn_tab = isbn_tab
IMPORTING
bookcat_tab = bookcat_tab
EXCEPTIONS
empty_input_table = 2
invalid_isbn = 4.
ENDIF.

The data statement sets the data transfer for the ISBN table.

The method search_book of the class cl_book_shop is used to search for book titles that
match the user input. When this happens, the method search_book gets the page
parameters author, title, publisher, isbn and keyword, and the parameter
isbn_tab is returned with the results of the search. The following exceptions or errors are
defined in search_book:

• There are no search parameters, that is, the user input fields are empty (sy-
subrc=2).

This scenario is already taken care of by OnInputProcessing on the search


page. Therefore, it cannot occur here.

• The specified ISBN does not correspond to the conventions (sy-subrc=4).

In this case, the ISBN error page (invalid_isbn.htm) is called.

• An internal error occurs (sy-subrc<>0).

In this case, the general error page (error.htm) is called.


If no errors occur, the method get_book_data of the class cl_book_shop is called, which
finds suitable results. Sometimes, no suitable results are found, that is, isbn_tab is empty.
In this case, get_book_data returns sy-subrc = 2, and the table bookcat_tab is empty.
The layout part checks for this scenario.
OnInputProcessing
navigation->set_parameter( 's_cata_id' ).
Based on the user input, the book page is opened for the book with the s_cata_id that was
specified in the layout with the statement below:
<a href="showbook.htm?s_cata_id=<%= bookcat-cata_id %>">

Layout for the Book Page

Navigation Structure
In our example, the navigation structure is important mainly for the search function.
When the user enters search criteria on the search page (search.htm), a
corresponding results list (results.htm) is output. The navigation request
TORESULTS controls the navigation procedure that opens the results page.
When the user orders a book on the page showing detailed information on individual
books (showbook.htm), the page containing a confirmation of the order
(corder.htm) is displayed. The navigation request TOORDER controls this
navigation procedure.
The navigation structure for your BSP application, which you set using the tab page
Navigation, looks like this:

You have now created your own online bookshop as a BSP application. Once you
have activated all the BSPs and the BSP application itself, call your application in the
Web browser.
To Be Continued...
In the next tutorial you will extend your online bookshop by adding an online shopping
basket with cookies, and a function for creating new users.
Our Little Online Bookshop Using MVC and
HTMLB
Purpose
In this tutorial we create the same online bookshop as in Tutorial 3 ( Our First Online
Bookshop) but this time using MVC and HTMLB.

Introductory Comments
This has the advantage over the previous BSP application that you have several
components on one page, where each component is represented by a controller and a
view.
You should do this tutorial if you are used to creating BSP applications (ideally once
you have completed all of the tutorials) and you want to use MVC and HTMLB to
create your applications. You should also have already completed the short Model
View Controller Tutorial.

Integration
Each tutorial builds on the information presented in the previous one.
You can also read the reference documentation on the SAP Web AS Architecture,
which explains the system’s architecture and components:
You can find documentation about the MVC Design Pattern in Model View
Controller (MVC).
You can find documentation on BSP extension HTMLB in the system: you can
display detailed documentation for each HTMLB element in the Tag browser of the
Web Application Builder.
Features
In this tutorial you will learn how to:
• Recognize HTMLB elements TableView, Button, Tray, Group and so on.
• How to create a page (view) that calls several sub-controllers
• How you implement event handling with MVC
• How you can control the rendering of individual cells in a table
Section Bookshop Structure describes how you set up the BSP application to be
created.
See Creating BSP Applications, Controllers and Views for the exact procedure.
Constraints
This model does not explain the use of models; for this comparatively simple
application you need controllers and views only.
The tutorial ends without any defined error pages. You can find information about
using and creating error pages in the MVC documentation in Creating Error Pages.

Bookshop Structure
Unlike the online bookshop without MVC, this bookshop is structured so that book searches,
results lists and the detailed displays are summarized on one page.

You can use this to clearly show how the MVC programming model "thinks".

If you call the URL hidden behind the main controller in the browser, the following page is
displayed:
Tha main controller bookshop.do calls view default.htm.

This contains a page fragment, which represents the bookshop header (like Tutorial 3 but with
HTMLB), as well as 3 HTMLB trays, which call the corresponding controllers.
The following graphic highlights the structure.

The URL is recognized by the SAP Web AS as a BSP application and is processed by the
BSP runtime. This calls main controller bookshop.do up first, that is, method DO_REQUEST
for the corresponding controller class is executed. This then calls the main view
default.htm, which in turn uses <bsp:call> element within HTMLB trays to call sub-
controllers search.do, result.do and detail.do. These sub-controllers have views that
they call.

You can now get going with the implementation!

Creating BSP Applications, Controllers and Views

Creating BSP Applications, Controllers and


Views
In the Web Application Builder, create the following:

• A BSP application

We have chosen tutorial_3 as the name. This is a sample BSP


application contained in package SBOOKSHOP. Pay attention to the customer
namespaces when you are naming your BSP application.
Select your BSP application (Properties tabstrip) as Stateful. This is
recommended when you work with sub-controllers (see Bookshop Structure),
because the main controller must recognize all sub-controllers when it
delegates the data. It must also be instantiated.

If you want to program the application as stateless, you must create


sub-controllers in the DO_INIT method of that controller. You can
find additional information about this in Stateful and Stateless.

• Next controller

bookshop.do. This is the main controller that is also called using the URL
by the browser. Method ON_REQUEST of the controller class of this controller
is executed first of all. This calls the view default.htm. Creating Main
Controller bookshop.do describes how you create this controller.
search.do. This is the controller that is responsible for the book search. It
must react to the searchbutton, process the book data that are entered,
search for suitable books and then write these to an internal table. It then
passes this table to view search.htm. Creating Controller search.do for the
Search describes how you create this controller.
result.do. This controller is responsible for outputting the books that are
found as well as for event handling when a user clicks on a book to display
detailed data about that book. Individual rendering of the author column must
also be determined. Creating Controller result.do for the Results Page
describes how you create this controller.
detail.do. This controller is responsible for determining the detailed data
for a selected book. It then passes this table to view detail.htm. Creating
Controller search.do for the Detail Display describes how you create this
controller.

• Following views

default.htm. This is the main view that consists of the header and 3
HTMLB trays, which contain the search-, result- and detail controllers
and the corresponding views. Creating Main View default.htm describes how
you create this view.
search.htm. Creating View search.htm for the Search describes how you
create the view for inputting the search data.
result.htm. Creating View result.htm for the Results List describes the
view for displaying the results list with an HTMLB table view.
detail.htm. This view returns details on a book selected in the results
table. Creating View detail.htm for the Details Display describes how you
create the view.
about.htm. If no books were found in the search or the results table is
empty for another reason, information about the bookshop should be
displayed instead of the book details. Create the view as described in
Creating View about.htm for the Detail Display.

• Page fragment head.htm, which is included in main view default.htm. Creating


Page Fragment head.htm describes how you create this with HTMLB.
• A page with flow logic corder.htm. You can navigate to this from the detail.do
controller. Like Our First Online Bookshop, you navigate to this page if you want to
order a book. Creating Page with Flow Logic corder.htm describes how you create
the page.
Further Developing the Online Bookshop
Purpose
Welcome to the fourth tutorial! In this tutorial, you will further develop the functions
of the Online Bookshop.
Introductory Comments
Some important functions, such as customer administration and a shopping basket, are
still missing from your online bookshop.
This tutorial shows you how to add these functions to the application. The application
is a stateless one (see Stateful and Stateless Applications), which means that any books
selected by the user remain in the shopping basket, even if the connection is
interrupted. For example, if the customer is in the middle of ordering a book, goes to
visit another site, and then comes back to the bookshop, all the details of the order are
still there, thanks to a cookie on the client side which retains the relevant information.
The new bookshop functionality is described under What’s New?.
Integration
Each tutorial builds on the information presented in the previous one. This tutorial
requires the Online Bookshop (or Our Little Online Bookshop Using MVC and HTMLB)
from Tutorial 3.

You can also read the reference documentation on the SAP Web AS
Architecture, which explains the system’s architecture and components:
Features
In this tutorial you will learn how to:
• Use an application class (CL_BSP_TUTORIAL)
• Check user input and write it to the database
• Set cookies on the client side to store information in a stateless application
• Use caching functions
• Use the messages object
• Use the Online Text Repository (OTR)

Let’s get started!

What’s New?
In this tutorial, the online bookshop that you created in the last tutorial (Online Bookshop) will
be extended to include the following functions and BSPs:

• The page newuser.htm is used to register new customers. New customer data is
stored in the customer table BSCUSTOMER. The page cnewuser.htm shows the
customer that the registration has been successfully completed. For subsequent
orders, the customer simply logs on on the page order.htm using his or her user ID
(e-mail address) and password.
• The page basket.htm is the most important addition. This page displays the current
status of the shopping basket. The user can delete entries and modify the quantity of
an item. If the connection is terminated and then re-opened, the current status of the
shopping basket can be regenerated using a cookie.
• Initally, you will use the application class CL_BSP_TUTORIAL to implement the above
functionality. This class contains the methods for maintaining the shopping basket.
• Caching is used with the results page results.htm.
• Error messages that are output in the case of incorrect user information are
implemented using the messages object. Error pages error.htm and
invalid_isbn.htm, which are available in the third tutorial, are not used as a
result.
• Some of the error messages have been declared as online text repository texts as an
example. OTR texts have the advantage that they are connected to the SAP
translation system.

The ways in which the online bookshop can be extended are described in the section
Extending the Online Bookshop.

Extending the Online Bookshop


In this section, you will extend the first page of the Online Bookshop by adding one line to the
header page fragment. This line enables the user to go to the standard pages (Search,
Create New User, Shopping Basket, and About) from any page.
Users use these pages to do the following:

• Go to the search page


• Create a new user, that is, register themselves
• Display the current shopping basket
• Display the information page (about.htm)

The search function and the detailed book data display are transferred from the Online
Bookshop.
The user registration function is also new:
On this page, the customer (user) enters his or her name, address, company, and password.
When the user clicks the done button, the data is checked for completeness and for identical
passwords, and is then entered in the database table BSCUSTOMER.
If the registration is successful, the following page appears:
The next time this user wants to place an order, he or she only needs to enter his or her e-
mail address and password.
Adding an administration function for the shopping basket is another way of further extending
the functionality of the Online Bookshop. When the shopping basket is empty, the page
basket.htm looks like this:

If you search for a book, select it, and place it in the shopping basket, the shopping basket
then looks like this:
On this page, the user can change the number of books, remove items from the basket, and
update the basket.
Once the user has completed the order, he or she chooses Order Basket to place the order.
The following page appears:
On this page, the user enters his or her e-mail and password to authenticate the login. If the
user is not yet a registered customer, he or she can also register on this page.
If the e-mail address and password entered are correct, this activates the order. The page
corder.htm opens.
This completes this addition to the bookshop.
In the next step, you will learn how to trigger the ordering process, for example, by means of a
BAPI. The BAPI in turn triggers the creation of an invoice, the deletion of a book from the
bookshop, and the delivery of an item.

The method for processing this BSP application is described in


section Processing Procedure.
For information on the data model in the SAP System, see the
section Data Structures.

Go to Processing Procedure, to Data Structures, or to Creating BSP Applications and


Pages.

Creating BSP Applications and Pages


Prerequisites
You have implemented the Online Bookshop as a BSP application.

Procedure
Make a copy of the existing BSP application to a new one, with a freely definable name in the
customer namespace. In our example, we used tutorial_4. To do this, go to the Web
Application Builder and open the BSP application tutorial_3. Right-click on the BSP
application and choose Copy.

In the popup that appears, enter ‘tutorial_4’ in the field Target Application.

In the field Target Application, enter the name of your new BSP application.

Now create from scratch the following BSPs:

Page Name Meaning

basket.htm Shopping Basket Page

This page implements the shopping basket function. The user is taken to
this page when he or she places a book in the basket, or modifies the
contents of the basket.

order.htm Order Page

The user is taken to this page when he or she wants to order the current
contents of the shopping basket. At this stage, the user has to authenticate
himself or herself, otherwise the ordering process cannot continue.

newuser.htm Registration Page

This page is used to register new customers. The customers enter their e-
mail address to identify themselves.

cnewuser.htm Registration Confirmation Page

This page confirms that a new customer has registered successfully. The
customer’s data is stored in the database table BSCUSTOMER of the
package in question (see Data Model for the Bookshop Tutorials).

Some existing pages and page fragments must be changed.

These modifications are described in the following sections:


Modifying the Title Bar head.htm

Modifying the Order Confirmation Page corder.htm

Modifying the Entry Page default.htm

Modifying the Results Page results.htm

Modifying the Search Page search.htm

Вам также может понравиться