10
-
Web Application Development
- Writing applications by hand can get pretty voluminous.
- Can we develop more “easily”?
- Alternatives:
- Frameworks
- Other languages
-
Alternative Languages JSP
- Released by Sun Microsystems in 1999.
- Allow the creation of web content with static and dynamic components.
- Built upon Java Servlets
- Make available all the dynamic capabilities of Java Servlet technology but provide a "more natural" approach to creating static content.
- Features:
- A language for developing JSP pages, which are text-based documents that describe how to process a request and construct a response
- An expression language for accessing server-side objects
- Mechanisms for defining extensions to the JSP language
- A Top Level JSP Life Cycle
- A JSP page is converted into a Servlet in order to service requests.
- The JSP life cycle defines the process from its creation until the destruction.
- The JSP Lifecycle is that of a Servlet
- With the additional first step of translating the JSP page into Servlet code.
The Steps in the JSP Life Cycle
1. Translation of the JSP page to Servlet code.
2. Compilation of the generated Servlet to bytecode.
3. Loading the Servlet class.
4. Creation of a Servlet instance.
5. Initialization of the JSP page by calling the jspInit() method
6. Request Processing by calling the _jspService() method
7. Destruction by calling jspDestroy() method
- Types of JSP Tags
- Expression tag <%= expression %>
- Scriptlet tag <% scriptlet %>
- Directive tag <%@ directive attribute="value" %>
- Declarative tag <%! declarations %>
Expressions
<%= Java expression %>
- The Java expression is evaluated,
- Converted to a string, and
- Converted to a string, and
Scriptlets
<% statements %>
- Contains code fragments
- Have access to the same automatically defined variables as expressions
- Can use pre-defined variables
- request, the HttpServletRequest;
- response, the HttpServletResponse;
- session, the HttpSession associated with the request (if any); and
- out, the PrintWriter (a buffered version of type JspWriter) used to send output to the client.
- Example:
Your hostname: <%= request.getRemoteHost() %>
Declarations
<%! Java Code %>
- Define methods or fields that get inserted into the main body of the servlet class
(outside of the service method processing the request). - Example
<%! public int getValue(){ return 78; } %>
- can then be used in an expression
<%=getValue()%>
- Error Handling
- Specify a default error page in the web.xml deployment descriptor with instructions such as the following:
<error-page> <error-code>404</error-code> <location>/error404.html</location> </error-page>
The Page Directive - Syntax
<%@ page ... %>
- Defines page-dependent attributes,
- such as session tracking, error page, or buffering requirements.
- Set the page directive isErrorPage parameter to true.
- Then this page can access the exception as a jsp implicit object and use it to send customized error message to the client.
- JavaBeans
- A JavaBean is a specially constructed Java class written in the Java and coded according to the JavaBeans API specifications.
- It provides a default, no-argument constructor.
- It should be serializable and that which can implement the Serializable interface.
- It may have a number of properties which can be read or written.
- It may have a number of "getter" and "setter" methods for the properties.
- The useBean action declares a JavaBean for use in a JSP. Once declared, the bean becomes a scripting variable that can be accessed by both scripting elements and other custom tags used in the JSP.
- Strengths
- JSP is fast
- Because the page is _compiled_ into Java.
- Then the code is run, HTML is produced via the PrintWriter.
- Compared with alternatives such as php, every time a page is loaded it is interpreted
(the text of the page is read, the php code blocks are identified, processed) - With compiled code the JVM is multi-threaded, more efficient (memory and CPU)
- We can design our front-facing web page and dynamically include application data BUT
The inclusion of server-side code on the client is problematic. - There are many tags to execute functionality BUT
Many outcomes can be achieved in (too) many ways.
- Drawbacks
- Inclusion of server-side code on the client is problematic, because there is no real separation of concerns.
- Modern approaches include:
- Using templates but don't include server-side code, just variables, as the separation is cleaner or
- Making API calls to the server and updating the page.
- Accessing a page for the first time is slow.
- JSP pages must be compiled on the server when first accessed. This initial compilation produces a noticeable delay when accessing the JSP page for the first time.
- BUT that's just for the first customer, not for every customer.
- Can be worked around by starting the server and sending a set of requests to trigger pre-compile of pages.
- The developer may compile JSP pages and place them on the server in compiled form (as one or more class files) to speed up the initial page access.
-
Frameworks
- Frameworks contain a lot of functionality that has been ensured to work together
- Libraries are compatible
- Contain many modules that can be used by developers to write applications by configuring modules to work together
Popular Java Frameworks
- Java Spring
- The most important Java based framework is Spring
- Consists of features organized into about 20 modules
- Are grouped into Core Container, Data Access/Integration, Web, Instrumentation and Test.
- Maven support.
- Spring provides an abstraction layer on existing technologies like servlets, jsps, jdbc, jndi, rmi, jms and Java mail etc., to simplify the develpment process.
- IoC supporting Dependency Injection.
- Spring supports both xml and anotation configurations.
- Benefits
- Is vendor supported, i.e. developers can get support from vendors as well as from the user base.
- Incidence support from consultants
- Frameworks are a skill base: 10 different tools that are individually better than Spring will need 3-4 people who can control them
- Drawbacks
- Spring is monolithic, it “Is only called” lightweight.
- Problems: dev – ops level, testing etc.
- Requires a steep learning curve.
- Slow to change, hard to upgrade.
-
New Trend: Micro Services
- One large app on many servers
- New direction: micro-services -> many services in a container.
- Examples: AWS – many services, services for everything (everything is a service).
- Defined functionality that can be worked on by a small set of people in any language
- Flexibility
-
Alternative Language: Go
- Benefits
- Relatively easy to learn, reduced syntax in comparison with Java.
- Designed for large scale programs.
- Compiles fast.
- Runs fast on the server.
- Strict dependency management, not allowed to import untrusted code.
- Garbage collection (similar to Java) - > no need to allocate / deallocate memory.
Good tool support, such as //go:generate . - Self-contained binaries on all platforms.
- Self-contained binaries on all platforms.
- Support for cross-compilations. Each platform allows to compile for any other supported platform.
- Fast Loading
- Because of small binaries.
- Similar to using a WAR file
- Has files embedded in the binary to speed up startup.
- Has file system function for reading files, that are in the binary
- bindata_assetfs
- Meta Programming
- Programs that write programs
//go:generate - The go generate tool looks for such comments and runs the commands
here: go-bindata-assetfs... - This generates a go file which can provide all web files in a virtual filesystem
Code example
For a complete running example look at the additional learning materials section on GCULearn servemessages.go, similar in functionality to Runner.java but is much shorter.
func Serve( fs *assetfs.AssetFS) { var root http.FileSystem = fs //create a gorilla router r := mux.NewRouter r.HandleFunc("/messages", list).Methods("GET") r.HandleFunc("/messages", add).Methods("POST") r.HandleFunc("/messages/{user}", listUser).Methods("GET") r.HandleFunc("/messages/{user}", deleteMesage).Methods("DELETE") // serve static files from root }
- Practical Syntax
- functions can return multiple values
- conventionally with 2 values returned the second value is an error (a non-nil error value).
- this means that the error can be handled right away and no try{} – catch{} – block is needed.
Example: in servemessages.go func Serve
//function that serves files r.PathPrefix("/").Handler(http.FileServer(root)) //function listening on port 9001 if err := http.ListenAndServe(":9001", authenticate(r)); err != nil { log.Printf(err.Error()) }