Ajax on java: nothing fancy

As of 2019, I found a 2007 book [[ ajax on java: The Essentials of XMLHttpRequest and XML Programming with Java ]]. Some basic observations:

  • ajax works with tomcat servlet engine
  • ajax works with JSF and GWT but not so popular nowadays.

There’s also a 2006 book [[Practical Ajax Projects with Java Technology]], so I guess java+ajax integration was most prominent in 2007 !java


struts self-quiz

Q: what kind of obj is returned by execute()? How is it related to the httpRequest’s forward() call?
Q: how does execute() get the form input data? P741
Q: how many servlets are there in a typical web app? how many are there in a struts app? P743
Q: a session is for one web app only?
Q: how 2 share a session obj btw 2 web apps?

servlet filters — possible uses

usage: add custom headers. both request and response. custom headers are flexible and powerful communication devices. X-ZED headers.

usage: standard logging on selected requests. You can add this filter to any number of servlets.

usage: time logging. end-to-end roundtrip
usage: request translation. response too.
usage: response compression
usage: consistent cookie processing and logging
usage: authentication and single-sign-on
usage: consistent look and feel?
usage: spell checker?

2 ways for http sessions to share a single object

2 ways for sessions to share a single huge object

Requirement: a huge object to be instantiated before the first session, and kept alive after all sessions end. Object is not immutable.

Solution 1: put that object in an app-scope bean.

Solution 2: static field in a special class. Your huge object will be reachable from the persistent class-object.

%%struts quiz

brief points? ok
j4: keep for review in 2 years

[g=generic servlet/jsp issue]

  1. [i] error-handling is relatively simple but imp2iview. What kind of entities read ActionErrors and how are they used? views?
  2. ActionForward ^ ActionForwards ? P 113
  3. where does Struts use reflection and introspection? P 114
  4. do you need to manage sessions or struts does it for you?
  5. [i] what kind of data structure to hold multiple errors in ActionErrors (No need to be exact) ?
  6. how2get an afbean from a mapping object? Is the afbean “contained” (HAS-A) in the mapping obj? I think when the afbean object exists in JVM, the mapping obj provides a path to it.
  7. [gi] when does a session start and in which method? probably by ActionServlet
  8. [i] signature and usage of findForward()? defined in which class? P 741 [[ ?? ]]
  9. [gi] is ActionServlet a singleton?
  10. which object invokes the afbean’s validate()?
  11. how does execute() retrieve the afbean? from the argugment mapping obj or from the request argument?
  12. how2get formbean from req? when ? when req is forwarded to a non-struts servlet or another struts servlet?
  13. [i] which method(s) return ActionErrors (see the trailing s), following which well known design pattern?
  14. let’s zoom into Struts’ usage of dataSource class in standard java. which struts components interact with a datasource?
  15. [g] is ActionServlet a single-threaded servlet, and need many sisters to service simultaneous requests?
  16. [gi] How is ActionServlet thread-safe?
  17. session in struts is same as session in other servlets?
  18. <action input=…. means?
  19. <action name=…. means?
  20. struts connection pooling? no answer
  21. beside global forward and local forward, there’a 3rd way to DEFINE an afward. P189
  22. which validator xml file contains the javascript function? What’s the other major content in the samel xml? name of a method?
  23. controls the (non-validator) validate() method u create in your afbean, but what if u use validator?
  24. 1 basic use of var in validator.xml? p378
  25. #1 most basic validator in the validator package? how do u configure it in validator-rules.xml? p375
  26. aforward obj is returned by which method to whom? How is it used?
  27. [gi] in which method do u do jdbc connect? perhaps a M object not defined by struts
  28. why execute() need the map? local forwards?
  29. g how does a non-struts servlet retrieve afbean from the request (received by forward)? P221
  30. Without struts-validator, what page is returned to browser upon validation error? How do u make this takes place by configuration?
  31. biggest 2 struts extensions each can be used outside struts, and each defines its taglib. What’re the 2 tag prefixes?
  32. what return type do u use with a formbean getAmount() ? P155
  33. simple yet important AR question: which obj calls execute()? P 741
  34. where 2 spell out a regex? how 2 pass it into a validator
  35. can take one of 3 { include, forward, ???? } I think it’s type
  36. ignore validator for now. afbean usually defines an public instance method validate(). what’s the signature? revealing! P740
  37. [i] simple yet tricky question: exactly which object (loaded into the servlet container) acts as the router, inspecting and dispatching requests to other objects?
  38. signature of execute(). AR-revealing
  39. [gi] how does the query result get into the view? aforward? req obj? P 741 [[servlet]]
  40. [i] which obj auto-populates a formbean? ActionServlet?
  41. where is the Model object instantiated? P 741 [[ servlet ]]
  42. is the mysterious but important ActionServlet (full class name) mentioned in any prominent place? Hint: along with struts-config.xml. P 743 [[servlet]]
  43. during request processing flow, describe when the mapping object is loaded and how it controls each module such as form population/valiation, forward, custom action etc. P47.
  44. example of httpSession in struts? P79

