How to set up smartphones and PCs. Informational portal
  • home
  • Windows Phone
  • Jsp description of what it is used for. How can you prevent direct access to the JSP page from the browser? Comments and citation symbols

Jsp description of what it is used for. How can you prevent direct access to the JSP page from the browser? Comments and citation symbols

Java Server Pages (tm) (JSP) technology enables web application developers and designers to quickly develop and easily maintain dynamic web pages. But the description of almost every technology of this purpose (ASP, PHP, Net.Data) is accompanied by such words - quickly and easily ...

Despite the external similarity, JSPs are distinguished by some points that make this technology something more than just another tool for creating dynamically generated content for web pages.

First, a simple listing:

  • really high cross-platform portability; usage universal language high level Java as scripting;
  • JSP is not some stand-alone tool for solving a fairly narrow range of tasks, albeit quite powerful, but another in a number of a whole galaxy of technologies that are combined by Java;
  • a real opportunity to separate the tasks of writing business logic for a web application and a user interface, which allows you to develop and maintain various parts of the project independently;
JSP technology is a direct extension of another Java technology - Servlets (tm) and is also closely related to Java Beans (tm) technology and uses XML-like tags (tags) and scriptlets written in the Java programming language to inject logic creating dynamic content of a web page, while HTML or XML tags are transmitted directly to the client side.

The number of tags is quite small, which simplifies the initial development of this technology; however, for simple things, the same Net.Data or PHP are also very simple. As usual, consider the primitive case of the class Hello world!
<%@ page contentType="text/html; charset=ibm866" %> <%@ page import ="java.net.*" %> <%@ page import ="java.util.Date" %> Who Am I? <% InetAddress localHost = InetAddress.getLocalHost(); Date localTime = new Date(); %>

Who Am I?

I am called<%= localHost.getHostName() %> (<%= localHost.getHostAddress() %>).
This page last executed at<%= localTime.toString() %>.

Even with a person not knowledgeable in Java, understanding the above code will most likely not cause problems. Let's dwell on some points: the code inside the tags<% %>, in fact, there is the scriptlet code; everything in between<%-- --%>-- a comment; tag<%= позволяет вывести значение переменной в нужном месте страницы; <%@ page %>allows you to import classes and also customize some features in the behavior of the page.

If the power of such competing (probably this is still so ;-) tools like PHP and Net.Data is primarily due to a huge set of predefined functions, then the entire conglomerate of Java classes and technologies is behind JSP.

But with such a simple example, it is not at all obvious why you need to choose JSPs and everything associated with them, primarily servlets and beans. Nevertheless, let's try to look at some of the nice aspects of JSP.

Session Management

The values ​​that are stored and retrieved from the session object cannot be primitive data types (int, double) and must be represented in the form of their analog classes (Integer, Double).
HttpSession session = request.getSession (); // get session object or create one session.getId () // get the session ID number Integer item = (Integer) session.getValue ("item") // retrieve Integer object session. putValue ("ItemValue", itemName); // ItemValue must not be primitive

Application Management

Sometimes it is necessary to provide the server with some variable values ​​at the site level, each client uses and manipulates copies of this data. JSP uses the ServletContext object, which provides a session-like mechanism (i.e. no primitive types).
getServletContext (). setAttribute ("Item", ItemValue); // to set an application variable Integer i = (Integer) getServletContext (). getAttribute ("ItemName"); // get item color = blue>

JSP-Specific Language

JSP directives "tell" the server to do something when they are converted from JSP to servlet; directives are preceded by @. Some important JSP directives are listed below, for a more complete acquaintance, you will naturally have to read something else.
include - include a static or dynamic file (Server Side Include) <%@ include file="hello.jsp" %> import - the resulting servlet will import the given package<%@ import = "java.util.*" %>extends - the servlet will extend (inherit) the specified class (this is a superclass) <%@ extends = "java.util.Dictionary" %> implements - the servlet will implement the interface <%@ implements = "java.util.Enumeration" %> content_type - Sets the type of response generated by the servlet <%@ content_type = "text/plain" %> or <%@ content_type = "text/html" %>

It is known that tasks in this complex world are not only simple or even very simple. If you succumb to the temptation to do everything using scriptlets (dynamic insertion of Java code among static HTML), and consider external classes as a powerful library of functions, it is very easy to turn a dynamic page into a voluminous monster, difficult to debug and with enormous difficulties with further modifications and extensions.

Yes, like the competition, complexity can be mitigated by breaking a complex page into several logically distinct chunks and putting them together using an include tool.

There are two options for include:

  • Static inclusion, at the same time, JSP elements in the include file are processed, if they exist and get into the resulting generated Java code, in fact, a serlet:
    <%@ include file="includeheader.jsp"%>
    or so
    <%@ include file="includeheader.html"%>
    that is, the include file does not have to be a JSP page at all.
  • Dynamic inclusion, while the content of the included file is processed independently, in fact, control is transferred to it at the time of execution:
Interestingly, dynamically included content can be cached independently, which in some cases gives significant gains on complex multi-component pages. But the ability to include is nevertheless probably the most primitive of multifaceted possibilities JSP.

Almost everyone, starting to make a web application, is faced with the need to provide the user with convenient tool to enter information, and here, as a rule, b O There are more problems than just providing information in the form of generated HTML pages. It is necessary to ensure sufficient intelligence of the input, in addition, in case of input errors, do not lose the previously entered and transfer the required general information from page to page. In Net.Data, for example, I have not found a way to do this other than using hidden fields in input forms, while storing information with a "session" lifetime becomes a difficult task; how you can get out with solving this problem in PHP, I do not know. As for JSP / servlets - there is a standard JavaBeans facility (in this context, we will not dwell on such a more powerful development of this concept as EJB) - these are full-fledged Java classes with some additional rules programming.

It is a very powerful tool, but it does require some stereotyping. JavaBeans are Java components that can perform well-defined tasks and include data objects. JavaBeans follow structured object model: The bean has a public constructor that has no arguments, and its properties are set using the control servlet using introspection / reflection.

Including a bean in a JSP "page" is done like this:

... Addition <%=formHandler.getErrorMsg("description")%> Owner <%= formHandler.getOwnerName()%> | <%= formHandler.getOwnerName()%> <%=formHandler.getErrorMsg("owner")%> ===> or here's another one
I like<%= Cindy.getFlavor() %>coffee. // The Coffee Bean: Public class Coffee (private String m_flavor; public Coffee () (m_flavor = "Regular";) public void setFlavor (String flavor) (m_flavor = flavor;) public String getFlavor () (return m_flavor;))

