Conditional constructions. Java Server Page. JSP page syntax
JSP pages have a combined syntax: a combination of the standard syntax as defined by the HTML specification and the JSP syntax as defined by the specification Java Server Pages. JSP syntax defines the rules for writing JSP pages composed of standard HTML tags and JSP tags.
JSP pages, in addition to HTML tags, contain JSP tags of the following categories:
JSP directives
JSP directives provide global information regarding specific requests sent to the server and provide information needed during the translation stage. Directives are always placed at the beginning of the JSP page before all other tags, so that parser(parser) JSP, when parsing the text, at the very beginning, highlighted the global instructions. Thus, the JSP Engine (JSP runtime) parses the code and creates a servlet from the JSP. Directives are messages to a JSP container.
Syntax JSP directives as follows:
<%@ директива имяАтрибута="значение" %>
Task syntax directives in XML:
JSP directive can have multiple attributes. In this case, the directive can be repeated for each of the attributes. At the same time, couples "AttributeName = value" can be located under one directive with a space as a separator.
There are three types of directives:
- page (page)
- taglib (tag library)
- include (include)
JSP page directive
JSP page directive defines the properties of the JSP page that affect the translator. Order of attributes in a directive page does not matter. Violation of syntax or presence of unrecognized attributes results in a translation error. An example of a directive page the following code can serve:
<%@ page buffer="none" isThreadSafe="yes" errorPage="/error.jsp" %>
The page directive declares that this page JSP does not use buffering, which makes it possible to simultaneously access the given JSP page many users, and that an error page with the name error.jsp.
JSP page directive may contain information about the page:
<%@ page info = "JSP Sample 1" %>
List of possible directive attributes page presented in the table.
Attribute name | Meaning | Description |
---|---|---|
language | Line | Determines the language used in JSP file scriptlets, expressions, or any include files, including the body of translated code. The default is "java" |
extends | Line | Specifies the superclass for the generated servlet. This attribute should be used with great care as it is possible that the server is already using a superclass. |
import | Line | Definition of packages to import, for example: <%@ page import="java.util.* %> |
Session | true or false | Meaning true(default) indicates that a predefined variable session(type HttpSession) must be bound to an existing session, if any, otherwise a new session is created and bound to. Meaning false determines that sessions will not be used, and attempts to access a variable session will result in an error when translating the JSP page to the servlet |
Buffer | none or the size of the buffer in kB. | Sets the buffer size for the JspWriter out. The default value depends on the server settings and should not exceed 8 kB. If the value is none the output goes directly to the object ServletResponse |
autoFlush | true or false | Determines whether the buffer should be emptied automatically when it overflows or an error occurs. The default is true |
isThreadSafe | true or false | Meaning true(the default) specifies the normal execution mode of the servlet, where multiple requests are processed concurrently using a single servlet instance, assuming that the author has synchronized access to the variables of that instance. A false value signals that the servlet should inherit SingleThreadModel(single-threaded model) where sequential or concurrent requests are handled by separate instances of the servlet |
info | Line | Defines a string of information about a JSP page that will be accessed using the method Servlet.getServletInfo () |
errorPage | Line | The attribute value is the URL of the page that should be displayed in case of possible errors that cause exceptions |
isErrorPage | true or false | Signals whether this page can be used to handle errors for other JSP pages. The default is false |
contentType | Line | Specifies the encoding for the JSP page and response, and the MIME type of the JSP response. The default value of the content type is text / html, encodings - ISO-8859-1. For example: contentType = "text / html; charset = ISO-8859-1" |
pageEncoding | Line | Determines the character encoding of the JSP page. The default is charset from attribute contentType if it is defined there. If the value charset in attribute contentType undefined, value pageEncoding is set equal ISO-8859-1 |
JSP taglib directive
JSP directive taglib declares that the given JSP page uses a tag library, uniquely identifies it with a URI, and maps the tag prefix with which the library can be acted upon. If the container cannot find the tag library, a fatal translation error occurs.
Directive taglib has the following syntax:
<%@ taglib uri="URI of the included tag library"prefix =" prefix name" %>
Prefix " prefix name"is used when referring to the library. An example of using the tag library mytags:
<%@ taglib uri="http://www.taglib/mytags" prefix="customs" %>
. . .
In this example, the tag library has a URI "http: //www.taglib/mytags", the string is assigned as a prefix customs that is used in the JSP page when accessing elements of the tag library.
JSP include directive
JSP Directive include allows you to insert text or code while translating a JSP page into a servlet. Directive syntax include looks like this:
<%@ include file="The relative URI of the page to include" %>
Directive include has one attribute - file... It includes the text of the specified resource in the JSP file. This directive can be used to place a standard copyright header on every JSP page:
<%@ include file="copyright.html" %>
The JSP container accesses the include file. If the include file has changed, the container can recompile the JSP page. Directive include treats a resource, such as a JSP page, as a static object.
The given URI is usually interpreted relative to the JSP of the page on which the link is located, but as with any relative URI, you can tell the system the position of the resource of interest relative to the home directory of the WEB server by prefixing the URI with a "/" character. The content of the include file is treated as plain JSP text and therefore can include elements such as static HTML, script elements, directives, and actions.
Many sites use a small navigation bar on every page. Due to the problems of using HTML frames, this task is often solved by placing a small table on top or in the left half of the page, the HTML code of which is repeated many times for each page of the site. Directive include- this is the most natural way to solve this problem, saving the developer from the nightmare of the routine of copying HTML into each separate file.
Since the directive include includes files during page translation, then after making changes to the navigation bar, re-translation of all JSP pages using it is required. If the attached files change quite often, you can use the action jsp: include that connects the file when accessing the JSP page.
JSP declarations directive
JSP directive declarations are intended to define variables and methods in the scripting language, which are later used in the JSP page. Syntax declarations looks like this:
<%! код Java %>
declarations are located in the declaration block and are called in the expression block of the JSP page. The code in the declaration block is usually written in Java, but application servers can use the syntax of other scripts. ads are sometimes used to add additional functionality when working with dynamic data obtained from properties of JavaBeans components. Examples of ads are presented in the table.
Declarations can contain multiple lines, such as in the below code for calculating the value of a function fact (int n), which should be equal to 1 when n is less than 2 and n! with a positive value of n;
<%! public static int fact (int n) { if (n <= 1) return 1; else return n * fact (n - 1); } %>
declarations do not produce any output to standard output out... Variables and methods declared in declarations are initialized and made available to scriptlets and others ads at the time the JSP page is initialized.
Scriptlets scriptlets
scriptlets include various pieces of code written in the scripting language defined in the directive language... Code snippets must comply with the syntactic constructs of the language scriptlets, i.e., usually the syntax of the Java language. scriptlets have the following syntax:
<% текст скриптлета %>
Syntax equivalent scriptlet for XML is:
If in the text scriptlet it is necessary to use the sequence of characters%> exactly as a combination of characters, and not as a tag - an end sign scriptlet, instead of the sequence%>, use the following combination of characters% \>.
The JSP specification provides a simple and straightforward example scriptlet that dynamically changes the content of the JSP page throughout the day.
<% if (Calendar.getInstance ().get (Calendar.AM_PM) == Calendar.AM) {%>Good morning<% } else { %>Good Afternoon<% } %>
It should be noted that the code inside scriptlet inserted as written and all static HTML text (template text) before or after scriptlet converted using the operator print... This means that scriptlets do not have to contain completed Java chunks, and that chunks left open can affect static HTML outside of scriptlet.
Scripts have access to the same auto-defined variables as expressions. Therefore, for example, if there is a need to display any information on the page, you must use the variable out.
<% String queryData = request.getQueryString (); out.println ("Дополнительные данные запроса: " + queryData); %>
Expressions expressions
Expressions expressions in a JSP page, an executable expression written in the scripting language specified in the language declaration (typically Java). Result expressions JSP, which is of the required type String, is sent to the standard output stream out using the current object JspWriter... If the result is expressions cannot be cast String, either a translation error occurs if the problem was detected at the translation stage, or an exception is thrown ClassCastException if the inconsistency was detected during the execution of the request. Expression has the following syntax:
<%= текст выражения %>
alternative syntax for JSP expressions when using XML:
Execution order expressions on the JSP page from left to right. If expression appears in more than one run-time attribute, then it runs from left to right in that tag. Expression must be a complete expression in a specific script (typically Java).
expressions are executed while the HTTP protocol is running. The expression value is converted to a string and included in the appropriate position in the JSP file.
Expressions are commonly used to compute and display the string representation of variables and methods defined in a JSP page declaration block or derived from JavaBeans that are accessible from a JSP. The following code expressions serves to display the date and time of the page request:
Current time:<%= new java.util.Date () %>
In order to simplify expressions there are several predefined variables that you can use. The most commonly used variables are:
- request, HttpServletRequest;
- response, HttpServletResponse;
- session, HttpSession - associated with the request, if any;
- out, PrintWriter - a buffered version of the JspWriter type for sending data to the client.
One of the fundamental elements of many programming languages is conditional constructions... These constructions allow you to direct the work of the program along one of the paths, depending on certain conditions.
The Java language uses the following conditionals: if..else and switch..case
If / else construct
The if / else expression checks the truth of a certain condition and, depending on the results of the test, executes a certain code:
Int num1 = 6; int num2 = 4; if (num1> num2) (System.out.println ("The first number is greater than the second");)
A condition is placed after the if keyword. And if this condition is met, then the code that is placed further in the if block after the curly braces is triggered. The operation of comparing two numbers acts as a condition.
Since, in this case, the first number is greater than the second, the expression num1> num2 is true and returns true. Consequently, control passes into the block of code after the curly braces and starts executing the instructions contained there, specifically the System.out.println method ("The first number is greater than the second"); ... If the first number were less than or equal to the second, then the statements in the if block would not be executed.
But what if we want some action to be taken if the condition is not met? In this case, we can add an else block:
Int num1 = 6; int num2 = 4; if (num1> num2) (System.out.println ("The first number is greater than the second");) else (System.out.println ("The first number is less than the second");
Int num1 = 6; int num2 = 8; if (num1> num2) (System.out.println ("The first number is greater than the second");) else if (num1 We can also combine several conditions at once using logical operators: Int num1 = 8; int num2 = 6; if (num1> num2 && num1> 7) (System.out.println ("The first number is greater than the second and greater than 7");) Here the if block will be executed if num1> num2 is true and at the same time num1> 7 is true. Design switch / case is similar to the if / else construction, since it allows you to process several conditions at once: Int num = 8; switch (num) (case 1: System.out.println ("number is 1"); break; case 8: System.out.println ("number is 8"); num ++; break; case 9: System.out. println ("number is 9"); break; default: System.out.println ("number is not 1, 8, 9");) The expression to be compared follows the switch keyword in parentheses. The value of this expression is sequentially compared with the values after the case operator. And if a match is found, then a specific case block will be executed. A break statement is placed at the end of a case block to avoid execution of other blocks. For example, if the break statement were removed in the following case: Case 8: System.out.println ("number is 8"); num ++; case 9: System.out.println ("number is 9"); break; then since our variable num is equal to 8, then the case 8 block would be executed, but since in this block the num variable is increased by one, there is no break statement, then the case 9 block would start executing. If we also want to handle the situation when no match is found, then we can add a default block, as in the example above. The default block is optional though. Starting with JDK 7, in the switch..case expression, in addition to primitive types, you can also use the strings: Package firstapp; import java.util.Scanner; public class FirstApp (public static void main (String args) (Scanner in = new Scanner (System.in); System.out.println ("Enter Y or N:"); String input = in.nextLine (); switch ( input) (case "Y": System.out.println ("You pressed the letter Y"); break; case "N": System.out.println ("You pressed the letter N"); break; default: System.out .println ("You pressed an unknown letter");))) The ternary operation has the following syntax: [first operand is a condition]? [second operand]: [third operand]. Thus, three operands are involved in this operation at once. Depending on the condition, the ternary operation returns the second or third operand: if the condition is true, then the second operand is returned; if the condition is false, then the third. For example: Int x = 3; int y = 2; int z = x Here, the result of the ternary operation is the variable z. First, the condition x When we look at a java program, it can be defined as a collection of objects that interact by calling each other's methods. Now let us briefly understand Java syntax what does class, object, methods and instance variables mean. An object- objects have state and behavior. For example: a dog can have a state - color, name, as well as behavior - nod, run, bark, eat. An object is an instance of a class. Class- can be defined as a template that describes the behavior of an object. Method- is primarily a behavior. A class can contain multiple methods. It is in methods that logically recorded data is manipulated and performed. Instance variables- each object has its own unique set of instance variables. The state of the object is generated by the values assigned to these instance variables. Let's take a look at a simple code that will display the words "Hello world!" And, for one, the Java syntax. Public class MyFirstJavaProgram (public static void main (String args) (/ * This is my first java program. Execution will display "Hello world!" * / System.out.println ("Hello world!"); / / Displaying a message on the screen)) It is very important to know and remember the following points in the syntax: Identifiers- the names used for classes, variables and methods. All Java components require names. There are several rules in Java syntax to remember about an identifier. They are as follows: Enumerations were introduced in Java 5.0. They constrain the variable to select only one of several predefined values. The values in this enumerated list are called transfers. By using enumeration in Java, you can reduce the number of errors in your code. For example, if you were looking at orders for fresh juice in a store, you could limit the size of the juice pack for small, medium, and large. This makes it possible to use enumeration in Java so that no one orders any other package size other than small, medium, or large. The resulting output from the above example: Size: MEDIUM Note: in Java, enums can be declared either independently or within a class. Methods, variables, constructors can also be defined inside an enumeration. As with other languages, in Java you can modify classes, methods, and so on using modifiers. Modifiers in Java fall into two categories: We'll take a closer look at class modifiers, method modifiers, and others in the next section. In Java, an array is an object that stores multiple variables of the same type. However, the array itself is an object. We'll look at how to create and populate an array in later chapters. must necessarily match the name of the class whose main () method is called when the Java machine is started. A Java source file is a text file that contains one or more class definitions. The Java translator assumes First of all, in this chapter we will write, translate, and run the canonical “Hello World” program. After that, we will look at all the essential lexical elements perceived by the Java translator: spaces, comments, keywords, identifiers, literals, operators, and delimiters. By the end of this chapter, you will have enough information to be able to navigate a good Java program on your own. So here is your first Java program class HelloWorld ( System. out. println ("Hello World"); In order to work with the examples given in the book, you need to get over the network from Sun Microsystems and install the Java Developers Kit - a package for developing Java applications ( The Java language requires all program code to be contained within named classes. The above example text should be written to the HelloWorld.java file. Be sure to check that the uppercase letters in the file name match the same in the name of the class it contains. In order to translate this example, you need to start the Java translator - javac, specifying the name of the file with the source text as a parameter: The translator will create a HelloWorld.class file with the processor-independent bytecode for our example. In order to execute the resulting code, you must have a Java runtime environment (in our case, a java program), into which a new class must be loaded for execution. We emphasize that the name of the class is specified, and not the name of the file in which this class is contained. Little has been done, but we have verified that the installed Java translator and runtime work. Step by step class HelloWorld ( This line uses a reserved word public static void main (String args) ( This, at first glance, an overly complex example line is a consequence of an important requirement inherent in the development of the Java language. The point is that in Breaking this line into separate tokens, we immediately come across the keyword The next keyword is You will often need methods that return a value of one type or another: for example, Finally, we get to the method name All parameters that need to be passed to the method are specified inside a pair of parentheses as a list of elements separated by ";" (semicolon). Each item in the parameter list consists of a space-separated type and an identifier. Even if the method has no parameters, you still need to put a couple of parentheses after its name. In the example we are now discussing, the method System. out. prlntln ("Hello World!"); This line executes the method The closing curly brace on line 4 ends the method declaration Lexical basics Now that we have covered a minimal Java class in detail, let's go back and look at the general aspects of the syntax of this language. Programs for Comments (1) Although comments do not affect the executable code of the program in any way, a = 42; // if For more detailed explanations, you can use comments placed on several lines, starting the text of comments with symbols / * and ending with symbols * /. In this case, all text between these pairs of symbols will be treated as a comment and the translator will ignore it. * This code is somewhat convoluted ... * I'll try to explain: The third, special form of comments, is for the service program * This class can do wonderful things. We advise anyone who * wants to write an even more perfect class, take it as * basic. * @see Java. applet. Applet * © author Patrick Naughton class CoolApplet extends Applet (/ ** * This method has two parameters: * / void put (String key, Object value) ( Reserved keywords Reserved keywords are special identifiers that, in the language table 2 Java reserved words Note that the words Table 3 Reserved method names Identifiers Identifiers are used to name classes, methods, and variables. Any sequence of lowercase and uppercase letters, numbers, and symbols _ (underscore) and $ (dollar) can be used as an identifier. Identifiers should not start with a digit, so that the translator does not confuse them with numeric literal constants, which will be described below. Literals Constants in Integer literals Integers are the most commonly used type in ordinary programs. Any integer value such as 1, 2, 3, 42 is an integer literal. In this example, decimal numbers are given, that is, numbers with base 10 - exactly those that we use on a daily basis outside the world of computers. In addition to decimal numbers, base 8 and 16 numbers - octal and hexadecimal - can also be used as integer literals. Java recognizes octal numbers by the leading zero. Normal decimal numbers cannot start with zero, so using an externally valid number 09 in the program will result in a translation error message, since 9 is not in the range 0 .. Integer literals are values of type Floating point literals Floating point numbers represent decimal values that have a fractional part. They can be written in either regular or exponential formats. In normal format, a number consists of a number of decimal digits followed by a decimal point, followed by decimal digits of a fractional part. For example, 2.0, 3.14159, and 6667 are valid floating point values written in standard format. In exponential format, the decimal order is additionally indicated after the listed elements. The order is determined by a positive or negative decimal number following the character E or e. Examples of numbers in exponential format: 6.022e23, 314159E-05, 2e + 100. V Boolean literals A boolean variable can only have two values - Character literals Symbols in Table 3. Control sequence Description Octal symbol Hexadecimal character Apostrophe Backslash Carriage return Line feed, new line Translation of the page Horizontal tab Go back one step String literals String literals in Operators An operator is something that performs some action on one or two arguments and produces a result. Syntactically, operators are most often placed between identifiers and literals. The operators will be discussed in detail in Table 3. Separators Only a few groups of characters that may appear in a syntactically correct Java program are still unnamed. These are simple delimiters that affect the look and feel of your code. Name What are they used for? round brackets Allocate lists of parameters in the declaration and call of a method, and are also used to set the priority of operations in expressions, highlight expressions in program execution control statements, and in typecasting operators. braces square brackets Used in array declarations and when accessing individual array elements. semicolon Separates operators. Separates identifiers in variable declarations, also used to link statements in the loop header Separates package names from subpackage and class names, also used to separate a variable or method name from a variable name. Variables A variable is the main storage element in a Java program. A variable is characterized by a combination of identifier, type, and scope. Depending on where you declared the variable, it can be local, for example, to the code inside the for loop, or it can be an instance variable that is accessible to all methods of this class. Local scopes are declared using curly braces. Variable declaration The basic form of declaring a variable is as follows: type identifier [= value] [, identifier [= value A type is either one of the built-in types, that is, The example below creates three variables corresponding to the sides of a right triangle and then class Variables ( public static void main (String args) ( System.out.println ("c =" + c); Your first step We have already achieved a lot: first we wrote a small program in the languageSwitch construct
Ternary operation
The first program and familiarity with the syntax of the language
C:> javac MyFirstJavaProgram.java C:> java MyFirstJavaProgram Hello world! Java syntax basics
Java identifiers
Enumerations
Java enum code example
class FreshJuice (enum FreshJuiceSize (SMALL, MEDIUM, LARGE) FreshJuiceSize size;) public class FreshJuiceTest (public static void main (String args) (FreshJuice juice = new FreshJuice (); juice.size = FreshJuice.FreshJuiceSize.MEDIUM; System.out .println ("Size:" + juice.size);)) Variable types
Modifiers
Array
int a; ... actions on the variable a ...; if (a) (...)
Not correct in terms of Java syntax and will not compile.
In addition, supported limited types, by specifying the superclass for the parameter classes. For example, declaring a "generic class" class CLASS_NAME