Choose your reason below and click on the Report button. This will alert our moderators to take action. Nifty 15, HAL 1, Market Watch. Mutual Funds. ET NOW. Tax How to file ITR. Tax Saving. ITR Forms. Income Tax Refund. Tax Exemption Limit. Income Tax Slabs. Insure Life Insurance. Health Insurance. Motor Insurance. Other Risk Covers.
Personal Finance News. Anirban Halder. Rate Story. Font Size Abc Small. Abc Medium. Abc Large. ET Spotlight. ITR Forms. Income Tax Refund. Tax Exemption Limit. Income Tax Slabs. Insure Life Insurance. Health Insurance. Motor Insurance.
Other Risk Covers. Personal Finance News. Rate Story. Font Size Abc Small. Abc Medium. Abc Large. By Dhirendra Kumar Returns, liquidity , volatility and predictability. In our routine way of looking at investments, this is all that matters. In our busy, result-oriented way of thinking, we only look at only what investments are and not for any deeper reasons of what they are. However, a certain type of investor steps back and starts thinking a little more deeply. He tells the stories of two small for him investments he made, both of which were among the most unusual assets that he bought.
One was a farm in rural Nebraska, the part of the US where he lives, and the other was a retail property in downtown New York City, a sort of a mini-mall with a number of shops. Both were bought during distress sales by lenders who were failing and thus both were bought at times when the outlook for the businesses was not good. Disclaimer: The opinions expressed in this column are that of the writer. The facts and opinions expressed here do not reflect the views of www. Read the now!
Indulge in digital reading experience of ET newspaper exactly as it is.
|Forex margin requirements calculator for fractions||899|
|Forex bid ask explained variation||151|
|Wicket keeping basics of investing||I coached Frenchy when he started at Nottingham. Q;Explain the meaning of ther term "long catches" in wicket keeping? ETPrime stories of the day Cybersecurity The gods of the metaverse are mistaken. Hi I am I've read lots and lots of articles and books about wicketkeeping coaching, and not one has mentioned the most important part: concentration.|
|Blogs about the forex market||I cannot bowl so this is a important trait for me. Fill in your details: Will be displayed Will not be displayed Will be displayed. You need to do more the field a few throws before play. If I played well then it would push Alan Knott, keep him on his toes, which is the objective source a reserve, and only benefits the team. Did you ever have a mentor or coach to bounce ideas off? This will alert our moderators to take action.|
|Pamm forex alpari review||647|
The same investors that panicked yesterday panic again, but this time they are flooding back into the market for fear of missing out on a big rally which they ironically create. Only one day later, Google's stock price soars by 4. Do you think Google's true value really changed so drastically in a two day period? Of course not. There is simply a lot of volatility in the short term, which is why we want you to understand a little about investor psychology, so you can avoid the herd.
In the example, the herd sold on the way down and bought on the way up. If you buy high and sell low you are guaranteed to lose money. Unfortunately we are programmed to act this way, your mind will try to get you to make stupid stock market moves whenever you are scared or stressed, you'll have to make a conscious effort to avoid these mistakes.
To avoid all of this unnecessary stress, master your own psychological impulses. Hold on to your winners for as long as you can, at least a year, and don't let short-term market volatility scare you into or out of the market. Long term investors win, short term investors lose, and that's not a theory, it's a fact. Also, avoid bouncing between strategies when the market changes, reacting to news, or trying to time the market by moving back and forth from cash to stocks.
If you understand your strategy and are good at implementing it, you should wind up with high quality stocks that you bought at a good price and that you can hold onto for a long period of time. Dollar Cost Averaging means investing a fixed amount of money on a regular basis. The benefit is that you are always buying more stock when prices are low since the market trend is usually upward.
The reason this is so important for you to learn is because most investors do the exact opposite. Don't you feel the urge to buy when the market is bullish and rising and feel the urge to wait or sell when the market is bearish and dropping? Most people do, and as a result they buy when prices are high and do nothing or sell when prices are low or falling.
This kind of behavior greatly increases your cost basis and decreases your returns, so avoid it, be a dollar-cost averager. Remember that even if the market tanks it always recovers for long term investors, and when it is low you will snatch up a lot of shares at bargain prices. As long as you are dollar-cost averaging you will always be buying shares at a cheaper price.
While this is actually a component of investor psychology, it's important enough to have earned spot 9 on our top 10 list of investing principles. Sounds silly doesn't it, why would any investor hold on to their losers and sell their winners? Oddly, this is what many people do, and not just beginners. Even seasoned investors will fall into this habit occasionally if they're not diligent about sticking to their strategy.
Let's first talk about holding on to losers, almost everyone has done this so it's an easier concept to absorb. We often put a lot of hard work into selecting investments. However, investing is a numbers game, we can't be right every time and we will inevitably pick losers now and then.
When this happens, rather than realizing that we either missed something when we did our research or that something has fundamentally changed about the company or the market, many of us still stubbornly believe that we made a good investment. Because we worked so hard to identify a good stock, we find it hard to believe that we were wrong.
Even if the price is dropping while our other investments are going up we hold onto it because we're sure the loss is only a temporary correction and that the stock will head back up very soon. This rarely ends well.
Eventually we realize that no recovery is in sight and we sell the stock back into the market at a much larger loss than we should have taken. On the other side of the equation, when we review our portfolio and see that an investment has done particularly well, we are often tempted to take a profit because we don't think that any company can sustain such exceptional performance for long. Stock investors are more likely to behave this way than fund investors since they are looking at individual stocks but it can happen to anyone.
Let's look at Google again since it's a company we've already used for several examples. As a result, there was an enormous amount of selling volume in April. Had Google's growth potential or business environment changed? No, the selling was simply early profit-taking by skittish investors.
Ouch, painful lesson. As painful as it is to take a loss, smart investors set sell limits for every investment that they buy. If it gets close to that limit, they reevaluate to see if they erred in their research or if something has fundamentally changed. Regardless of the situation, if the investment hits the sell limit, they get rid of it, they don't ever hold on hoping it will go up because they know their money will be better off working for them elsewhere. On the other side of the equation side, avoid selling winners by doing as much homework before you sell as you did before you bought.
If the company still meets all of the criteria for your strategy, isn't it still a winner and shouldn't you hold onto it? Trust your strategy and hold onto any investment that still meets all of your buy criteria, there is no limit to how high a stock can go so price appreciation should get you excited, not scare you to the sidelines. Don't throw good money after bad. If you hold onto losers or sell winners, you are not managing your money efficiently and this will kill your returns.
The easiest way to correct this behavior is to stay objective with every investing decision and stick to your strategy, never let your emotions make investing decisions for you. This is so true about everything in life and it's especially true about investing. As a beginner, you are probably overwhelmed by the amount of information you need to learn to become a savvy investor. This is a good time to point out an important fact.
Your confusion is a result of your lack of knowledge and from the overwhelming amount of new information being thrown at you, NOT because investing is complex and sophisticated. Don't stray from the keep it simple philosophy as you become a more seasoned investor.
You have to understand the basics of your strategy, but don't needlessly add complexity because you feel being a more sophisticated investor will make you more successful. Index investors choose funds that own the stocks of whatever index they'd like to track That's it, that's the whole strategy. You were expecting more?
Half of our Fund Street Monthly newsletter is dedicated to Index and ETF investing because it is one of the best strategies even though it is also one of the simplest. Bottom line, if you adhere to the 10 Basic Principles of Investing, always continue to learn, implement your strategy well, and stay abreast of changes in the market and the economy you will be a successful investor.
Have you heard of Peter Lynch? Invest in what you know. Sounds simple but there is a lot of wisdom in this advice. Lynch meant that in our everyday lives we tend to become experts in some field or another either because it relates to our career or because we use related products on a daily basis. For example, if you have been a pharmaceutical salesman for the past 15 years, you probably have picked up a lot of knowledge about the major companies, the industry, how a product is tested and marketed, not to mention detailed knowledge on any drugs that you have sold during your career.
This expertise is your foundation and gold mine as an investor. To emphasize this point, imagine you are the pharmaceutical rep described above and you are trying to decide between two different investments. The first is a profitable and established pharmaceutical company that you've been competing against for 15 years. Your friends think it's a boring stock and point out that their share price hasn't budged in five years while the market has made great gains.
They tell you that new drugs come out all the time, and remind you that this company has already released two this year without making any impression on investors or impact to the share price. However, you know that this pharmaceutical company has solid patents and recently received FDA approval for a cheaper generic version of a very expensive drug that your company makes.
Sales for your company's competing drug have plummeted as a result. You also know that this is a popular drug, many doctors will prescribe it to the elderly on a regular basis. You ask around different companies and reps in your industry and find that no one else has anything in testing or pending approval that can compete on a cost basis. Finally, this company is huge, they will have no trouble digging into their deep pockets to market and mass produce. The second potential investment is a tech IPO that your broker and a couple of your friends are really excited about.
Apparently they invented some type of technology that can improve the speed of all search engines and they just landed Google as a client, the major player in the search engine space. As a result of the Google deal, they are already making money which isn't always the case for many startup tech companies. You're seeing a lot of news about this IPO, it looks like it will be a hot stock since there's already so much buzz.
Your broker even offered to get you some IPO shares which will probably net you a nice profit on the very first day of trading. What would Peter Lynch do? He would buy the pharmaceutical company every single time. Here's what you know. The well-established pharmaceutical company has a new patent protected drug that is already approved for sale by the FDA.
The tech company has an unproven product, investors don't even know if major search engines such as their new client, Google, will need or continue to use the technology. The drug is already proving itself by outselling you, the competition. You have no idea how well the tech company is equipped to compete and it sounds like they may be dependent on their one major client for survival, Google.
Not a strong position. Finally, there won't be any competitors for several years for the drug company because no one is even testing a competing product yet. What are the barriers to entry for the tech company, could one pop up tomorrow or could Google or Yahoo just make their own version of the technology? We certainly don't want you to get the impression that you should avoid every strategy, stock, or fund that you don't know much about. What we really want you to understand is that you should play to your strengths when you invest.
Invest in what you know when you can and when you want to try something new, take the time to learn a lot about it first. Ignoring this rule can ruin even great strategies. For example, a value investor is always looking for great bargains, i.
But if they buy companies that they know little about, more often than not they'll wind up with a stock that has done something to deserve a low share price and would have been best avoided. There is an enormous amount of information available for any stock you'd like to buy. Study the company, their competition, the industry, and anything else you can think of before you decide. This sounds like a lot of work but your portfolio will reward you generously in the form of profits if you do your homework.
One of the most common and costly mistakes that new investors make is not measuring their performance against an appropriate benchmark. Many don't compare to ANY benchmark, much less an appropriate one. What is the danger? The biggest drawback is you will never really know how well or poorly you are investing.
There are tons of them, they are easy to look up, and there are plenty of free tools available that will allow you to compare your performance to an index with just a couple of mouse clicks. We will provide a list of the most popular and which strategy they match in the chart below. The year is and all of your money is invested in Large Cap US companies. Pretty strong, right? The problem is that you have absolutely no basis of comparison. Now let's add some information and see how drastically it can change the picture.
To add insult to injury, let's also throw in the possibility that your returns are much less because you selected highly volatile companies and a few tanked. Regardless of your strategy or goals, you should always compare your month-over-month and annual performance to an appropriate benchmark.
We already mentioned that if you don't compare you'll never know if you're improving as an investor. Another major reason is to see how well you are implementing your investing strategy. For example, if you've chosen to purchase large growth stocks and technology stocks a good index to compare too would be the NASDAQ If you outperform the index for several years in a row, then you have proven that you are good at implementing your strategy of buying high potential growth and technology stocks.
Unfortunately, many people think that buying an index fund is like throwing in the towel. They feel this way because it means accepting the market returns, index investors aren't really implementing any traditional investment strategy. If you can't beat 'em, join 'em. No problem. That means you'll look at more than one index and you should compare each investment or group of investments to their relevant index. Germany's version of the Dow. This is a Blue Chip stock index consisting of 30 major German companies.
Popular German Index and a good measure of the health of the German economy. Good benchmark for any large cap German based stocks. Best-known and most widely followed market indicator in the world and a good measure of US economic health.
Perfect benchmark for Blue Chip, large cap and Income Investors. Good benchmark for any large cap UK based stocks. Popular Hong Kong Exchange index and a good measure of China's economic health. Good benchmark for any large cap Chinese stocks. Index of foreign stocks. Focuses only on developed countries in Europe, Asia and the far east.
Good benchmark for anyone that has a portion of their portfolio allocated to developed foreign countries. Good benchmark for anyone that has a portion of their portfolio allocated to developing foreign countries. This index is designed to reflect the overall market, there is no specific weighting of industries.
Most watched index of Asian stocks and a good measure of Asia's economic health. Good benchmark for any Asian stocks. One of the most widely followed indices and a good measure of US economic health. Good benchmark for any large cap US stocks. Wicket and the other component oriented frameworks bring to web development the same kind of abstraction that GUI frameworks offer when we build a desktop application. Most of those kind of frameworks hide the details of the HTTP protocol and naturally solve the problem of its stateless nature.
At this point some people may still wonder why OOP is so important for web development and what benefits it can bring to developers. Web pages are objects : web pages are not just text files sent back to the client. They are object instances and we can harness OOP to design web pages and their components.
With Wicket we can also apply inheritance to HTML markup in order to build a consistent graphic layout for our applications we will see markup inheritance in chapter 4. They are Java objects and they can keep a state inside them and reference other objects. We can stop worrying about keeping track of user data stored inside the HttpSession and we can start managing them in a natural and transparent way. Testing web applications is much easier : since pages and components are pure objects, you can use JUnit to test their behavior and to ensure that they render as expected.
Wicket has a set of utility classes for unit testing that simulate user interaction with web pages, hence we can write acceptance tests using just JUnit without any other test framework unit testing is covered in chapter Wicket is not the only component oriented framework available in the Java ecosystem.
Moreover, as any other Apache project, Wicket is developed paying great attention to user feedback and to suggested features. This is clearly in contrast with the concept of separation between presentation and business logic and it leads to a more confusing code in our pages. All we have to do is to attach our components Java instances to the HTML tags using a simple tag attribute called wicket:id we will shortly see how to use it.
With Wicket we can easily use JavaBeans and POJO in our web tier : one of the most annoying and error-prone tasks in web development is collecting user input through a form and keeping form fields updated with previously inserted values. This usually requires a huge amount of code to extract input from request parameters which are strings , parse them to Java types and store them into some kind of variable.
And this is just half of the work we have to do as we must implement the inverse path load data from Java to the web form. Moreover, most times our forms will use a JavaBean or a POJO as a backing object, meaning that we must manually map form fields with the corresponding object fields and vice versa.
Wicket comes with an intuitive and flexible mechanism that does this mapping for us without any configuration overhead using a convention over configuration approach and in a transparent way. Chapter 10 will introduce a Wicket model concept and we will learn how to harness this entity with forms.
No complex XML needed : Wicket was designed to minimize the amount of configuration files needed to run our applications. No XML file is required except for the standard deployment descriptor web. See Chapter 4 for more details. Wicket allows us to design our web pages in terms of components and containers, just like AWT does with desktop windows.
In both frameworks we find a base class for GUI components called Component. Both frameworks promote the reuse of presentation code and GUI elements building custom components. Even if Wicket already comes with a rich set of ready-to-use components, building custom components is a common practice when working with this framework.
Inside this archive we can find the distribution jars of the framework. Each jar corresponds to a sub-module of the framework. The following table reports these modules along with a short description of their purpose and with the related dependencies:.
Contains the main classes of the framework, like class Component and Application. Contains utility classes and components to help developers with tasks such as debugging, class inspection and so on. Contains a vast set of built-in components to build a rich UI for our web application Ajax support is part of this module.
This module provides common classes to support Inversion Of Control. This module provides integration with the dependency injection framework developed by Google. This module provides panels and utility class to integrate Wicket with Velocity template engine. This module provides panels and utility class to integrate Wicket with Java Management Extensions. Please note that the core module depends on the utility and request modules, hence it cannot be used without them.
In this chapter we will see a classic Hello World! Since this is the first example of the guide, before looking at Java code we will go through the common artifacts needed to build a Wicket application from scratch. A Wicket application is a standard Java EE web application, hence it is deployed through a web. The content of web. WicketFilter which dispatches web requests to our Wicket application:.
In the xml above we have mapped every URL to our Wicket filter. If we are using Servlet 3 or a later version, we can of course use a class in place of web. The following example uses annotation WebFilter. If we look back at web.
This value must be the fully qualified class name of a subclass of org. WebApplication which provides a closer integration with servlet infrastructure. One of these methods is getHomePage that must be overridden as it is declared abstract:. As you may guess from its name, this method specifies which page to use as a homepage for our application. Another important method is init :. The Application class exposes its settings grouping them into interfaces you can find them in package org.
We can access these interfaces through getter methods, which will be gradually introduced in the next chapters when covering related settings. We will give more details about this method in chapter 9. The content of the application class from the HelloWorldExample project is the following:. The home page of the application is the HomePage class. In the next paragraph we will see how this page is implemented and what conventions we have to follow to create a page in Wicket.
To complete our first Wicket application we must explore the home page class that is returned by the Application 's method getHomePage seen above. In Wicket a web page is a subclass of org. This file is a regular plain HTML file its extension must be html. By default this HTML file must have the same name of the related page class and must be in the same package:.
We will cover this topic later in chapter Apart from subclassing WebPage , HomePage defines a constructor that adds a Label component to itself. Method add Component component is inherited from ancestor class org. MarkupContainer and is used to add children components to a web page.
Class org. Label is the simplest component shipped with Wicket. It just inserts a string the second argument of its constructor inside the corresponding HTML tag. Just like any other Wicket component, Label needs a textual id 'helloMessage' in our example to be instantiated. This tag must have a special attribute called wicket:id and its value must be identical to the component id comparison is case-sensitive! We can see that the wicket:id attribute is set according to the value of the component id.
If we run this example we will see the text Hello WicketWorld! The basic form of interaction offered by web applications is to navigate through pages using links. In HTML a link is basically a pointer to another resource that most of the time is another page. Wicket implements links with component org. Link , but due to the component-oriented nature of the framework, this component is quite different from classic HTML links.
In the following example we have a page with a Link containing an empty implementation of onClick :. By default after onClick has been executed, Wicket will send back to the current page to the client web browser. If we want to navigate to another page we must use method setResponsePage of class Component :.
In the example above we used a version of setResponsePage which takes as input the class of the target page. In this way a new instance of AnotherPage will be created each time we click on the link. The other version of setResponsePage takes in input a page instance instead of a page class:. The difference between using the first version of setResponsePage rather than the second one will be illustrated in chapter 8 , when we will introduce the topic of stateful and stateless pages.
For now, we can consider them as equivalent. Since Wicket 8 is built on Java 8, we can choose to leverage lambda expressions to specify handler method:. Factory class ComponentFactory is provided by the WicketStuff project. You can find more information on this project, as well as the instructions to use its modules, in Appendix B.
Wicket comes with a rich set of link components suited for every need links to static URL, Ajax-enhanced links, links to a file to download, links to external pages and so on. We will see them in chapter In this chapter we have seen the basic elements that compose a Wicket application. We have started preparing the configuration artifacts needed for our applications.
As promised in chapter 2. Before going ahead with more advanced topics, we will see how to maintain a consistent layout across our site using Wicket and its component-oriented features. There was a time in the 90s when Internet was just a buzzword and watching a plain HTML page being rendered by a browser was a new and amazing experience.
Over the years this tag has almost disappeared from our code and it survives only in few specific domains. For example is still being used by JavaDoc. Then, we manually insert these areas in every page including the appropriate markup fragments.
In this chapter we will see how to use Wicket to build a site layout. The sample layout we will use is a typical page layout consisting of the following areas:. Once we have chosen a page layout, our web designer can start building up the site theme. The result is a beautiful mock of our future web pages. Over this mock we can map the original layout areas:.
Now in order to have a consistent layout across all the site, we must ensure that each page will include the layout areas seen above. With an old template-based approach we must manually put them inside every page. If we were using JSP we would probably end up using include directive to add layout areas in our pages. We would have one include for each of the areas except for the content :. The need of ensuring a consistent layout across our pages unveiled a serious limit of the HTML: the inability to apply inheritance to web pages and their markup.
One of the goals of Wicket is to overcome this kind of limit. As we have seen in the previous chapter, Wicket pages are pure Java classes, so we can easily write a page which is a subclass of another parent page. But in Wicket inheritance is not limited to the classic object-oriented code inheritance.
This type of inheritance is called markup inheritance. Markup inheritance comes in handy for page layout management as it helps us avoid the burden of checking that each page conforms to the site layout. However to fully take advantage of markup inheritance we must first learn how to use another important component of the framework that supports this feature: the panel.
It shares a common ancestor class with WebPage class, which is org. MarkupContainer :. MarkupContainer implements a full set of methods to manage children components. The basic operations we can do on them are:. The string parameter is the id of the component or its relative path if the component is nested inside other MarkupContainers. This path is a colon-separated string containing also the ids of the intermediate containers traversed to get to the child component.
Component MyPanel is a custom panel containing only a label having "name" as id. Under those conditions we could retrieve this label from the container page using the following path expression:. This can be done in the old way pre-Wicket 8 using method iterator or using visitor pattern with method visitChildren.
Starting from Wicket 8 the same task can be accomplished using the stream object returned by methods stream which contains only the direct children and streamChildren which contains all children. Both Panel and WebPage have their own associated markup file which is used to render the corresponding component. If such file is not provided, Wicket will apply markup inheritance looking for a markup file through their ancestor classes.
When a panel is attached to a container, the content of its markup file is inserted into its related tag. While panels and pages have much in common, there are some notable differences between these two components that we should keep in mind. The main difference between them is that pages can be rendered as standalone entities while panels must be placed inside a page to be rendered.
Another important difference is the content of their markup file: for both WebPage and Panel this is a standard HTML file, but Panel uses a special tag to indicate which part of the whole file will be considered as markup source. A markup file for a panel will typically look like this:.
The space outside this tag can be used by both web developers and web designers to place some mock HTML to show how the final panel should look like. In chapter 5. Now we will build a reusable template page for our web application combining pages and panels. The code examples are from project MarkupInheritanceExample. For example given the header area.
For each layout area we will build a panel like the one above that holds the appropriate HTML markup. In the end we will have the following set of panels:. Now we can build a generic template page using our brand new panels. Its markup is quite straightforward :. The HTML code for this page implements the generic left-menu layout of our site.
The page class contains the code to physically assemble the page and panels:. Our template page is ready to be used. Now all the pages of our site will be subclasses of this parent page and they will inherit the layout and the HTML markup. They will only substitute the Label inserted as content area with their custom content.
As final example we will build the login page for our site. We will call it SimpleLoginPage. First, we need a panel containing the login form. This will be the content area of our page. We will call it LoginPanel and the markup is the following:. The form of this panel is for illustrative purpose only. We will see how to work with Wicket forms in chapters 11 and You can see the final page in the following picture:.
Here is an example of child page markup:. Considering the two pages seen above, the final markup generated for child page will be the following:. Going forward with our example we can build a login page creating class SimpleLoginPage which extends the JugTemplate page, but with a related markup file like this:. Wicket applies inheritance also to HTML markup making layout management much easier and less error-prone. Defining a master template page to use as base class for the other pages is a great way to build a consistent layout and use it across all the pages on the web site.
During the chapter we have also introduced the Panel component, a very important Wicket class that is primarily designed to let us divide our pages in smaller and reusable UI components. Many Wicket newbies are initially scared by its approach to web development because they have the impression that the component-oriented nature of the framework prevents them from having direct control over the generated markup.
This is due to the fact that many developers come from other server-side technologies like JSP where we physically implement the logic that controls how the final HTML is generated. This chapter will prevent you from having any initial misleading feeling about Wicket showing you how to control and manipulate the generated HTML with the built-in tools shipped with the framework. At the end of the previous chapter we have seen how to hide a component calling its method setVisible.
In a similar fashion, we can also decide to disable a component using method setEnabled. Class Component provides two getter methods to determine if a component is visible or enabled: isVisible and isEnabled. Even if nothing prevents us from overriding these two methods to implement a custom logic to determine the state of a component, we should keep in mind that methods isVisible and isEnabled are called multiple times before a component is fully rendered.
Hence, if we place non-trivial code inside these two methods, we can sensibly deteriorate the responsiveness of our pages. As we will see in the next chapter, class Component provides method onConfigure which is more suited to contain code that contributes to determine component states because it is called just once during rendering phase of a request. This class extends org. Behavior and can be added to any component via the Component 's add method. Class Behavior is used to expand component functionalities and it can also modify component markup.
With method setOutputMarkupId boolean output we can decide if the id attribute will be rendered or not in the final markup by default is not rendered. The value of this attribute will be automatically generated by Wicket and it will be unique for the entire page. If we need to specify this value by hand, we can use method setMarkupId String id.
The value of the id can be retrieved with method getMarkupId. Wicket generates markup ids using an instance of interface org. The default implementation is org. DefaultMarkupIdGenerator and it uses a session-scoped counter to generate the final id. A different generator can be set with the markup settings class org. MarkupSettings available in the application class:. Creating custom panels is a great way to handle complex user interfaces.
However, sometimes we may need to create a panel which is used only by a specific page and only for a specific task. In situations like these org. WebMarkupContainer component is better suited than custom panels because it can be directly attached to a tag in the parent markup without needing a corresponding html file hence it is less reusable. Suppose that this page shows a notification box where user can see if new messages have arrived. This box must be hidden if there are no messages to display and it would be nice if we could handle it as if it was a Wicket component.
Under those conditions we can consider using a WebMarkupContainer component rather than implementing a new panel. The code needed to handle the information box inside the page could be the following:. As you can see in the snippet above we can handle our information box from Java code as we do with any other Wicket component.
Note also that we may later choose to make information box visible by calling setVisible true , upon for example an AJAX request we will be covering such an example in chapter Another circumstance in which we may prefer to avoid the creation of custom panels is when we want to conditionally display small fragments of markup in a page.
In this case if we decided to use panels, we would end up having a huge number of small panel classes with their related markup file. To better cope with situations like this, Wicket defines component Fragment in package org. In addition to the component id, Fragment 's constructor takes as input also the id of the fragment and a reference to its container. When the page is rendered, markup inside the fragment will be inserted inside div element :.
Fragments can be very helpful with complex pages or components. Please check your mail to activate your user profile. Instead of displaying this message with a new component or in a new page, we can define two fragments: one for the initial form and one to display the confirmation message. The second fragment will replace the first one after the form has been submitted:. When we bind a component to its corresponding tag we can choose to get rid of this outer tag in the final markup.
If we call method setRenderBodyOnly true on a component Wicket will remove the surrounding tag. Our data are rarely displayed alone without a caption or other graphic elements that make clear the meaning of their value. For example:. All we have to do is to put the involved markup inside this tag.
Now if component totalAmount is not visible, its description Total amount: will be automatically hidden. Component org. Border is a special purpose container created to enclose its tag body with its related markup. Just like panels and pages, borders also have their own markup file which is defined following the same rules seen for panels and pages. Now if we attached this border to the following tag.
Border can also contain children components which can be placed either inside its markup file or inside its corresponding HTML tag. In this chapter we have seen the tools provided by Wicket to gain complete control over the generated HTML. With classic server-side technologies like PHP or JSP we use loops like while or for inside our pages to achieve this result.
To perform this task Wicket provides a special-purpose family of components called repeaters and designed to repeat their markup body to display a set of items. Just like applets and servlets, also Wicket components follow a lifecycle during their existence. In this chapter we will analyze each stage of this cycle and we will learn how to make the most of the hook methods that are triggered when a component moves from one stage to another.
Rendering: components are prepared for rendering and generate markup. If a component contains children i. Removed: this stage is triggered when a component is explicitly removed from its component hierarchy, i. This stage is facultative and is never triggered for pages. Detached: after request processing has ended all components are notified to detach any state that is no longer needed.
Class Component comes with a number of hook methods that can be overridden in order to customize component behavior during its lifecycle. In the following table these methods are grouped according to the stage in which they are invoked and they are sorted by execution order :. A component is instantiated by application code or by Wicket in case of bookmarkable page and added to a parental component.
When we override this method we have to call super. This stage is reached each time a component is rendered, typically when a page is requested or when the component or one of its ancestors is refreshed via AJAX. Method onConfigure has been introduced in order to provide a good point to manage the component states such as its visibility or enabled state. This method is called on all components whose parent is visible. As stated in chapter 6. On the contrary method onBeforeRender see the next paragraph is not indicated for this task because it will not be invoked if component visibility is set to false.
The most important hook method of this stage is probably onBeforeRender. This method is called on all visible components before any of them are rendered. In the next example project LifeCycleStages we will create a page which alternately displays two different labels, swapping between them each time it is rendered:. The code inside onBeforeRender is quite trivial as it just checks which label among firstLabel and secondLabel is currently inserted into the component hierarchy and it replaces the inserted label with the other one.
This method is also responsible for invoking children onBeforeRender. So if we decide to override it, we have to call super. This method gives all components the possibility to add items to the page header through its argument of type org. Method onComponentTag ComponentTag is called to process a component tag, which can be freely manipulated through its argument of type org. Just like we do with onInitialize , if we decide to override onComponentTag we must remember to call the same method of the super class because also this class may also customize the tag.
Overriding onComponentTag is perfectly fine if we have to customize the tag of a specific component, but if we wanted to reuse the code across different components we should consider to use a behavior in place of this hook method. We have already seen in chapter 6. In chapter Just like onComponentTag it takes as input a ComponentTag parameter representing the component tag.
In addition, we also find a MarkupStream parameter which represents the page markup stream that will be sent back to the client as response. For example taken from project OnComponentTagExample we can display a brief description instead of the body if the label component is disabled:.
Called on each rendered component immediately after it has been rendered - onAfterRender will even be called when rendering failed with an exception. This stage is entered when a component is removed from its container hierarchy. The only hook method for this phase is onRemove. If our component still holds some resources needed during rendering phase, we can override this method to release them. Once a component has been removed we are free to add it again to the same container or to a different one.
Starting from version 6. Please note that while onInitialize is called only the very first time a component is added, onReAdd is called every time it is re-added after having been removed. When a request has finished, the page and all its contained components move a the detached stage:.
The hook method onDetach notifies each component that it should release all held resources no longer needed until the next request. In this chapter we have seen which stages compose the lifecycle of Wicket components and which hook methods they provide. Overriding these methods we can dynamically modify the component hierarchy and we can enrich the behavior of our custom components. This chapter explains how Wicket manages page instances, underlining the difference between stateful and stateless pages.
The chapter also introduces some advanced topics like Java Serialization and multi-level cache. However, to understand what you will read you are not required to be familiar with these concepts. Wicket pages can be divided into two categories: stateful and stateless pages.
Stateful pages are those which rely on user session to store their internal state and to keep track of user interaction. Wicket automatically assigns a session to the user the first time a stateful page is requested. Page versions are stored into user session using Java Serialization mechanism.
If we want to know whether a page is stateless or not, we can call the isPageStateless method of class Page. These rules are illustrated in paragraph 8. A new page version is created when a stateful page is requested for the first time or when an existing instance is modified for example changing its component hierarchy. To identify each page version Wicket uses a session-relative identifier called page id. This is a unique number and it is increased every time a new page version is created.
In the final example of the previous chapter project LifeCycleStages , you may have noticed the number appended at the end of URL. This number is the page id we are talking about:. This is necessary because Wicket creates a new page version only if the page is modified before its method onBeforeRender is invoked. The code of the new home page is the following:.
If we press the back button the page version previously rendered and serialized will be retrieved i. As we have stated at the beginning of this chapter, page versions are stored using Java serialization, therefore every object referenced inside a page must be serializable.
In paragraph To retrieve a specific page version in our code we can use class org. PageReference by providing its constructor with the corresponding page id:. If for any reason we need to switch off versioning for a given page, we can call its method setVersioned false.
Starting from version 1. Wicket serializes pages using an implementation of interface org. However on internet we can find other interesting serialization libraries like Kryo. We can access this class inside the method init of the class Application using the getFrameworkSettings method :. A serializer based on Kryo library and another one based on Fast are provided by the WicketStuff project. By default Wicket persists versions of pages into a session-relative file on disk, but it uses a two-level cache to speed up the access.
The first level of the cache contains all the pages involved in the current requests as we may visit more than one page during a single request, for example if we have been redirected with setResponsePage. The second level cache stores the last rendered page into a session-scoped variables.
Wicket allows us to set the maximum size of the file used to store pages with setting class org. The Bytes parameter is the maximum size allowed for this file:. Bytes is an utility class provided by Wicket to express size in bytes for further details refer to the JavaDoc.
Page instances are not kept in the user session forever. They can be discarded when the limit set with the setMaxSizePerSession method is reached or more often when user session expires. When we ask Wicket for a page id corresponding to a page instance removed from the session, we bump into a PageExpiredException and we get the following default error page:.
This error page can be customized with the setPageExpiredErrorPage method of class org. ApplicationSettings :. The page class provided as custom error page must have a public constructor with no argument or a constructor that takes as input a single PageParameters argument the page must be bookmarkable as described in paragraph For example consider the public area of a site or a login page: in those cases a stateful page would be a waste of resources or even a security threat, as we will see in paragraph paragraph All its children components and behaviors are in turn stateless, which means that their method isStateless must return true.
In order to comply with the second requirement it could be helpful to check if all children components of a page are stateless. To do this we can leverage method visitChildren and the visitor pattern to iterate over components and test if their method isStateless actually returns true :. Alternatively, we could use the StatelessComponent utility annotation along with the StatelessChecker class they are both in package org.
To use StatelessComponent annotation we must first add the StatelessChecker to our application as a component render listener:. A page can be also explicitly declared as stateless setting the appropriate flag to true with the setStatelessHint true method. This method will not prevent us from violating the requirements for a stateless page, but if we do so we will get the following warning log message:. In this chapter we have seen how page instances are managed by Wicket.
We have learnt that pages can be divided into two families: stateless and stateful pages. Knowing the difference between the two types of pages is important to build the right page for a given task. However, to complete the discussion about stateless pages we still have to deal with two topics we have just outlined in this chapter: class PageParameters and bookmarkable pages.
The first part of chapter 10 will cover these missing topics. For example this is necessary if we want to store an arbitrary parameter in the user session. Wicket provides wrapper classes that allow us to easily access to web entities without the burden of using the low-level APIs of Java Servlet Specification. Beside configuring and initializing our application, the Application class is responsible for creating the internal entities used by Wicket to process a request.
These entities are instances of the following classes: RequestCycle , Request , Response and Session. The next paragraphs will illustrate each of these classes, explaining how they are involved into request processing. The Request and Response classes are located in package org. Both classes are declared as abstract but if our application class inherits from WebApplication it will use their sub classes ServletWebRequest and ServletWebResponse , both of them located inside the package org.
If we need to access these low-level objects, we can call Request 's method getContainerRequest and Response 's method getContainerResponse. RequestCycle is the entity in charge of serving a web request. Our application class creates a new RequestCycle on every request with its method createRequestCycle request, response. Instead, we must build a request cycle provider implementing interface org. The current running request cycle can be retrieved at any time by calling its static method RequestCycle.
Strictly speaking this method returns the request cycle associated with the current or local thread, which is the thread that is serving the current request. A similar get method is also implemented in classes org. Application as we have seen in paragraph 4.
Session in order to get the application and the session in use by the current thread. Component provides the getRequestCycle method which is a convenience method that internally invokes RequestCycle. In order to process a request, RequestCycle delegates the task to another entity which implements interface org. There are different implementations of this interface, each suited for a particular type of requested resource a page to render, an AJAX request, an URL to an external page, etc.
IRequestMapper interface. The mapping interface defines the getCompatibilityScore Request request method which returns a score indicating how compatible the request mapper is for the current request. RequestCycle will choose the mapper with the highest score and it will call its mapRequest Request request method to get the proper handler for the given request.
Once RequestCycle has resolved a request handler, it invokes its method respond IRequestCycle requestCycle to start request processing. The following sequence diagram recaps how a request handler is resolved by the RequestCycle :.
Developers can create additional implementations of IRequestMapper and add them to their application via the mount IRequestMapper mapper method of the WebApplication class. The overloaded urlFor method from above also has a corresponding version that returns an instance of org. Url instead of a CharSequence. This version has the prefix 'map' in its name i. The RequestCycle class contains the implementation of the setResponsePage method we use to redirect a user to a specific page see paragraph 4.
The namesake method of class org. Component is just a convenience method that internally invokes the actual implementation on current request cycle:. The RequestCycle comes with some hook methods which can be overridden to perform custom actions when request handling reaches a specific stage. These methods are:. The default implementation of this method invokes detach on the current session the Session class will be shortly discussed in paragraph 9. A more flexible way to interact with the request processing is to use the listener interface org.
In addition to the three methods already seen for RequestCycle, this interface offers further hooks into request processing:. To use the request cycle listeners we must add them to our application which in turn will pass them to the new RequestCycle 's instances created with createRequestCycle method:. The getRequestCycleListeners method returns an instance of class org. This class is a sort of typed collection for IRequestCycleListener and it also implements the Composite pattern.
In Wicket we use class org. Session to handle session-relative informations such as client informations, session attributes, session-level cache seen in paragraph 8. In addition, we know from paragraph 8.
This method is not declared as final, hence it can be overridden if we need to use a custom implementation of the Session class. By default if our custom application class is a subclass of WebApplication , method newSession will return an instance of class org. As we have mentioned talking about RequestCycle , also class Session provides a static get method which returns the session associated to the current thread. Similar to the RequestCycle , class org.
Session also offers support for listener entities. With Session these entities must implement the callback interface org. ISessionListener which exposes only the onCreated Session session method. As you might guess from its name, this method is called when a new session is created. Session listeners must be added to our application using a typed collection, just like we have done before with request cycle listeners:.
The Session class handles session attributes in much the same way as the standard interface javax. The following methods are provided to create, read and remove session attributes:. If the session already contains an attribute with the same name, the new value will replace the existing one. The value must be a serializable object. Wicket will automatically add a prefix to the name of the attributes. If for any reason we need to directly access to the underlying HttpSession object, we can retrieve it from the current request with the following code:.
Using the raw session object might be necessary if we have to set a session attribute with a particular name without the prefix added by Wicket. One of the administrative tools provided by Tomcat is a page listing all the active user sessions of a given web application:.
Instead, we must use the raw HttpSession and set our attributes on it:. Nonetheless, even under these conditions, a temporary session object is created to process each request but it is discarded at the end of the current request. To know if the current session is temporary, we can use the isTemporary method:.
If a session is not temporary i. This value will be null if the session is temporary. Although Wicket is able to automatically recognize when it needs to replace a temporary session with a permanent one, sometimes we may need to manually control this process to make our initially temporary session permanent. The code of the two pages is as follows:.
Again, we kept page logic very simple to not over-bloat the example with unnecessary code. If the home page has not invoked this method, the session with its attribute would have been discarded at the end of the request and the page DisplaySessionParameter would have displayed an empty value in its label.
Once a user has finished using our web application, she must be able to log out and clean any session data. To be sure that a permanent session will be discarded at the end of the current request, class Session provides the invalidate method. If we want to immediately invalidate a given session without waiting for the current request to complete, we can invoke the invalidateNow method.
JavaServer Pages Specification1 defines 4 scopes in which a page can create and access a variable. These scopes are:. The lifespan of these variables is at most equal to the one of the related request. They are discarded when the full response has been generated or when the request is forwarded somewhere else. Variables declared in this scope can be used by any page of a given web application. Metadata is quite similar to a Java Map in that it stores pairs of key-value objects where the key must be unique.
The key used for metadata is an instance of class org. To put an arbitrary object into metadata we must use the setMetaData method which takes two parameters as input: the key used to store the value and the value itself. If we are using metadata with classes Session or Component, data object must be serializable because Wicket serializes both session and component instances.
This constraint is not applied to metadata of classes Application and RequestCycle which can contain a generic object. In any case, the type of data object must be compatible with the type parameter T specified by the key. In the following example we set a java. Wicket uses a number of custom exceptions during the regular running of an application.
We have already seen PageExpiredException raised when a page version is expired. We will see them later in the next chapters. All the other exceptions raised during rendering phase are handled by an implementation of org. IExceptionMapper which by default is class org. To use a custom internal error page we can change application settings like this:. Developers can also decide to use a custom exception mapper instead of DefaultExceptionMapper. To do this we must override Application 's method getExceptionMapperProvider :.
The method returns an instance of org. IProvider that should return our custom exception mapper. To control the behavior in Ajax requests the application may use org. By default if an error occurs during the processing of an Ajax request Wicket will render the configured error page. By configuring org. In this chapter we had a look at how Wicket internally handles a web request. Entities like Application and Session will come in handy again when we will tackle the topic of security in chapter However this component alone is not enough to build all possible kinds of links we may need in our pages.
Therefore, Wicket offers other link components suited for those tasks which can not be accomplished with a basic Link. Besides learning new link components, in this chapter we will also see how to customize the page URL generated by Wicket using the encoding facility provided by the framework and the page parameters that can be passed to a target page. A common practice in web development is to pass data to a page using query string parameters like? Wicket offers a more flexible and object oriented way to do this with models we will see them in the next chapter.
However, even if we are using Wicket, we still need to use query string parameters to exchange data with other Internet-based services. Consider for example a classic confirmation page which is linked inside an email to let users confirm important actions like password changing or the subscription to a mailing list. This kind of page usually expects to receive a query string parameter containing the id of the action to confirm.
Query string parameters can also be referred to as named parameters. In Wicket they are handled with class org. Here is a snippet to illustrate the usage of PageParameters:. Base class Page comes with a constructor which takes as input a PageParameters instance.
In the following example taken from the PageParametersExample project we have a home page with a link to a second page that uses a version of setResponsePage method that takes as input also a PageParameters to build the target page named PageWithParameters.
The code for the link and for the target page is the following:. At first glance the URL above could seem a little weird, except for the last part which contains the two named parameters used to build the target page. This kind of URL is called bookmarkable because it can be saved by the users as a bookmark and accessed at a later time. A bookmarkable URL is composed by a fixed prefix which by default is bookmarkable and the qualified name of the page class org.
PageWithParameters in our example. Segment wicket is another fixed prefix added by default during URL generation. Besides named parameters, Wicket also supports indexed parameters. These kinds of parameters are rendered as URL segments placed before named parameters. The URL above contains two indexed parameters foo and bar and a query string consisting of the page id and a named parameter baz. Just like named parameters also indexed parameters are handled by the PageParameters class.
As their name suggests, indexed parameters are identified by a numeric index and they are rendered following the order in which they have been added to the PageParameters. The following is an example of indexed parameters:. Project PageParametersExample comes also with a link to a page with both indexed parameters and a named parameter:.
A link to a bookmarkable page can be built with the link component org. BookmarkablePageLink :. Bookmarkable pages can be linked directly inside markup files without writing any Java code. The key part of the markup above is the href attribute which must contain the package-relative path to a page.
The home page is inside package org. This package hierarchy is reflected by the href attributes: in the first anchor we have a link to the home page itself while the second anchor points to page SubPackagePage which is placed into sub package anotherPackage. Absolute paths are supported as well and we can use them if we want to specify the full package of a given page. For example the link to SubPackagePage could have been written in the following more verbose way:.
Since Wicket uses plain HTML markup files as templates, we can place an anchor to an external page directly inside the markup file. When we need to dynamically generate external anchors, we can use link component org. In order to build an external link we must specify the value of the href attribute using a model or a plain string.
In the next snippet, given an instance of Person, we generate a Google search query for its full name:. If we need to specify a dynamic value for the text inside the anchor, we can pass it as an additional constructor parameter:.
Component Link has a stateful nature, hence it cannot be used with stateless pages. To use links with these kinds of pages Wicket provides the convenience org. StatelessLink component which is basically a subtype of Link with the stateless hint set to true. Please keep in mind that Wicket generates a new instance of a stateless page also to serve stateless links, so the code inside the onClick method can not depend on instance variables.
The printed value will always be zero because a new instance of the page is used every time the user clicks on the statelessLink link. Having structured URLs in our site is a basic requirement if we want to build an efficient SEO strategy, but it also contributes to improve user experience with more intuitive URLs.
Wicket provides two different ways to control URL generation. In the next paragraphs we will learn both of these two techniques. With Wicket we can mount a page to a given path in much the same way as we map a servlet filter to a desired path inside file web. The path provided to mountPage will be used to generate the URL for any page of the specified class:.
Under the hood the mountPage method mounts an instance of the request mapper org. MountedMapper configured for the given path:. The path specified for mounted pages can contain dynamic segments which are populated with the values of the named parameters used to build the page.
These segments are declared using special segments called parameter placeholders. Consider the path used in the following example:. The path used above is composed by three segments: the first and the last are fixed while the second will be replaced by the value of the named parameter foo that must be provided when the page MountedPageWithPlaceholder is instantiated:. If the named parameter for an optional placeholder is missing, the corresponding segment is removed from the final URL:.
Whether it's batting tips from his coach, Dhoni always learns. You must always learn about investments, before you invest your hard earned. By Dhirendra Kumar Returns, liquidity, volatility and predictability. In our routine way of looking at investments, this is all that matters. Every smart investor should know about these 5 parallels between cricket & investing! Synopsis. The Income Plus option of the HDFC Life Click 2.