Some explanations for this squeeze: scope = "request" means that the lifetime of the bean is request, property = "*" means that this bean accepts with the help of its methods all parameters passed in the request to this page... These methods have a simple naming rule: if the form parameter is lastName, then the method that receives the data will have the name setLastName, and the method that returns the data will have getLastName.

Unfortunately, it's hard enough to demonstrate the full power of using beans in simple application... However, this article does not aim to give all the depth, the task is to interest.

The general line that can be traced in many recent publications is the separation of the work of the designer and the work of the programmer, who provides the writing of the actual work with the database and the business logic of the web application. Most of this can be done at the bin level. Unfortunately, the laboriousness of writing, according to at least on the initial stage, the JSP-servlets-beans bundle looks larger than that of Net.Data and PHP (however, I am familiar with the latter at a slightly larger "Hello World!" level). But even the use of bins does not completely exempt from the minimum using Java On the page. To reach the logical end and leave the designer only the correct arrangement of tags on the page, the JSP introduced the ability to write custom JSP tag libraries.

Using tag libraries allows, firstly, to further increase code reuse, secondly, to reduce the complexity of writing an application, and, thirdly, to further help in the division of labor. Unfortunately, the latter in our reality has not yet acquired the proper weight when choosing a development tool. In conclusion, I will give a small example of using custom tags, for example, a query to the database with the output of the result in the form of a table might look like this:
<%@ taglib uri="xsql.tld" prefix="xsql" %> ...

somethingsomethingdescription
"$1$""$2$""$3$"
but that doesn't mean that it should look like that ;-)

In fact, the topic is too broad to be covered without blank spots in such a short presentation.

JSP (Java server pages) Is a technology that allows you to embed Java code as well as EL (expression language) in static page content) and allows web developers to dynamically generate HTML, XML and other web pages. JSP is part of a unified technology for creating J2EE business applications.

JSP - can run on almost any web server, as this technology is based on the Java programming language, which is platform independent. Java server pages supports HTML tags, Javascript as well own set tags.

JSP - allows you to separate the dynamic part of the page from the static one. This technology provides for the insertion of Java code into the page. We will not consider this use case for JSPs as this technology is considered obsolete and imperfect. The reason is simple: developers and designers who design the appearance of a page may not always be familiar with Java and this can cause additional difficulties when editing or maintaining web applications.

Instead of inserting Java code, the jstl tag library or Javascript for the very advanced is now used. We will consider an example with jstl tags. This is a very handy library that has almost all the functionality you need to create dynamic pages. If you need something specific, you can always write your own tag and insert its content into the page.

We are already partially familiar with JSP from the first. The main body of the JSP page is HTML, into which tags with dynamic content are inserted.

Sample JSP Page

A very necessary knowledge that we will use is the JSP directive.

A JSP directive is a message that a page can send to the appropriate container, specifying actions. Directive syntax:<% @ атрибут = «значение» %>

There are three main types of directives:

  1. page (can be used to import classes);
  2. include (gives you the option to insert the file into the servlet class when translating the JSP file to the servlet);
  3. taglib (makes it possible to include a tag library).

Since we will not insert the code into the page, we will consider the last two directives.

For example, we have pages that will have the same top and bottom. A very common pattern where the footer and header are the same for all pages. In order not to write the code of these pages in each JSP file, you can put their code into separate files and then connect it in the place we need using include directives.

Location of files in the project:

In the code above, you can trace the use of the taglib directive. With its help, we connected the jstl tag library. Using this directive, you can connect a library of your own tags:<%@ taglib uri=»/WEB-INF/mylib.tld» prefix=»test» %>.

Note that the important taglib attribute is prefix. This is a required attribute. With prefix, you can call the library in your code. You can choose any prefix name. By the way, here is the use of jstl tags in practice:

    < c: forEach items= "$ (accounts) " var = "account">

    < tr align= "center" >

    < td>$ (account. number)

    < td>$ (account. balance)

    < td>< c: if test= "${!account.isBlocked}" >$ (statusActive)

    < c: if test= "${account.isBlocked}" >$ (statusBlocked)

    < td>< c: if test= "${!account.isBlocked}" >

    < a href= "? command = blockaccount & accountId = $ (account.accountId)"> $ (block)

    < td>< a href= "? command = showinfo & accountId = $ (account.accountId)"> $ (showInfo)

The code above demonstrates the output of all the elements of the list. How we transferred it to the page will be in the next articles. Its syntax is:

$ (item)

This is the sidebar code linked above. As you can see, forking is used here to display only the information that is available to a certain type of user.

Syntax:
a equals b

It is best to consider jstl tags when writing real project, since I see no reason to learn and memorize the entire syntax for each action. The code above should only serve as an example of how this is used. You don't need to memorize anything. When you write the code, then refer to this syntax.

By the way, the project code from which this code was taken is located here: https://github.com/caligula95/payment-systemapp

I posted the project on heroku: https://payment-systemapp.herokuapp.com/ - a free account is used here, so for the first request you need to wait a couple of minutes for the project to start.