property^param^attribute ] servlet

property = field
attribute => 4 scopes
param … usually means GET or POST params
These are the shortest intro to the 3 frequent terms in servlet/jsp literature. Now some details.
— param
GET => query string
POST => user input
usually means “request param” ie GET/POST param, unless otherwise stated
means request param, too!
disambiguation: “parameter” and “param” sometimes have specific and different meanings.
— attribute is a servlet concept
is usually a bean

corresponds to the setAttribute() and getAttribute() methods

in EL, ${*Scope.abc} usually refers to an attribute “abc”

disambiguation: Some servlet literature talks about “attribute” when they mean “xml attribute”.
–property => HAS-A.
Can be a bean.
is a generic java concept.
HAS-A can be nested, so can properties.
“setProperty” => a field in a bean

INCLUDE <jsp:include> <c:import>

The 2 common alternatives are INCLUDE and .

, defined in jstl-core, is less common.

To memorize the key difference among the 3 alternatives, #1 thing to remember is

” is in the middle ground”

reads content from arbitrary URL (vs which is restricted to the jvm)
* Insert into page
* Store in variable

getRequestDispatcher() in 2 classes

A: There is very little difference between the ServletContext and ServletRequest versions of this method, the RequestDispatcher you get operates in exactly the same way. However, the ServletRequest method also allows you to use a path argument that is relative to the “current” resource, starting with “./Example.jsp” or “../Example.jsp”. The ServletContext getRequestDispatcher method should only be used for paths relative to the application root, starting with “/Example.jsp”.

pretend2b d controller – [[headfirst servlet]]

The Most vague concept is the intangible Model. (New discovery: P 741, 745 [[ servlet ]] has a simple, clear example )

One excellent starting point is a real, tangible, mapping file.

Another starting point (P733 [[ servlet ]]) is “pretend to be the contoller” and trace its steps. You will notice that mostly the controller deals with
* request obj and stuff put in there such as user inputs
* response obj containing query output
* views
* query input, query output, to be sent to the view

After these things become familiar, maybe u can then lj the interactions with the elusive Model. Maybe there’s no model. Maybe it’s just a term used by … some people. Maybe it’s well defined in GUI.


some of the built-in-validators: required maxLength email date creditCard

* Now I think validator-rules.xml should be named built-in-validator.xml
* validator-rules.xml is a standard file you seldom need to modify.
* It configures the built-in-validators.

* root xml has a bunch of children like
* Each built-in-validator is also known as built-in-valiation-routine. Each built-in-validation-routine in the validator-rules.xml file has its own definition that is declared with a “validator” tag, which is used to assign a logical name to the routine, using the name attribute, and to specify the class and method for the routine. The routine’s logical name is used by other routines in this file as well as by validation definitions in the validation.xml file to refer to the routine.

update a session obj -> setAttribute() -> replication

(Perhaps the most basic coding technique when migrating a servlet to a cluster.)

1st time u call setAttribute(amt, Amount), the container binds Amount obj to the session scope. Subsequent changes to Amount would
be forever visible to any other servlet accessing the same session.

However, in a cluster,

make changes to Amount
setAttribute() again
make changes to Amount
setAttribute() again

I think each method call triggers a session replication.

%%jsp iview q

imprecise? ok
  1. what kind of content/data do u use Expression Language to express?
  2. give 3 common tags as part of the JSTL
  3. where are security roles defined? give a few examples
  4. where are security usernames defined? give a few examples
  5. mapping a username to a role? to 2 roles?
  6. (entities: real visitors, passwords, usernames, roles, url-resources to protect….) how does system authenticate a real visitor to such a username?
  7. How does a servlet or jsp add to the exception (implicit object)? P 299 [[ jsp ]]

struts as a dispatcher

“request dispatcher” or “request router”.  Explanation in one sentence:
“A traffice-cop that directs incoming requests [note 1] to places [note 2].”
[ Note 1: perhaps instructed by another struts component ]
[note 2: to other URL’s. Sometimes we talk of “to some processing components” ]
In this model, afbeans can become irrelevant whereas afward COMPONENTS become critical. In this model, u need to know the various means to add parameters (name-value pairs) during the dispatch.
This discussion is important only for AR. iview?


To impose the validation rules, the standard Struts ActionForm won’t suffice. For this to happen the ActionForm class designed specifically for the Validator framework must be used. It comes in two varieties- ValidatorForm and DynaValidatorForm. Two methods are present in both of them- reset() and validate().

