This document was uploaded by user and they confirmed that they have the permission to share
it. If you are author or own the copyright of this book, please report to us by using this DMCA
report form. Report DMCA
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.
Advanced
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: • • • • • •
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'. %> [ test line ] [ before <%= s%> middle <%= s%> end. ] [<%= 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'. %> [ test line ] [ before <%= s%> middle <%= s%> end. ] [<%= 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.
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: HTML text, can also contain scripting code 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="" prefix=""%> 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: • • • • • • • •
This is described in more detail below. The objects and their signatures for the individual event handlers are displayed if you choose Example:
in the Web Application Builder.
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.
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-
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
Cross References
See also: add_message
Number of currently existing messages
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.
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 email 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.
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>/’
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 navigation.
object
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 toplevel 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 View Controller design pattern for BSP.
Model
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 7.
symbol to branch to the change mode in your class.
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( '
' ). write( 'This is my very first controller' ). write( '
' ). 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. 4.
Choose . 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" %> Layout for Controller
View Example
Hello, user <%= name%>
6. 7.
Activate the view. 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. 4.
Choose . 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" %>
href="../../sap/public/bc/bsp/styles/sapbsp.css"> Layout for Controller
View Example
Hello, user <%= name%>
6. 7.
Activate the view. 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 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" %> Initial page 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: Layout for Controller
View Example
Hello, User GREBEL
5. You can now try out the difference between the element and the element.
If you use the element instead of the 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 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 For general information about this tutorial, choose about.
The following information page appears:
to order this book.
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 HTMLbased 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
ISBN
AUTHLNAM
In addition to the client for each book, this table also contains the ISBN and the first and last names of the author, written once in standard case and once in upper case.
AUTHFNAME AUTHLNAME BSBOOK
MANDT
TITLE
ISBN
SUBTITLE
This table contains the titles of the books available in the bookshop. ISBN and client are the
SERIES PUBLISHER PUBLYEAR BOOKPAGES
key fields. The other fields are title, sub-title, book series, publisher, year of publication, number of pages, the recommended retail price, the currency (euro), and the country code.
PRICE_RAW CURRENCY COUNTRY BSCATALOG
MANDT
CURRENCY
CATA_ID
OUR_PRICE
ISBN
DELIVERY COVER_URL
This table represents the book catalog. Each book has a unique number, the CATA_ID. The CATA_ID and the ISBN number are the 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
CUSTOMERID
SURNAME FIRSTNAME COMPANY STREET ZIP CITY COUNTRY DISCOUNT
This is the customer table. All customer data is stored here. The customer’s e-mail address (this must be unique) and the client are used as the key field. The other fields are title, first name and surname of the customer, customer address (street, postcode, city, and country), details of any discount arrangement with the customer, and the customer’s password.
USRPWD BSKEYWORD
MANDT
In addition to the client this table contains a keyword for an ISBN.
ISBN KEYWORD BSORDER
MANDT
ORDERDATE
CUSTOMER
AMOUNT
ORDER_ID
STATUS
ISBN
BSTEXTS
MANDT
ISBN
RELID
TEXT_TYPE
SRTFD
REVIEW_NO
SRTF2
INPUTDATE CLUSTR CLUSTD
This table contains all the orders. The key fields are the client, the customer ID (that is, the e-mail address), the order ID (assigned when the order is placed), and the ISBN. Other fields are the date of the order, the number of books ordered, and the order status. This is the table for long texts in the bookshop. The key fields are the client, the area in the import/export data table, the user-defined key part of the table INDX, and the next record counter in the import/export data 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
SEARCH_BOOK
Description 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
Symbol
ISBN check ISBN
ISBN
Flag
Indicator 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 2.
cursor on the highest-level hierarchy node in the left-hand navigation tree, and, using the right mouse button, choose Create → Page . 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" %> mySAP Bookshop
mySAP Bookshop
5.
6. Make sure that you do not include the end tags and 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" %>