Servlets allow you to receive requests from a client, do some work, and display the results on the screen. The servlet works fine until it comes information processing, i.e. before displaying information on the screen. You can insert quite complex logic into the servlet, make calls to the database, and much, much more that is necessary for the application. But it is very inconvenient to carry out the output to the screen inside the servlet itself. And what to do when developing complex design ideas and then making changes to user interface? Design technology Java Server Pages (JSP) is one of the J2EE technologies that is an extension of servlet technology to make it easier to work with Web content. JSP pages make it easy to separate Web content into static and dynamic parts, allowing for reuse of previously defined components. Java Server Pages developers can use JavaBeans components and create their own custom tag libraries that encapsulate complex dynamic functionality. The Java Server Pages specification (http://java.sun.com/products/jsp) inherits and extends the servlet specification (http://java.sun.com/products/servlets). Like servlets, JSP components are Web components and reside in a Web container. JSP pages are independent of the specific implementation of the Web container, which makes them reusable. In addition to the classes and interfaces for servlet programming (packages javax.servlet and javax.servlet / http), in packages javax.servlet.jsp and javax.servlet.jsp.target contains classes and interfaces related to Java Server Pages programming. Full description Java technologies Server Pages can be found in the spec at (java.sun.com/products/jsp/download.htm)

Java Server Pages Technology Overview

Java Server Pages technology contains four key components:
  1. Directives (directive) are messages for the JSP container, allowing you to define page parameters, connect other resources, use your own non-standard tag libraries.
  2. Actions (actions) encapsulate functionality in predefined tags that you can embed in a JSP page. Actions are often performed based on information sent to the server as part of a request from a specific client. Actions can also create Java objects for use in JSP scriptlets.
  3. Scriptlets (scriptlets) allow you to insert Java code into JSP pages that interacts with page objects when processing a request.
  4. Tag Libraries (tag library) are part of a tag extension mechanism that allows you to develop and use your own tags.
The presence of data with an immutable structure determines the choice of the programmer in deciding which technology to use: servlets or JSP pages. Programmers prefer to use JSP pages when most of the content sent to the client is immutable data and only a small portion of the content is dynamically generated using Java code. Servlets are preferred if only a small portion of the content sent to the client is immutable data. In fact, individual servlets may not generate any content for the client at all, doing a specific task in the client's best interest and then invoking other servlets or JSP pages to send the response. It should be noted that in many cases, servlets and JSP pages are interchangeable. Like servlets, JSP pages usually run on the side of a Web server called a JSP container. When a Web server that supports JSP technology receives the first request for a JSP page, the JSP container translates that JSP page into a Java servlet that serves the current request and any subsequent requests to that page. If errors occur when compiling a new servlet, these errors result in compile-time errors. The JSP container at the compilation stage puts the Java statements that implement the JSP page response into the method _jspService. If the servlet compiles without error, the JSP container calls the method _jspService to process the request. The JSP page can process the request directly, or it can call other components of the Web application to help process the request. Any errors that occur during processing cause Web server exception during request phase... All static HTML text called in the JSP documentation HTML template(template HTML) is sent directly to the output stream. The output stream of the page is buffered. Buffering is provided by the class JspWriter extending the class Writer... The buffer size is limited to 8KB by default, but it can be changed by the attribute buffer tag <%@ page> ... The presence of a buffer allows writing the response headers into the output stream together with the output text. In the buffer, the headers will be placed before the text. Thus, it is enough to write a JSP page, save it in a file with the extension jsp and install the file into a container, just like an HTML page, without worrying about compilation. During installation, you can set initial parameters the JSP pages are the same as the initial parameters of the servlet.
1) NetBeans 7.3;
2) Maven;
3) Hibernate;
4) Spring MVC;
5) JSP + JSTL;
6) Knowledge about Servlets, Sessions, JavaBean, XML, etc .;
7) HTML + CSS (a bit of beauty to your liking, but it's better to pay left-handed people - you have enough trouble with the server side);
8) Java SE (knowledge of collections, the ability to handle exceptions ... In general, a standard set);
9) Knowledge of design patterns (DAO, Factory);
10) JPA;
11) SVN;
12) SQL (for writing scripts that fill our databases).

Let's start with where we will store our code and how to share it with friends. I think not all beginners know about repositories, and this part is just for them.

SVN

There is such a thing as a repository - remote server storing the code.
If you are given a test task, and you send it in an archive, then you will most likely be sent too. Maybe they won't, but they will definitely be disappointed in you.
There are various repositories for CVS, SVN, Git. For beginners, I think SVN is optimal. Well, the main thing for you is not to know what it is, but to be able to apply it. As long as this is enough, the rest will come with experience.

After all this, you will have a link to your space. To understand what it is, you need to take one of your projects (or create some empty project in NetBeans). Click on it with the right button and you will have access to "Version Control" -> "Import into Subversion Repository" in the menu. After that, there will be a dialog box with the path to the repository - this is the link you received on the site in the "Source Code" tab.

Next, completely delete the project that you have committed. Then go to the folder where your projects are stored and check that everything is really deleted. Then you return to NetBeans and look for the Group tab in the menu bar (in the panel where File, View, Edit, Transition, Source ...) it contains our Subversion. And in the submenu it has "Get". Further, in the dialog boxes, you will need to specify a link to the repository (this is the link that you received on the site in the "Source Code" tab.) And when he offers to download the folders, then you will need to find your project in the repository tree and select it, and upon completion you download your project. This is how code is exchanged.
Your project will constantly sync with the repository and mark files that have been changed or new (which is different from the version on the repository). To update, you need to call the context menu, and in the "Version Management" tab there will be a large list of what you can do with the project. Update is to update your files; "Commit" - put the code that you wrote or changed into the repository; "Discard" - return to the version on the repository, and "Compare" - display changes to rows that differ from the deleted ones. This is a method of command exchange of code, which is always used and you need to get used to it.

You've already downloaded NetBeans, played around with SVN - now let's get down to business. Create a project. Click "Create Project", there you select Maven-> Web Application. Call it what you want, it's all your imagination. So, we have a web application, the assembly of our project is going maven, we have a goal and now it's time to think about how to implement it. That is, you, as a developer, have to think about how your application will look like, what architecture, package tree, and so on. The total number of lines of code here is about 4000 and it is better to take care of a beautiful architecture in advance, otherwise you will simply not understand what works where and how, by what miracle you, for example, display the last purchased item, as you consider the total amount of purchases. And if you are then asked to complete or add something, you will realize that it is easier to write everything from scratch.

And of course we need to figure out our plan of action.

So: Action Plan
1) we describe entity (entities) - entities. It is a POJO - a class associated with the database via annotation (@Entity) or via XML. We will use JPA, so we need to import javax.persistence. * Why not Hibernate Persistence API, because if we use it and then we want to change the ORM library, then our classes will have to be rewritten, and JPA is a standard from Sun. As for what JPA is - well, for you, I can put it this way in my own words: it is a library that provides an API for working with * long-lived * objects, that is, it allows us to conveniently save our objects in the database. I can give advice: create for this separate package name it entity or domain - whatever you want, the main thing is to make it clear to you. It might end up looking like this: edu.shop.model.domain.Customer.java edu.shop.model.domain.Notebook.java.
I will describe in more detail directly when considering this item. Now the task is to figure out a plan of action.

2) Create HibernateUtil (in general, the suffix or prefix Util implies that the code in this class is universal and is used by many classes).
So in HibernateUtil we host the SessionFactory. He's heavy. This code, in theory, should be independent of the entire application, since it establishes a connection to the database at startup and should only give us Sessions with the database. We also register our entity classes in this class. I'll tell you more about this class later. Let's put it in a separate package too, for example, edu.shop.model.hbutil.HibernateUtil.java