struts validator.xml

It is here that the rules defined within the validator-rules.xml that the rules are applied to the data fields of ActionForm objects.

validator.xml is the “link table” linking the rules with the afbean fields. (A: the other xml file, which defines the validators outside the context oof data fields)

validator.xml is Perhaps the 2nd step in swallowing this elephant, just like struts-config.xml to struts. The first step is …..

struts: swallow an elephant

iview q: “desc struts(&&spring) web flow of your project” There are more than 10 key aspects , so u need to digest and memorize something like an elephant. You need a system to organize these topics.

* Benefit: u will sound thorough, confident,
* benefit: As a bonus, fewer unprepared questions. Most iviewers ask about common, standard aspects like login, dao, formbeans, forward/redirect, session

[A=authentication]: after successful/unsuccessful login, redirect or forward?
A: login form bean?
A: login form send to ….?
A: which component sends the cookie? any session support offered by struts?
A: time out an idle session?
A: what objects do u put in the session obj, when and by which component

[I=form input interaction] which component does input validation?
I: how is the validation errors sent back? forward or redirect?
I: if successful, forward or redirect?

where else do u use forward? redirect?

M: biz logic in … biz-logic beans? servlets?
M: DAO questions
M: desc the usage of a formbean
v: how many forms? name a few. where do they submit to? controller? which one?
v: error pages?
v: validation error page?
c: routing map?
c: how many controllers? name a few

struts methods called by hollywood

* [P740] actionform bean’s instance method validate() is called by ActionServlet ie the framework — hollywood principle in action

* [P735] actionform bean’s setters are called by ActionServlet ie the framework — hollywood principle in action. Afbean auto-populated.

* [P741] execute() is called by ActionServlet ie the framework — hollywood principle in action

Page numbers -> [[ head first servlet ]]

spring mvc reload,starring wac4ds (AppCx)

wac4ds is the #1 thing to internalize, && the #1 source of initial confusion.

Q: What’s the relationship between a DispatcherSerlvet and a WebApplicationContext (WAC)?
A: “each DispatcherServlet has its own WebApplicationContext” — according to http://static.springsource.org/spring/docs/2.0.x/reference/mvc.html, which even shows a diagram

Q: To drive home the one-to-one mapping, give me the names of a { DS, WAC } pair?
A: These pairs are by no means behind-the-scene unsung heros. golfing-servlet.xml is the WAC if you have


Struts ActionServlet is similar:


In both spring and struts web.xml, this “golfing” name would subsequently be used for url mapping.

Q: is DispatcherServlet ready to use or must be subclassed?
A: No subclass need. You give a customized name to the standard DispatcherServlet in web.xml and use it.

Q: where to put the web application context config file?
A: WEB-INF/your_servlet_name-servlet.xml must be present. known as the
webapplicationContext (wac4ds) for the DispatcherServlet

struts vs spring, component-by-component


1) Struts Actions Are Roughly Spring Controllers

Actions are abstract classes (extends Action@@) and Controllers are interfaces. In order to be configured as a Spring MVC controller, an object would need only to implement the following method:

ModelAndView handleRequest (HttpServletRequest request, HttpServletResponse response); # pushmail

the simplest intermediary transition step from Struts to Spring is to rewrite Actions so they implement the Controller interfaces and reuse the existing code. This allows incremental removal of all the Struts dependencies while the application remains operational.

Some of the supplied Controllers match the more specialized Struts Actions with which you may be familiar. For instance, if you use DispatchActions, MultiActionControllers and the more elaborate AbstractWizardFormControllers will be helpful. About a dozen different Controller implementations come with Spring MVC, so it is well worth exploring their purposes and how they can replace your Struts mechanisms.

2) ActionForwards -> ModelAndView

closest component in Spring MVC to ActionForward is the ModelAndView interface. Spring Controllers return implementations of the ModelAndView interface, which, like a Controller, can be custom implemented. Or, if appropriate, you can use the ModelAndView implementations supplied by Spring MVC.

As the name implies, ModelAndView objects have Model and View components. Model components contain the business object to be displayed via the View component. ModelAndView implementations may not have any Model components included. They may simply forward into some form of an actual View component (JSP, XSLT, Tiles, HTML, XML, etc.). As with Controller implementations, I strongly recommend researching Spring MVC-supplied implementations of the Model and View interfaces and View Resolvers.

*) afbean (actionForm beans) have no direct counterpart

*) spring taglig is much smaller than struts 4 taglibs (html, logic, bean ….)

*) loginAction.java -> loginController.java

*) struts “action path=..” -> simpleUrlMapping to map a request URL to loginController

