Struts has different categories of tags which are used within JSP views:
Control tags
Data tags Non-Form tags |
Form tags
Ajax tags
|
The Linux and Mobile Solution Provider
Struts has different categories of tags which are used within JSP views:
Control tags
Data tags Non-Form tags |
Form tags
Ajax tags
|
We will, first of all, rewrite the BestSongs application using Struts:
Artists is slightly different from Countries as it require a parameter (countryid) to work properly. It therefore needs to implement the ParameterAware interface (and, consequently, implement the setParameters method).
Adding a logging interceptor
In Struts, interceptors are used to modify the workflow of an application.
In all Struts applications, there exist a default stack of interceptors (notice ParametersInterceptor, ActionMappingParametersInteceptor and StaticParametersInterceptor).
Also notice that there is an interceptor called “logger” but it is not part of the default stack.
Let us add the logger before the default stack and let us observe what happens:
<action name="Songs" class="com.knowledge7.strutsbestsongs.actions.Songs"> <interceptor-ref name="logger" /> <interceptor-ref name="defaultStack" /> <result>/Songs.jsp</result> <result name="error">/Error.jsp</result> </action>
The order can also be changed.
Creating a custom logging interceptor
User-made interceptors are straightforward to write and they can then be added to any Action (e.g. Songs). We will now write a custom logging interceptor which will log everything in a table in the database:
Enjoy!
Struts is a family of powerful MVC frameworks for Java.
Struts 1.x is the previous generation framework which is still being used in a lot of legacy applications.
Struts 2.x is a new framework (originally known as WebWork 2) which is now popular. As it is an MVC framework, it naturally supports Models, Views as well as Controllers.
In Struts 2.x, a request is processed by a Filter called FilterDispatcher. This filter is configured by an XML file called struts.xml (found in WEB-INF/classes) and which contain Actions.
When processing a request, the FilterDispatcher checks whether it matches one of the defined Actions. If true, the execute() method of the Action is called (this is where the Action can interact with Models) and that method then returns one of the various Struts 2.x constants (SUCCESS, INPUT, ERROR, etc.) An appropriate View is then shown depending on the return value. The View can easily access the properties of the Action.
In essence, Actions are like Controllers. Their execute method is called when a request comes. The Action interacts with Models and select a View.
Work to do
Let’s now create a simple menu:
Adding a login form
Struts 2.x also supports form tags which allow complex forms to be built very quickly.
Validation on the client
Struts 2.x has full support for server-side and client-side validation.
Now, let’s make validation work by (1) adding validate=”true” to the form and (2) by adding something similar to the following to the GetCharacter action:
@Validations ( requiredFields = { @RequiredFieldValidator(fieldName="string", message="The string needs to be specified"), @RequiredFieldValidator(fieldName="position", message="The position needs to be specified") }, requiredStrings = { @RequiredStringValidator(fieldName="string", message="The string needs to contain characters") }, stringLengthFields = { @StringLengthFieldValidator(fieldName="string", minLength="1", maxLength="100", message="The string must be between 1 and 100 characters long") }, intRangeFields = { @IntRangeFieldValidator(fieldName="position", min="1", max="100", message="The position should lie between 1 and 100") } )
What do you notice? Where is validation being done?
Validation on the server
In some applications, it’s better (not to say simpler) to validate on the server instead of on the client. To do that, do the following simple changes:
What do you observe when the application is run?
Further validation
ActionSupport has a method called validate() which can be used for more complex validations. For example, validate() can query databases and do calculations before emitting errors.
You want to receive our Picks of the Week every Monday morning?
Thank you for reading the fifth edition of the Knowledge7’s Picks of the Week.
Every week, Avinash Meetoo will make you discover interesting articles and websites to help you broaden your understanding of the world of open source software and information technology in general.
Jolicloud
Jolicloud is a new Linux distribution derived from Ubuntu which is itself derived from the oh so powerful Debian. Jolicloud is designed for netbooks having relatively small screens and amount of memory. Its philosophy is based upon blurring the distinction between native applications and web applications. For example, in Jolicloud, Skype and Flickr are accessed in the same way even though Skype is an application and Flickr is a website. This makes Jolicloud an easy operating system to use by beginners. Jolicloud is still young (version 1.1 has just been released) but it certainly has a lot of potential. I advise all Linux fans who have a spare netbook to give Jolicloud a try. Who knows? Some Windows fan might fall in love with Linux!
An In-Depth Exploration of the Art of Shell Scripting
I have been teaching Linux for ten years now and the one thing which always amaze most people is the shell (i.e. the command line). There are many reasons for that: (1) Linux and all the other Unixes as a matter of fact have many commands (about 2000…), (2) a lot of those commands are filters which transform data and are used in combination (in pipes) and (3) a set of commands (including conditionals and loops) can be saved in a shell script which then becomes indistinguishable from pre-existing commands (i.e. the set of commands is infinitely extensible). Of course, mastering everything takes a lot of dedication and a lot of time. This tutorial is an essential reading for anyone willing to, one day, become a Linux guru.
Yii Framework
PHP is a powerful programming language and major web applications like Wikipedia and Facebook are built using it. When developing a new application, one can write everything from scratch or use a framework. Most of the time, people tend to use a framework because of the added productivity this provides. Yii is a new PHP framework based on the Model View Controller (MVC) architecture and which supports AJAX and jQuery, interacts with relational databases (like MySQL) and provides multi-language support, performance optimisation through caching and security through role-based access control. Yii implements many of the good ideas of Ruby on Rails like minimal need for configuration, scaffolding (automatic PHP code generation based on a database table, for example) and full testability. All PHP programmers should give Yii a try.
Node.js
In the past, web applications were mostly server-based with only a few bits of verification and validation being done on the client. In 2011, this is not true anymore: any decent web application needs to have a complex Javascript portion to deal with AJAX as well as to provide a modern user interface. In other words, having Javascript in the client and, say, PHP on the server (using something like Yii for example). Node.js challenges this. With Node.js, it is possible to run Javascript on the server. In fact, Node.js adds to Javascript the capability to work as a web server with full support for all kids of databases through add-on modules. The advantage is, naturally, that the programmer only has to master one programming language instead of two. jQuery has revolutionized client-side programming. Can Node.js be as innovative on the server front? Only time will tell.
Clojure
Clojure is yet another programming language for the Java virtual machine. I talked about Scala previously but Clojure has had a lot of buzz since it was launched in 2007. Clojure is a LISP and, therefore, will look incompressible at first to those of you not versed into LISPdom. But it is also a very powerful general purpose language with extensive support for functional programming, it has a very powerful macro system inspired by the one in LISP and provides immutable data structures which allows for helps in writing efficient concurrent programs. Given that the programming environment in 2011 is essentially multi-core, it is important for all of us to start looking at alternative programming languages built with parallel processing in mind. Clojure is such a language. And, remember, parentheses are cool.
JSP is a powerful technology and it gets even more powerful when used properly!
As mentioned in the previous topic, most web applications are built using an MVC architecture. Most of the time, the controller will be a Java servlet, the model a POJO (Plain Old Java Object) or a JavaBean which exposes methods and the views are JSP.
We saw how to add an attribute to a request in the controller and access it from the JSP using EL and the requestScope object. In the previous example, the attribute was a scalar value. In most large applications, the attribute(s) might be complex object hierarchies and, consequently, it is important that JSP tags be extended to include conditionals, looping constructs and so on.
This is the role of JSTL, the JSP Standard Tags Library.
We will rewrite the Countries/Artists/Songs application to be compliant with the MVC architecture. We will also make sure that views leverage the tags found in JSTL. We will follow the following steps:
CountriesView.jsp uses the JSTL Core tag library (taglib) so the following line is needed:
Furthermore, the view will get the list of countries from the requestScope and loop through the countries using the c:forEach tag.
For information, JSTL Core contains the following tags:
Displaying artists…
The next step is to write ArtistsDAO (with a findByCountryid(int countryid) method which returns a list of artists who are from the same country), ArtistsController (which now takes one parameter, the countryid). Interestingly, this means that two views need to be writter, the expected ArtistsView.jsp and ErrorView.jsp in case, for instance, countryid is not valid.
ArtistsView.jsp will, of course, be written using JSTL tags (including, most probably, c:if, to know when to display the list of artists). Accessing a request parameter (which is not the same thing as a request attribute) is done through the param object in JSP.
… and songs + and the rest
To display songs, we need SongDAO (with the findByArtistid(int artistid) method), SongsController (which now takes two parameters: countryid and artistid) and the corresponding view, SongsView.jsp.
The rest is straightforward:
Using custom tags
The standard tag library is very useful as it is but it is also possible to create custom tag libraries with custom tags. For example, we will do the following:
JavaServer Pages (JSP) first appears in 1999 as an alternative to ASP and PHP for writing server-side software easily.
Like ASP and PHP, JSP allows code (in its case, Java) to be interleaved with HTML. The Java code is delimited by <% and %> and can refer to the following objects:
Write a small Java web application which:
We are going to enhance the web application so that the logic for the calculation of the factorial is encapsulated in a distinct class. We will make that class follow JavaBean conventions so that we can use it easily from a JSP. In essence, a class is a JavaBean if the following are all true:
JavaBeans can then easily be used, properties set and retrieved
Web applications generally follow a MVC (Model View Controller) architecture. In such an architecture, the application has three types of components:
We can enhance our application to become MVC compliant by implementing a controller as a Servlet. The controller gets a request, calls appropriate methods on our existing JavaBean to get the factorial (this is our model), sets the factorial as another attribute of the request and then selects a JSP (our view) for producing an HTML response.
The JSP can then access the attribute from its requestScope using Expression Language. The requestScope maps attribute names to their values. It allows JSP to access the attributes of the request object.
[img_assist|nid=223|title=|desc=|link=none|align=center|width=318|height=448]
A lot of companies rely on PHP and MySQL for powering their mission critical websites and web applications. Consequently, developers working in those companies need to be skillful in PHP and MySQL.
Knowledge7 is organising a Web Development with PHP and MySQL training starting on 14 March and will run over five Mondays from 9:00 to 16:00.
IT and HR Managers will be pleased to know that their staff will be more skilled and efficient by becoming conversant with the latest web technologies. Of course, trainees will also be exposed to best-practices and standards as used in industry allowing them to easily overcome challenges they might come across during their career.
Our Web Development with PHP and MySQL is MQA approved. Call Liliane on 5834-9001 for more information.
Book your seat now. Places are limited.
You want to receive our Picks of the Week every Monday morning?
Thank you for reading the fourth edition of the Knowledge7’s Picks of the Week.
Every week, Avinash Meetoo will make you discover interesting articles and websites to help you broaden your understanding of the world of open source software and information technology in general.
How to Install a Wireless Card in Linux Using Windows Drivers
Some years ago, life was tough for Linux fans who wanted to enjoy Wifi on their laptops as drivers were only available for a few chipsets. In 2011, things have greatly changed. People have written open source drivers for quite a lot of wireless chipsets from companies such as Atheros, Broadcom, Cisco, Intel, Lucent, Marvell, Ralink, Realtek and ZyDAS and, naturally, this means that Linux now supports Wifi out of the box. But, to be fair, there remains some more obscure chipsets which do not have corresponding open source drivers where the only solution is to use existing Windows drivers using a technology known as NDISwrapper. Yes, Linux can use Windows drivers! This article explains how to do that using the latest Ubuntu Linux.
The Java Tutorials: Concurrency
When Java 5.0 was released a few years ago, most people didn’t pay attention to a new standard library called Java Concurrency Utilities. This library allows a programmer to write concurrent programs easily by providing classes such as executors, futures and concurrent data structures. Here is a simple explanation for concurrency: a concurrent program is a program with parts which execute in parallel when run on a parallel computer. Running a non concurrent program on a parallel computer is stupid. But running a concurrent program on the latest multi-core processor is nice. When a programmer writes a Java program using classes from the Concurrency Utilities, she is being explicit about which parts are concurrent. Given that all computers now are parallel, this is a good thing to do.
Why You’re a Bad PHP Programmer
PHP is an excellent programming language. It wouldn’t be used by Facebook and Wikipedia if that wasn’t the case. But, to be fair, a lot of PHP programs are written by people who do not give a lot of importance to maintenance and, consequently, their PHP programs, while running well, exhibit a lot of “smells” (a term coined by Martin Fowler). Those smells are, for example, having no comments, writing brief code instead of being clear, not following standards, etc. In other words, trying to be too clever. The thing is that we are all guilty of that. We start with a quick and dirty solution and, as soon as it runs, release it to the wild without realising the maintenance nightmare that might result. This article explains how to be a good PHP programmer.
Managing Hierarchical Data in MySQL
The relational model as used in most relational databases including MySQL is not really intended to represent hierarchies. In fact, the relational model was a replacement for the hierarchical data model as used, for example, in the venerable IMS database developed in the 60’s by IBM. Unfortunately, the real world is full of hierarchies e.g. network of people, components in a machine, our solar system, blogging and forum software, etc. and, consequently, it’s tough to model such objects using MySQL. Tough but not impossible. The idea is to use adjacency lists and/or nested sets and then write special SQL queries. This article, by Mike Hillyer, explains in detail how one can use MySQL intelligently to represent such hierarchies.
Taking the Mystery out of Scaling a Company
It’s fun to run a startup. I know. I am. But, sometimes, some startups become large and then care must be taken to scale them properly. For instance, one must be ready to “give ground grudgingly”. Things that were easy to do when there were only two people in the company become hard when there are twenty employees. Specialists are frequently needed (e.g. accountants, HR people, etc). We must make sure that people communicate properly and that people do not misunderstand each other. In fact, the decision making process also becomes more complex as head count increases. Naturally, this implies that the company needs to change some of its processes. The thing is that we don’t want to address those concerns too early or else the startup will seem sluggish. On the other hand, waiting too long is bound to cause a lot of problems in the long run. This article shows what works, when and why.
System administrators should monitor Linux installations on a regular basis and detect if there is any hardware anomaly. For example, performance might not be optimal or resource clashes might be happening.
The various subsystems that need to be carefully monitored are:
Of course, legacy devices (serial ports, parallel ports) as well as more advanced devices (like SCSI devices) also need to be monitored.
Each subsystem has its own set of commands and configuration files.
You want to receive our Picks of the Week every Monday morning?
Thank you for reading the third edition of the Knowledge7’s Picks of the Week.
Every week, Avinash Meetoo will make you discover interesting articles and websites to help you broaden your understanding of the world of open source software and information technology in general.
Hacker Chat: Pinboard Creator Maciej Ceglowski Talks About Why Boring Architecture is Good, and More
Writing a web application in PHP is easy. But writing one which performs well when hundreds of users are accessing it concurrently is difficult. In this article, Maciej Ceglowski, creator of Pinboard, a very well known alternative to Delicious (which got rave reviews a few weeks ago when it would seem that Yahoo! was going to discontinue Delicious), explains that the KISS principle should apply to the architecture of PHP applications too. For instance, he mentions that having adequate RAM on servers is crucial, that dedicated hardware is always better than virtualised hardware, that it is important to optimise MySQL (see next pick) and that frameworks should be used with caution.
MySQL Performance Blog
If one wants to increase the performance of MySQL, the database server needs to be properly optimised: from key runtime variables (like key_buffer_size) to storage considerations. Then the database schema needs to be properly devised while taking into account current and future querying patterns. Specific SQL queries have to be written in such a way to perform as efficiently as possible and, if this is not possible, stored procedures might need to be used. Of course, indexing is always a possibility… if used judiciously. Buffering and caching possibilities also need to be explored. In other words, optimising MySQL is not trivial. Reading the MySQL Performance Blog provides excellent insights into the difficult art of MySQL optimisation.
The Scala programming language
The Java Virtual Machine (JVM) was originally devised to run bytecodes generated by a Java compiler. But Java is a very verbose programming language and some even say that it’s not very powerful as it lacks most of the expressive constructs found in functional and scripting programming languages. Scala is a new programming language which compiles to bytecodes which then run on the JVM. Scala is 100% compatible with Java and existing Java libraries, is fully object-oriented and supports functional programming. This allows programmers to write very powerful programs in just a few lines of code. A notable example of Scala in industry is Kestrel, the message queue server which forms the core of Twitter. Due to this high profile adoption, Scala has gained the respect it deserves and some people are even starting to believe that it’s the next big thing in programming.
GitHub
GitHub is an online service which hosts software developed using the Git source control system. A source control system allows multiple programmers to work on the same software concurrently. GitHub comes in two flavours: it is free for those who develop open source software and those who want to use it to host private repositories have to pay. Git was originally developed by Linus Torvalds to ease the development of the Linux kernel. Since GitHub was launched, a number of notable open source projects have switched to it. Examples include Erlang, Hibernate, jQuery, JUnit, Mozilla Labs, Perl, PHP and Ruby (including Ruby on Rails). One of the interesting aspects of GitHub is its ‘Explore’ facility which provides insights on the most active projects and programming languages in use (right now, it’s a tie between Javascript and Ruby).
How to Start a Startup
Paul Graham is one of my gurus. He co-created Viaweb, the first ever e-commerce website, which Yahoo! acquired for $50 million in 1998. Paul then created Y Combinator with the help of some friends to provide new startups with seed capital and advice. Some notable startups funded by Y Combinator include Reddit, Dropbox, Posterous and Justin.tv. So Paul knows what he is talking about when he says that the three most important things to get right when launching a startup is to begin with extremely competent people, to make something customers actually want and to spend as little money as possible. One thing I always tell people is that it’s not normal that only few young people in Mauritius want to emulate people like Bill Gates, Steve Jobs or Mark Zuckerberg when they finish school. Maybe “How to Start a Startup” needs to be taught in Mauritian schools…