3) Writing DAO.
What should I write in it? We write what we want to get from the database, but we do not need to think about how this data was obtained, the result is important. For example, we define the ProductDAO interface and write methods in it
List > getAllProducts (); then we write its implementation ProductDAOImpl.

What's the idea? If you and I wrote this application, you would say: "Micah, I need the following data from the database: all the goods that I have in the database." I answer: "not a question." And then the following development of events: in your code, wherever you need to make queries to the database, write the following%

* here call to method * .getAllProducts (); - and you see that the compiler does not swear, and I might not have time to write the implementation of this interface yet. And what is the result? Everything has been compiled for you, but there is not even a working code. We're going to use Enums and the Factory pattern here, and some more, but all in good time. It is in the DAO that you need to pay special attention to exception handling, at least to generate error pages. So that you quickly find a piece of broken code. Otherwise, you will simply be tortured with debugging.

3) This is where our work with Spring MVC starts. This is a long story and a separate article will be devoted to this. I'll tell you right away - this is the most difficult thing in this application. But I will show you a simpler option, how to display everything, not really caring about the MVC pattern.
Let's touch on the use of scriptlets.

4) Here we will have helper classes that add all sorts of goodies to our project: calculating the total amount of purchases; last purchased item; auxiliary variables that will be useful to us for the operation of the method, which, for example, will display things from the database for us no more than UAH 5000, or no less than 500; conclusion of all Asus brand laptops. This item is closely related to the previous one.

Let's dwell on this for now. We'll deal with the rest a little later. So, we have a planned plan, let's start implementing it.

Entity

We created our project and created our entity package. Let it be edu.shop.entity. There we create classes like this:

Note. The basket in which our purchased goods will be stored will be like a table in the database, I did this because I will show some of the basics of working with the database on it. For a real case, it would be more expedient to use collections to store our goods.

1) Product
2) Notebook
3) Camera
4) Book
5) Cable
6) Customer
7) Cart

Let's talk a little about what an entity class is.
Entity - POJO-class associated with the database using the annotation (@Entity) or via XML. This class has the following requirements:

Must have an empty constructor (public or protected);
- Cannot be nested, interface or enum;
- It cannot be final and cannot contain final fields / properties;
- Must contain at least one @Id-field.

In this case, an entity can:

Entities can be related to each other: one-to-one, one-to-many, many-to-one, and many-to-many.

We will use annotations. And here we immediately have the opportunity to describe in two ways. Either we will write annotations directly above the fields, or above the getters. I will say one thing: it is correct to write over getters, but you will ask the reason in Google. I can't describe all the topics here absolutely.

There is one more thing I want to say. To do this, you will have to show 2 examples of the description of the entity class. So the first example:
I wrote the comments to it in the code itself:

Import java.io.Serializable; import javax.persistence. *; import javax.validation.constraints.Size; / ** * * @author Mikhail Shumenko * / @Entity // With this annotation, we indicate that this class is an entity. @Table (name = "CART") // With this annotation, we indicate that a table named CART is responsible for this entity in the database // I want to note that the register is not important, this annotation can be omitted, then the hibernate will create a database for us with / / with the same name as the class public class CartEntity implements Serializable (// Here we write annotations over the fields. Writing correctly over the getters // Describe the Id of the table @Id // Indicate that this class field is responsible for the column in the table named Id // If we will not specify it, the hibernate will create a column with a name like the field. @Column (name = "ID") // You can write a lot here)) Why did I write like this here? In general, you can write AUTO instead of TABLE in //@GeneratedValue(strategy=GenerationType) then // at the first loading of the table, Id will be generated automatically from 1 to its maximum value. // If you have 20 items in the table, then it will generate from 1 to 20. // But with subsequent additions, the id of the added item will be something like this - 345768. // I wrote everything so that my last id is stored in the table and generated then adequately on subsequent additions. // There is also SEQUENCE, but it is not supported in Derby, and we will work with it. // In general, these are nuances. You can find out about them yourself @TableGenerator (name = "cartid", table = "cartpktb", pkColumnName = "idCart", pkColumnValue = "(! LANG: idCartValue",allocationSize = 1) @GeneratedValue (strategy = GenerationType.TABLE, generator = "cartid") private Integer id; //Указываем максимальный размер. Это строка из 25 символов. @Size(max = 25) @Column(name = "NAMEITEM") //Если тип нашего поля String, то и создаваться будет столбец с типом VARCHAR(в Derby) //Если Integer, то будет столбец, в который поместить можно только Integer //boolean в Derby - это столбец с типом SMALLINT private String nameItem; @Column(name = "PRICE") private Integer price; public CartEntity() { } public CartEntity(String nameItem, int price) { this.nameItem = nameItem; this.price = price; } public CartEntity(Integer id,String nameItem, int price) { this.id=id; this.nameItem = nameItem; this.price = price; } public CartEntity(Integer id) { this.id = id; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNameItem() { return nameItem; } public void setNameItem(String nameItem) { this.nameItem = nameItem; } public Integer getPrice() { return price; } public void setPrice(Integer price) { this.price = price; } } !}

Second way: we write over getters. See the code for explanations.

import java.io.Serializable; import javax.persistence. *; / ** * * @author miha * / @Entity // See, I did not specify the @Table annotation // Hibernate will understand everything for me. public class Product implements Serializable (private Integer id; private String nameProduct; private Integer availableProduct; @Id @GeneratedValue (strategy = GenerationType.AUTO) // I described Id above the getter, which means that work with the rest of the fields will go through getters.public Integer getId () (return id;) public void setId (Integer id) (this.id = id;) public String getNameProduct () (return nameProduct;) public void setNameProduct (String nameProduct) (this.nameProduct = nameProduct;) public Integer getAvailableProduct () (return availableProduct;) public void setAvailableProduct (Integer availableProduct) (this.availableProduct = availableProduct;))

So, you have two examples of entity classes. Build the rest using these examples. Such fields as: model, year of publication, name, cost - everything is up to your imagination. Be sure to include the field Available (in translation, availability). It will be useful to you later. You can make it boolean and add a column named quantity. All this will be useful to us.

Now let's give an example of our HibernateUtil