*) struts “forward name=..” -> viewResolver to translate a logical view name to a URL

*) struts-config.xml -> yourDisplatcher-servlet.xml (WAC4DS) + auxiliary config files

*) execute() -> handleRequest()

servlet project — sportsbook

— Singapore’s first …

— mvc, struts

— caching? See blog on money-changers

— oracle stored procedure to return report data

— periodic batch job to run huge stored procedures

— multi-lingual

— multi-threaded? but many users could be requesting the same report? Since the round trip takes only a few seconds, we let all the concurrent threads run independently.

— 1 dao for each request? See blog post on jsp-dao

— connection pool

— where is the SQL stored? See blog post on “core DAO”

a JSP-based batch

User? A golf specialty shop

Startup? User logs in to a website to configure and launch the batch job. After successful start, the JSP page shows a progress indicator, refreshed every 15 minutes.

Code sharing? POSBean ie Point-of-Sales bean is a big (thousands of lines) java component containing business logic for our batch and for other modules.
* parse correlated records from multiple sources including branch POS and membership databases
* calculate loyalty points, redemptions and discounts
* “roaming customers” — need to reference remote data maintained across borders
* sophisticated logic to reconcile conflicts among data sources

Database triggers? i think there were a few types
* input validation triggers
* in-DB logging triggers

Threads? single-threaded. Some kind of singletons. One or more “application/context scope attributes”.

Duration? typically less than an hour for small records

Cancel button on a web page? I think it was supported. I think the thread checks a cancellation flag periodically

Progress indicator? At any time, user can see a progess indicator. The thread updates a flag periodically

Realtime log viewing? At any time, user can view the last x lines of transaction logs

Realtime SQL statement viewing? Similar to log viewing

Schedule? on-demand. no automatic schedule.

tiles — 4 types of resources

To quickly get a TR on any tiles application like http://www.javaworld.com/javaworld/jw-09-2002/jw-0913-designpatterns.html, at a glance you need to identify 4 types of “resources”

1) component-jsp files like header.jsp
2) template files
3) definitions contained in tiles-defs.xml
4) user-jsp files ie any jsp files using the trio.

So now you know tiles are not that simple — the simplest demo needs at least 4 types of files.

To better understand the need for the 4 files, use the concept of “referencing”, or more simply, “mention”.
a) A template alone can’t reference a component-jsp. Internalize the fundamental reasoning. See other posts.
b) Therefore a template can’t be a URL. A URL must reference all component-jsp directly or indirectly.
c) A URL has to be a user-jsp, referencing the defitions, which in turn references template and component-jsp files

tiles — 3 types of resources

For Tiles, there’s some valuable but less-than-comprehensible code example at http://www.javaworld.com/javaworld/jw-09-2002/jw-0913-designpatterns.html

Background: U have a template file, containing variables, each naming a component-jsp file. Each variable is a place-holder to be substituted by the corresponding jsp.

Q: If you don’t know tiles, how would u do the substitution in a servlet container? How do you assign a header.jsp to the first variable? If first variable names “header.jsp” right within template.jsp , then we can’t reuse template.jsp in another project. We need template.jsp to be free of hard-coding.

A: You need some kind of glue-file. Tiles implents it as a set of definitions spelt out in tiles-defs.xml

Closest starting point: smarty — also contains template, variables holding large content. Smarty uses assign() to put the content into the variables and glue the parts.

struts^spring-mvc: 1-controller@@

Struts also has an “specialized” controller per action — the LoginAction/SignupAction/DetailsAction… classes, even though they only constitute part of the controller. The singular ActionServlet is the other part of the controller.

In summary, For Each action u need 0 or 1 form, 0 or more views, a 2-part controller, 1 mapping to tie them together

As you can see, the Model thingy is elusive.


velocity is mostly used as the V of the MVC.

An interesting prj: velocity email-template

– No JSP
– the template contains place holders for names, titles etc

Q: how was the “subsititution” triggered?
A: perhaps the mailer program loads the velocity classes which reads the config and the template

dao-jsp-struts q&&a

q: every browser request would trigger an instantiation of the DAO?
A: i think so, from the DAO factory. In fact, if the request uses 2 tables, then you need 1 DAO intance for each table.

q: at a minimum, how do u keep the dao instance persistent throughout the session?
A: I don’t think you want that. If you keep 3000 DAO object in that many sessions, then you need that many connection objects! See also P 360 [[ JSP ]]

q: dao objects are placed in jndi/app/session/request scope?
A: I think you can put in request scope.

[lopri] q: jndi?

q: in a non-trivial system like hib or struts, what are the most basic “interface points” of DAO
– how does a client get a DAO? jndi?
– where does the DAO return result to? in a bean? a value object?
– how does the client receive the result?