/ * * To change this template, choose Tools | Templates * and open the template in the editor. * / package edu.shumenko.hibernate; import edu.shumenko.entity.BookEntity; import edu.shumenko.entity.CableEntity; import edu.shumenko.entity.CameraEntity; import edu.shumenko.entity.CartEntity; import edu.shumenko.entity.CustomerEntity; import edu.shumenko.entity.NotebookEntity; import edu.shumenko.entity.ProductEntity; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.SessionFactory; / ** * Hibernate Utility class with a convenient method to get Session Factory * object. * * @author Mikhail Shumenko * / public class HibernateUtil (// Create our SessionFactory.private static final SessionFactory sessionFactory; static (try (// Create a new instance AnnotationConfiguration AnnotationConfiguration ac = new AnnotationConfiguration (); // We need this in order to so that we add all our entity classes. // each of your Entity needs to be registered here, if you don't write it, it won't work.ac.addAnnotatedClass (ProductEntity.class) .addAnnotatedClass (BookEntity.class) .addAnnotatedClass (CableEntity.class) .addAnnotatedClass (CameraEntity.class) .addAnnotatedClass (CameraEntity.class) .class) .addAnnotatedClass (NotebookEntity.class). addAnnotatedClass (CartEntity.class) .addAnnotatedClass (CustomerEntity.class); // So we actually created our Session Factory. // It is needed because we work with the database through sessions / / Details will come a bit later, while you know how to do it and how to work with it.sessionFactory = ac.configure (). BuildSessionFactory ();) catch (Throwable ex) (// Log the exception. System.err. println ("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError (ex); )) public static SessionFactory getSessionFactory () (return sessionFactory;))

DAO

Let's move on to the next part. What is DAO. This is a design pattern.

Its meaning:
- All access to the database in the system is done through DAO for encapsulation.
- Each DAO instance is responsible for one primary domain object or entity. If the domain object has an independent lifecycle, it must have its own DAO.
- The DAO is responsible for the operations of creating, reading (by primary key), updating and deleting (that is, CRUD (create, read, update, delete)) of a domain object.
- DAO can resolve queries based on criteria other than the primary key. I am referring to methods like finder or finders. The finder method usually returns a collection of domain objects that the DAO is responsible for.
- DAO does not handle transactions, sessions or connections. This is done outside the DAO for flexibility.
Google will always tell you more.

We will write a DAO for our products for now.
So, let's think about what we really need. The Product table will have 4 fields Id, nameProduct, available + amount + actionForServlet. We will need it to create categories on our site. We don't bother with the last field yet. The only thing we need is to get a list of products.

Writing an interface
public interface ProductDAO (ProductDAO INSTANCE_PRODUCT = new ProductDAOImpl (); List GetProducts (); // and the method with which we will work)

Implementation of our interface. See the code for explanations.
/ * * To change this template, choose Tools | Templates * and open the template in the editor. * / package edu.shop.model.dao; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; / ** * * @author Mikhail Shumenko * / public class ProductDAOImpl implements ProductDAO (@Override public List GetProducts () (List Result = null; // Create a session, it is needed to use transactions // Roughly speaking, a transaction is like a recovery point, if it does not go through to the end, then all changes are rolled back. Session session = HibernateUtil.getSessionFactory (). OpenSession (); try (session.beginTransaction (). begin (); // Criteria is used for a request to get data from the database // This formulation, I think, is enough for you for now // As a parameter, we pass the entity class that we use. If the data received from the Cart table, then transfer // it would be necessary Cart.class Criteria criteria = session.createCriteria (Product.class); result = (List ) criteria.list (); session.getTransaction (). commit) catch (Exception e) (// Be sure to write exception handling. But I'll leave that to you on your own. e.printStackTrace ();) finally (if (session! = null) session.close ( );) return result; ))

So, now we have the ability to get data from the database. You can use scriptlets to create a straightforward for-each loop and output your products to your index.jsp page.

Categories

// INSTANCE_PRODUCT what is it? // Such a variable is described in ProductDAO, it is responsible for creating ProductDAOImpl // Well, everything will be different for us, you don't have to remember it too much. // ProductDAO INSTANCE_PRODUCT = new ProductDAOImpl ();<% for (Product product:ProductDAO.INSTANCE_PRODUCT.getProducts()) {%> <%}%> <% for (Product product: ProductDAO.INSTANCE_PRODUCT.getProducts()) {%> <%}%>
Category"><%=product.getName()%>
Availability<%=product.getAvailable()%>

But this is for the first time, but in general it is bad to do so. This violates our MVC pattern... I will explain how to do it right in the next lesson, if they give me an invite. In the second tutorial we'll tackle Spring, in the third we'll touch on the Factory pattern, and dive deeper into hibernate. For those who are especially impatient, I will show you how to delete from the database, save to the database and completely delete everything from the database. Well, how to make it all interact with our application as a whole and leave the detailed consideration for later.

Save to DB

public void addItemToCart (CartEntity cart) (Session session = HibernateUtil.getSessionFactory (). openSession (); try (session.beginTransaction (). begin (); session.save (cart); session.getTransaction (). commit (); ) catch (Exception ex) (ex.printStackTrace ();) finally (if (session! = null) (session.close ();)))

Remove from database by id

public void deleteItemFromCart (Integer id) (Session session = HibernateUtil.getSessionFactory (). openSession (); try (session.beginTransaction (). begin (); CartEntity itemDelete = (CartEntity) session.get (CartEntity.class, id); session.delete (itemDelete); session.getTransaction (). commit ();) catch (Exception ex) (ex.printStackTrace ();) finally (if (session! = null) (session.close ();)))

Removing the group id from the base.

public void deleteAllItemToCart (List idAllItemsInCart) (Session session = HibernateUtil.getSessionFactory (). openSession (); try (session.beginTransaction (). begin (); for (Integer id: idAllItemsInCart) (CartEntity itemDelete = (CartEntity) session.get (CartEntity.class, id); session.delete (itemDelete);) session.getTransaction (). commit ();) catch (Exception ex) (ex.printStackTrace ();) finally (if (session! = null) (session.close () ;)))

You will also need a Hibernate configuration file. Create a shop database in Derby. Username and password are root and pass respectively. If it does not work out - do not be discouraged - I will devote more time to this.

org.hibernate.dialect.DerbyDialect org.apache.derby.jdbc.ClientDriver jdbc: derby: // localhost: 1527 / shop root pass UTF-8 update

We will talk about how to fill in our databases later. You can fill them in manually. Or wait for the next lesson.

05.13.05 14.8K

Introduction

Java Server Pages (JSP) technology is part of the unified technology for building J2EE business applications. JSP is an alternative technique for developing applications that dynamically generate responses to specific client requests. Before the JSP document is used, a special procedure converts it to the appropriate servlet. In turn, a servlet is usually written in Java language and implements a specific interface. Further, the servlet is also not a standalone application and functions only when placed in the appropriate web container. The web container provides data exchange between the servlet and clients, takes care of such functions as creating a software environment for a functioning servlet, identifying and authorizing clients, organizing a session for each of them.

On the currently the JSP page is translated into a servlet, the program code of which is written in the Java language. However, the authors of the Java Server Pages specification leave it possible to implement JSPs in other programming languages.

The relationship between servlets in a line-of-business application and URLs on the server is specified in the deployment descriptor. Servlet implementation technology is discussed in a separate article. For now, it is important to note that the code used to write servlets is not always convenient for dynamically generating text documents in response to a client request. For example, a snippet of a servlet that generates a dynamic HTML pages might look like this:

PrintWriter out = res.getWriter (); out.println (" "); out.println (" "); ... out.println (""); out.println (""); out.close ();

As you can see, each HTML string document in the servlet corresponds to a certain piece of program code, which does not contribute to the ease of development and maintenance of business applications.

It is more convenient to separate the dynamic and static parts of the generated web page. You will continue to use Java or another programming language to create the dynamic part. It makes sense to design the static part as a text document - Java Server Page (JSP page), designed in accordance with HTML requirements, XML, or another markup standard. In fact, a JSP page can be thought of as a template or prototype of a dynamic page, which remains to be supplemented with dynamic elements. To describe the dynamic component, the JSP technology provides two main mechanisms: JavaBeans and libraries of additional tags. As a result, the JSP technology presupposes the parallel work on the application by two different specialists: a programmer and a person responsible for layout of documents (web masters), who are responsible, respectively, for the development of dynamic and static parts of documents generated in response to customer requests.

As mentioned, before you can use a JSP page, you need to transform it into an appropriate servlet. This transformation can be performed either when the JSP page is placed on the server, or when the client first accesses the page. Since the conversion procedure is quite laborious and time-consuming, it is usually performed only once. However, the server will automatically redirect subsequent calls from the client to the JSP page to the servlet that was received as a result of its transformation.

The servlet obtained after transforming the JSP of the page operates within a standard servlet container and uses a highly regulated interface. Therefore, this technology does not depend on any features of a particular hardware platform. On the other hand, since JSP technologies can be built on the basis of the Java interpreted language, this gives a guarantee of portability of applications built on JSP technology to any platform where you can install virtual Java car.

JSP page

Typically a JSP page is stored in separate file with the extension .jsp. Most of the page's JSP content is servlet mapped into a set of out.println () statements. Sample JSP page:

<%@ taglib uri="/exttags.tld" prefix="dscat" %> <%@ page import = "xbcat.util.*" %> All Customers <% Vector menu=pagescroll.getMenu(); if(pagescroll.page.size() > 0) { %>

<%= pagescroll.getTotalPages() %> <% if(!pagescroll.isSinglePage()) { for(int i=0; i "><%= name %> <% } else { %> <%= name %> <% } } } %>

The dynamic component of the JSP page is represented by three types special elements: directives, actions and scripts. Each of them is discussed in more detail in the corresponding section.

Directives

Since the web container, before using the JSP page provided by the developers of the business application, translates it into the appropriate servlet, it makes sense to provide the ability to leave directives on the JSP page that will control the translation process. Directives have the syntax

<%@ директива... %>

Let's look at some of these directives

The page directive. Declares a number of JSP page properties. Directive syntax:

<%@ page список_параметров %>

Let's describe some of the most interesting parameters of this directive:

  • import - As already mentioned, the JSP page must be converted into the program code - the class corresponding to the servlet before use. In turn, the servlet class can refer to other classes from the standard Java libraries or classes from other packages. By default, the servlet class obtained after the JSP page is translated can be associated with the java.lang, java.servlet, java.servlet.jsp, and java.servlet.http packages. If the servlet class needs to communicate with other packages, for example, with xbcat.util as in the above JSP page example, the latter should be supplemented with a page directive that has an import attribute with the name of the corresponding package.
  • session - If the HTTP protocol is used to communicate with a client, a session object is created by default for each session, which allows storing information about this client in the interval between its calls to the server. On the other hand, if the session attribute was specified with the value false, this allows you to refuse to create a session object and use the freed server resources for other tasks.
  • buffer - The content of the page created in response to the client's request is passed by the servlet to the out output stream, from where it is then passed by the web container directly to the client. In order to obtain a more optimal transmission mode, this stream is provided with a buffering mode. The default buffer size is 8 kilobytes. The buffer parameter of the page directive allows you to either set a different buffer size, or to abandon the buffering mode altogether by passing the value "none" to the attribute.
  • isThreadSafe - According to the servlet specification, the default web container allows the same servlet instance to process requests from multiple clients in parallel. In this case, a separate thread is allocated to each of the requests. However, in some cases it can be useful to disable parallel query processing. (The corresponding controller in the web container queues incoming requests and passes them to the servlet for processing strictly one at a time.) To do this, it is enough to use the isThreadSafe attribute, with the value false.
  • pageEncoding - Allows the application developer to declare the encoding to be used in the document passed to the client. By default, the page is considered to be in ISO-8859-1 encoding.
  • contentType - In response to a client request, the default JSP page generates a document HTML type... At the same time, the field of application of Java Server Pages technology is much wider, since it allows you to generate any other types of text documents: XML, WML, VRML, etc. The MIME type of the generated document is declared with the contentType attribute. As already understood, this attribute is set to "test / html" by default. Together with the document type, the JSP specification allows the encoding of the generated document to be specified in the same attribute.

The taglib directive. Allows you to use additional tags created by the application developer (custom tags) on JSP pages. Directive syntax:

<%@ taglib uri="URI библиотеки тэгов" prefix="имя префикса" %>

where, uri is an absolute or relative URI that uniquely identifies a handle to the tag library associated with the specified prefix. The specified prefix is ​​used to identify matching custom tags.

<%@ taglib uri="http://www.mycorp/supertags" prefix="super" %> ... ... ...

We will look at the procedure for creating custom tags later.

Include directive. Used to put texts and program code from other sources into a JSP page. Substitution is performed when the JSP page is translated into the appropriate servlet. An example of using the directive:

<%@ include file="menu.jsp" %>

Note that substitution of materials from an external source can also be performed using a special tag , which will be discussed by us later. The difference between this tag and the described directive is that the substitution is carried out directly in the process of processing a client request, and therefore can be tied to the request parameters.

A fragment of the program code on the JSP page (script)

The script, like other elements, adds a dynamic component to the final document. However, unlike them, a script is a program code placed directly in the JSP text of a page. The script can perform calculations or manipulate objects, which allows you to visually associate the characteristics of the generated page with the parameters of the client's request and the business rules of the application. Script elements are of three types: declarations, scriptlets, and expressions.

Declarations

After the JSP of the page is converted to a servlet, most of its content goes into the _jspService () method, which is called whenever a customer order needs to be processed. A JSP page declaration is most often used to declare additional attributes and methods in a servlet class that will be available when processing any client request. Declarations have the syntax<%! … %> .

Examples of declarations on the JSP page:

<%! int i; %> <%! int i = 0; %> <%! public String f(int i) { ... } %>

Scripts

A scriptlet can contain program code and local variable declarations that will be used to process client requests. In fact, a scriptlet is a piece of program code from a future servlet, which in due time will be placed in the _jspService () method. As a part of the servlet, the scriptlet gains access to the response object and, accordingly, can independently form a certain part of the final dynamic page. However, most often scriptlets are used not for this, but in order to manage objects of business logic and application logic.

The scriptlet has the syntax<% … %>... An example of using scriptlets in JSP page content:

<% if (i == 0) { %>Good morning<% } else { %>Good afternoon<% } %>

To appreciate the clarity and simplicity of this construction, compare it with the equivalent code snippet in a servlet:

if (i == 0) (out.println ("Good morning");) else (out.println ("Good afternoon");)

Expressions

Often, the page transmitted to the client contains the results of calculations or calls to certain methods and attributes of certain classes. Any of these dynamic elements can be converted to a string and presented on a JSP page by calling out.println in the appropriate script:

<% UserProfile user = (UserProfile) session.getValue("Profile"); %> <% out.println(user.getFaxNumber()); %>

The second line in the given example is more convenient and clearer to represent in a more multiple form, using the expression syntax<%= … %> :

<%= user.getFaxNumber() %>

Another example of using an expression in the body of a JSP page:

<%! int i = 0; %>Hi, now the servlet processing<%= ++i %>th request.

JSP pages and objects

In the course of processing requests, the JSP page can access the objects located on the server, create them and modify them. Objects are accessed through script and action elements. Each object created in the application has a certain lifetime, which is declared in the corresponding attribute. The specification provides four intervals:

  • page - The object, whose lifetime is defined as page, is accessible only within the JSP page where it was created. All references to this object must be released immediately after the client's request has been processed.
  • request - An object whose lifetime is specified as request and is available to all pages associated with processing this request. In particular, if processing is redirected to a new JSP page, this object will be available on both the old and the new page. As in the previous case, references to the object must be released after the request has been processed.
  • session - A session-scoped object is available to all pages handling requests associated with a specific session (a session with a specific client). References to objects associated with the session are placed in the session object. At the end of the session, the links must be released.
  • application - Most general scope. Objects scoped with application are not tied to any separate page or session and are accessible from all JSP pages of this application.

JSP page always has access to a specific set of objects, created by the web the default container:

  • request - An object containing the client's request. Refers to the javax.servlet.ServletRequest class, or another class that inherits from it. For example, for the HTTP protocol, this would be an object of the javax.servlet.http.HttpServletRequest class. The scope of the object is request.
  • response - The object into which the servlet will place the response to the user's request. Refers to the javax.servlet.ServletResponse class, or another class that inherits from it. For example, for the HTTP protocol, this would be an object of the javax.servlet.http.HttpServletResponse class. The scope of the object is request.
  • pageContext - An object that defines the JSP context of the page. Object scope - page
  • session - An object created by the container to identify the client, as well as store personal objects. Created by the container for the HTTP protocol and is an instance of the javax.servlet.http.HttpSession class.
  • application - An object associated with the configuration of the servlet corresponding to this JSP page. The object's scope is application.
  • out - An object containing the servlet's output stream. The information sent to this stream will be sent to the client. The object is an instance of the javax.servlet.jsp.JspWriter class. For example, most of the static template on a JSP page should ideally be written in the form of an appropriate set of out.println () commands. The object's scope is page.
  • config - Object associated with servlet configuration. Instance of the javax.servlet.ServletConfig class. For a JSP page, the scope of the config object is page.
  • page - The object associated with rendering this page. Scope - page

Action elements

Regardless of the type of document generated in response to a user request, in general, a JSP page contains text and tags. Obviously, the latter correspond to the type of the generated document: HTML, XML, etc. In addition, the body of a JSP page can contain fragments of Java code that must be part of the servlet received after translation: declarations, scriptlets, and expressions. The idea is to supplement the set of standard markup tags with special tags - action elements, behind which the developer of a business application can hide part of the program code related to the application, or some additional instructions.

Note that from the point of view of a layout specialist, action elements are the same tags as all the others, and therefore they are permissible. sharing with other elements:

Let's take a look at some of these elements.

Standard action elements

Standard action elements look like regular tags, the name of which begins with the jsp: character combination, for example ... In XML terminology, this means that the standard action elements in JSP technology belong to the jsp namespace.

jsp: useBean

The jsp: useBean element allows you to use objects in the JSP page that correspond to JavaBeans. Element contains a parameter that associates a unique identifier with the component. The latter will then be used when referring to this object:

This example creates an object of the com.myco class. In the future, to refer to it, it is enough to use the "customer" identifier. For instance:

<%= customer.getName() %>

By default, objects associated with a JavaBean are scoped to page by default. The developer of the JSP page can specify more long time the existence of a JavaBean by using the scope element when writing the jsp: useBean element. The possible values ​​for this attribute — page, request, session, and application — we discussed earlier when we talked about the scope of objects associated with a JSP page.

We will not cover the rest of the attributes of the jsp: useBean element. Here is just one more example of its use:

The internals of JavaBeans will be discussed in a separate article.

jsp: setProperty and jsp: getProperty

Any class must give access to some of its attributes and methods. The difference between the JavaBean element is that access to its attributes is unified and is implemented on the JSP page using the jsp: setProperty and jsp: getProperty elements.

The jsp: getProperty element takes a Bean instance, retrieves the value of the specified attribute, converts it to a string if necessary, and puts it in the data stream passed to the client. For example, according to the following entry

the generated document is filled with the value of the name property from the Bean instance with the identifier user.

The jsp: setProperty element, unlike the previous one, does not retrieve, but sets a new value for the attribute. For instance:

In addition to explicitly setting new values, the jsp: setProperty element allows you to set an object attribute with a value retrieved from a client request. For instance:

This record means that among the data received from the client is the login parameter and its value is passed to be placed in the name attribute of the Bean object with the identifier "user".

Finally, when the field names in the client request match the attribute names of the Bean, there is another option where all values ​​are migrated at once. For instance:

jsp: include

Like the include directive, this element allows you to put static and dynamic material from an external source into the body of a dynamically generated page. At the same time, although the material borrowed in this way is processed in the same context as current page, it is only given access to the output stream of the servlet. For example, code included in a JSP page should not access cookies or use its own headers that declare the encoding or document type.

The difference between the include directive and the jsp: include element is that the included material for it cannot be dynamic, and the search and processing of possible dynamic fragments is carried out not separately, but after inclusion, with the entire page.

An example of using the jsp: include element:

jsp: forward

This element allows you to redirect the further generation of a dynamic page to another JSP page, servlet, or use a prepared text for completion. For instance:

In the next, more complex example dynamic page ends with content text file whose name is taken from the someValue variable:

In conclusion, it should be noted that there are two main schemes for processing client requests:

In the first case, the processing of the client's request and the formation of a dynamic page in response are performed within a single JSP page or servlet. The latter, if necessary, can access JavaBeans or import material from external sources using the include directive or the jsp: include element.

In the second case, processing is carried out in two stages. First, control is passed to a servlet or JPS page that actually handles the request. For example, data is retrieved from a client request and placed into a database or attributes of certain objects. Control is then passed to a separate JSP page or servlet responsible for generating the dynamic page for subsequent transfer to the client. However, there does not have to be any relationship between processing a request and generating a new page. For example, it may just be a customer return to home page upon completion of any procedure.

Additional tag sets

Introduction

Textual markup protocols such as HTML have a highly regulated set of tags. At the same time, during the development of documents, there is often a need to use additional, special tags, which, although they were not declared in the corresponding specifications, but to a greater extent correspond to the subject area of ​​a business application. On the one hand, such additional or custom tags can be viewed as a kind of macros that will be replaced by an equivalent combination of standard tags before the document is sent to the client. Alternatively, a specific piece of code can be behind the custom tag. For example, a fairly common single tag might be a hit counter or a menu whose content depends on the role a given customer plays in a business process.

Building custom tags involves writing specific program code. JSP technology provides for placing this code in a separate program module - the custom tags library. Development of such libraries can be outsourced to companies. The JSP page is connected to a particular custom tag library using the previously described taglib directive. The specified directive binds the descriptor of the corresponding library with a specific prefix, which, in turn, identifies all custom tags from this library in the body of the JSP page. So, the directive

<%@ taglib uri="/exttags.tld" prefix="dscat" %>

declares that the JSP page uses a library of additional tags, each of which starts with the dscat prefix. For instance:

All Customers

The program code of this library is described by the exttags.tld descriptor. We will not dwell here on the rules for writing a library descriptor, but consider only one of the possible examples of its implementation:

1.0 1.2 dscat pageheader ru.view.tag.PageHeader

Creating a custom tag library

Custom tags without content processing

The code for supporting a custom tag is in a special way a written instance of a Java class that is invoked by the web container whenever it needs to render a JSP page containing the corresponding tag.

In the simplest case, to support a custom tag, you can take any of the business application classes and supplement it with methods that correspond to the Tag interface. If you do not need to use external objects, then TagSupport can be used as the base class. These and other standard classes and interfaces are found in the javax.servlet.jsp.tagext package.

An example of a class supporting a custom tag:

public CopyrightTag extends TagSupport (public int doStartTag () throws Exception (pageContext.getOut (). print (" © Copyright 2001"); return SKIP_BODY;) public int doEndTag () (return EVAL_PAGE;))

Methods of the class that processes the custom tag are called in a specific sequence. When processing reaches the opening custom tag in the JSP page, the doStartTag () method is called to process it. When processing reaches the corresponding end tag, the doEndTag () method is called. The doInitBody () and doAfterBody () methods are used to process the part of the JSP page that is enclosed between these two tags.

In addition to the fact that the doStartTag () method can do any kind of processing on the request, the value it returns is important. If it is SKIP_BODY, then the information enclosed between the corresponding opening and closing tags will be ignored, and the JSP processing of the page will immediately jump to the closing tag. For the content of the custom tag to still be processed, the medot must return EVAL_BODY_INCLUDE. Likewise, if the doEndTag () method returns SKIP_PAGE, then the rest of the JSP page after the end tag will be ignored. To prevent this from happening, the method must return EVAL_PAGE.

In some cases, it is necessary to show the content of a custom tag not once, but several times. In this case, the class that processes the tag must implement the IterationTag interface, or use the TagSupport class as a parent. To redo displaying the custom tag content one more time, the doStartTag and doAfterBody methods must return EVAL_BODY_AGAIN.

Custom tags with content handling

If access to the content of a custom tag is required, then the corresponding Java class must implement the BodyTag interface or inherit from the BodyTagSupport class. In either case, a class can implement the doInitBody and doAfterBody methods.

The doInitBody method is called immediately after the content of the tag is identified, but before it is processed. Typically this method is used when you need to initialize a class based on the content of a custom tag.

The doAfterBody method is called after the content of the custom tag has been processed. As in the previous section, the doAfterBody method can indicate whether to iterate over the tag content again. If necessary, the method should return EVAL_BODY_BUFFERED. Otherwise, it should return SKIP_BODY.

In addition to the two previous ones, the JSP technology provides for a call to the release method in order to allow the class supporting the custom tag to release the resources allocated to it, as well as perform other necessary actions to return to its original state.

The technology provides two methods directly for accessing the content of a custom tag: getString and getReader.

Attributes in custom tags

In addition to the information between the opening and closing tags, a custom tag can have some attributes that can also affect the order in which the client's request is processed. For each of these attributes in the class that implements the custom tag, the corresponding attribute must be specified, as well as two get method and set. For example, if the custom tag looks like

then the class implementing this custom tag should contain the following code:

from

Good bad

Top related articles