Download presentation
Presentation is loading. Please wait.
Published byMelissa Melton Modified over 7 years ago
1
Chengyu Sun California State University, Los Angeles
CS5220 Advanced Topics in Web Programming Bits and Pieces of Web Programming Chengyu Sun California State University, Los Angeles
2
Roadmap Data binding and conversion Internationalization
Input Validation Sending Template engine View template framework Logging File upload and download Task scheduling and execution Exception handling Application deployment
3
Data Binding HTML Form Model Attribute Binding
public class User { String username; String password; … } Usename: Password: Add User Bind form fields to properties of the object
4
What About Properties of Class Type?
HTML Form Model Attribute Binding public class User { String username; String password; User manager; … } Usename: Password: Manager: ?? Add User
5
Use Spring Converters …
Tell the framework how to convert one data type to another Form fields (String) Properties (Class) Example: SpringMVC TextToUser UserToText
6
… Use Spring Converters
Configure a Conversion Service bean in <servlet-name>-servlet.xml For example: <mvc:annotation-driven conversion-service="conversionService" /> <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="springmvc.web.converter.TextToUser" /> <bean class="springmvc.web.converter.UserToText" /> </set> </property> </bean>
7
Exercise: Dropdown List
Use a dropdown list to select manager in Add/Edit User in SpringMVC Use <form:select> Support the case where a user does not have a manager
8
Message Bundles Separate text messages from application code and put them into their own files E.g. messages.properties error.username.required=A username is required. error.password.short=The password is too short. error.username.taken=The username {0} is already taken.
9
Advantages of Using Message Bundles
Change text messages without modifying the source code Internationalization (I18N) messages.properties messages_en_US.properties messages_zh_CN.properties …
10
Using Message Bundles with JSTL
<fmt:setBundle basename="messages" /> <fmt:message key="msg1"> <fmt:param value="Chengyu" /> </fmt:message> <fmt:message key="msg2" />
11
Using Message Bundles with Spring
Declare a messageSource bean <spring:message> tag <spring:message code="msg1" arguments="Chengyu" /> <spring:message code="msg2" />
12
Input Validation in Spring
Add error messages to the message bundle Implement a Validator and wire it to the controller Add a BindingResult parameter to the controller method Use the validator to validate the model attribute Return the form view if validation fails Display errors using <form:errors>
13
Example: Validate Add/Edit User
Both username and password fields cannot be empty Cannot use an existing username
14
Why Input Validation Seems So Complicated
There may be multiple errors in a form submission Need to identify which error is caused by which field Internationalization Remember the correct fields Separate validation code from application logic BindingResult <form:errors> Message bundle Model attribute and other <form> tags Validator
15
Other Validation Options
Server-side vs. Client-side Validation HTML5 validation JavaScript validation E.g. Commons-validator Provide both declarative and programmatic validation
16
Commons-Validator Declarative Validation Example
<form name=“fooForm"> <field property=“name“ depends="required"> <arg0 key=“fooForm.definition"/> </field> <field property="difficultyLevel" depends="required, integer"> <arg0 key=“fooForm.difficultyLevel"/> </form>
17
Commons-Validator Routines
Independent of the declarative validation framework A set of validators to validate Date and time Numeric values, currency ...
18
Email Function in Web Applications
Various notifications, e.g. order, payment, shipment, forum post and reply, account activities, and so on Advertisement campaigns and product promotions Password reset …
19
How Email Works SMTP, IMAP, POP Email Server A Email Server B ?? ?? ??
Client A Client B
20
JavaMail http://www.oracle.com/technetwork/java/javamail/index.html
Maven dependency: javax.mail:mail Properties props = System.getProperties(); props.put("mail.smtp.host", mailhost); Session session = Session.getInstance( props ); Message msg = new MimeMessage(session); ... Transport.send( msg );
21
Set Up a Local Email Server for Testing
hMailServer on Windows - postfix on Linux -
22
Spring Email Support Mail message classes
Need spring-context-support dependency Declare a mailSender bean JavaMailSender interface See CSNS2 for example Mail message classes Simpl Message No attachment, no special character encoding Mim Message
23
Use Templates Hello ${user.name},
Your order ${order.number} “${order.name}” has been shipped. You may track your order at the following URL We hope to see you again soon. Your Online Store
24
Template Engine A template engine combines templates with data to produce documents Java template engines Apache Velocity FreeMarker - JSP, Apache Tiles … There is no fundamental difference between template engines and view technologies, but some are more “lightweight” than others
25
Basic Features of a Template Engine
Template language Access objects and properties Basic expression and control flow statements For example: EL and JSTL for JSP Support for I18N
26
FreeMarker Basics Data access Expressions Built-ins Directives
E.g. ${user.username} Expressions E.g. ${user.age + 1} Built-ins Directives Mostly the same as EL
27
Built-ins Built-ins are some pre-defined functions that can be applied on data Examples name?length – number of characters in name id?c – converts a number to a string lastUpdated?date – use only the date part of a Java Date object
28
The if Directive <#if x == 1> x is 1 <#elseif x == 2>
x is not 1 or 2 </#if>
29
The list Directive <#list users as user> <tr>
<td>${user.id}</td> <td>${user.name}</td> </tr> </#list>
30
Use FreeMarker with Spring
Create a FreeMarker Configuration bean Inject the bean to where it’s needed Combine template with data FreeMarkerTemplateUtils.processTemplateIntoString( configuration.getTemplate( template ), data ); Name of the template file A Map of <key,value> passed to the template engine
31
Apache Tiles http://tiles.apache.org/ A template framework for JSP
Similar to Master Page and Razor in ASP.NET Dependency org.apache.tiles:tile-jsp
32
The Need for View Templates
page1.jsp pageN.jsp Header Header Content 1 Content N Footer Footer
33
Why JSP <include> Is Not Enough
It breaks HTML syntax, e.g. <html> in header.jsp and </html> in footer.jsp. It’s difficult to create and manage multiple complex templates.
34
Basic Tiles Usage Template page = JSP + placeholders (i.e. attributes)
<tiles:insertAttribute> Content (i.e. attribute values): JSP, string, other tiles Definition: combine template and content <put-attribute> Tiles Tag Library
35
A Tiles Example page1.jsp page2.jsp Header Header Content 1 Content 2
Footer Footer
36
Tiles – Template Page template.jsp Header Footer
<tiles:insertAttribute name=“content” /> Footer
37
Tiles – Content Pages page1.jsp page2.jsp Content 1 Content 2
38
Tiles – Definitions <definition name=“page1” template=“template.jsp”> <put-attribute name=“content” value=“page1.jsp” /> </definition> <definition name=“page2” template=“template.jsp”> <put-attribute name=“content” value=“page2.jsp” /> </definition>
39
Use Tiles with Spring <servlet-name>-servlet.xml
<bean class="org.springframework.web.servlet.view.tiles3.TilesViewResolver"/> <bean class="org.springframework.web.servlet.view.tiles3.TilesConfigurer"> <property name="definitions"> <list> <value>/WEB-INF/tiles.xml</value> </list> </property> </bean>
40
Use Multiple View Resolvers in Spring
The order of view resolvers specified in <servlet-name>-servlet.xml determines the order they will be used to resolve a view If a view resolver cannot resolve a view, Spring tries the next one The JSP view resolver (i.e. InternalResourceViewResolver) should always be the last because it never “fails” to resolve a view (404 is considered a valid view).
41
Tiles Usage in CSNS2 WEB-INF/layout for template and header/footer pages WEB-INF/content for content pages WEB-INF/tiles.xml for definitions
42
Logging Recording events happened during software execution, e.g. using print statements to assist debugging Why do we want to do that when we have GUI debugger?? public void foo() { System.out.println( “loop started” ); // some code that might get into infinite loop … System.out.println( “loop finished” ); }
43
Requirements of Good Logging Tools
Minimize performance penalty Support different log output Console, file, database, … Support different message levels Fatal, error, warn, info, debug, trace Easy configuration
44
Java Logging Libraries
Logging implementations Log4j - java.util.logging in JDK Logging API Apache Commons Logging (JCL) - Simple Logging Façade for Java (SLF4J) -
45
Choose Your Logging Libraries
Log4j Widely used Good performance Rich features Easy configuration java.util.logging Part of JDK, i.e. no extra library dependency Commons Logging Determines logging implementation at runtime SLF4j Statically linked to a logging implementation Cleaner design Better performance Less problem
46
Using Log4j and SLF4j Library dependencies Coding Configuration
Creating a Logger Logging statements Configuration Output format
47
Log4j Configuration File
log4j.xml or log4j.properties Appender Output type Output format Logger Package or class selection Message level
48
Log4j PatternLayout
49
Logging in CSNS2 src/main/resources/log4j.xml build.properties
app.log.dir app.log.level Use of Log Viewer plugin in Eclipse
50
File Upload and Download in Web Applications
Pictures on online albums and social networking sites Attachments in web forum posts and web s Resumes on job search sites Student homework submissions in learning management systems (LMS) … …
51
File Upload – The Form <form action="FileUploadHandler"
method="post" enctype="multipart/form-data"> First file: <input type="file" name="file1" /> <br /> Second file: <input type="file" name="file2" /> <br /> <input type="submit" name="upload" value="Upload" /> </form>
52
File Upload – The Request
POST / HTTP/1.1 Host: cs.calstatela.edu:4040 […] Cookie: SITESERVER=ID=289f7e a2d7d1e6e44f931195 Content-Type: multipart/form-data; boundary= Content-Length: 509 Content-Disposition: form-data; name="file1"; filename="test.txt" Content-Type: text/plain this is a test file. Content-Disposition: form-data; name="file2"; filename="test2.txt.gz" Content-Type: application/x-gzip ?????????UC
53
Apache commons-fileupload
Maven dependency: commons-fileupload:commons-fileupload FileItemFactory fileItemFactory = DiskFileItemFactory(); ServletFileUpload fileUpload = new ServletFileUpload( fileItemFactory ); List items = fileUpload.parseRequest( request ); for( Object o : items ) { FileItem item = (FileItem) items; if( ! item.isFormFiled() ) {...} }
54
Handle File Upload in Spring
multipartResolver bean Support multiple request parser libraries See CSNS2 for example Add argument of type MultipartFile to the controller method
55
Store Uploaded Files In database On disk Pros and Cons?? BLOB, CLOB
BINARY VARCAR, VARCHAR On disk Pros and Cons??
56
File Download Generate an HTTP response directly Understand Java IO
Add an HttpServletResponse argument to the controller method Return null for view Understand Java IO Reader and Writer InputStream and OutputStream Use of the Content-Disposition header
57
Examples of Scheduled Tasks
Periodic s, e.g. Information about weekly sale Forum daily digests Member newsletters Payment reminders Batch data processing
58
Concepts in Task Scheduling and Execution …
Executor Use one thread for each task Use one thread for all tasks Use a thread pool Schedule (a.k.a. Trigger) E.g. every 5 minutes, every day at midnight, every first Sunday of each month at 8am …
59
… Concepts in Task Scheduling and Execution
Scheduler Task Schedule/Trigger Executor
60
Spring Configuration <task> namespace
<task:scheduler id="scheduler" /> <task:executor id="executor" pool-size="5"/> <task:annotation-driven scheduler="scheduler" executor="executor" /> Creates a scheduler Creates a thread pool Based executor Enables annotations @Scheduled and @Async
61
@Scheduled
62
Cron Expression Six field separated by space Seconds (0-59)
Minutes (0-59) Hours (0-23) Day of month (1-31) Month (1-12 or JAN-DEC) Day of week (1-7 or MON-SUN)
63
Cron Field Values Single value, e.g. 12 Set of values, e.g. 0,15,30,45
Range, e.g. 1-12,MON-FRI,* (first-last) Range with step, e.g. 1-12/3
64
Cron Expression Examples
Every hour at the beginning of the hour 0 0 * * * * 0 */10 * * * * 0 0 8 * * MON-FRI ,15 * * Every 10 minutes Every weekday at 8AM Every 1st and 15th of each month at 1AM
65
Problem with Java Exceptions
Too many checked exceptions Checked vs. Runtime exceptions Require lots of boilerplate exception handling code
66
Spring’s Solution to the Exception Problem
Use primarily runtime exceptions Separate exception handling code into exception handlers
67
Controller Exception Handing in Spring
An Exception Resolver handles all runtime exceptions thrown by controllers SimpleMappingExceptionResolver maps different exceptions to different views
68
ExceptionResolver in CSNS2
<bean id="exceptionResolver“ class="csns.web.resolver.ExceptionResolver"> <property name="exceptionMappings"> <props> <prop key="AccessDeniedException">exception/access</prop> <prop key=“MailException">exception/mail</prop> </props> </property> <property name="defaultErrorView" value="exception/default" /> </bean> A SimpleMappingExceptionResolver with additional logging.
69
Application Deployment
Deploy Application Computer for Development Server Hosting the Web Application
70
Directory Structure of a Java Web Application
Application Root Directory JSPs and static resources WEB-INF web.xml classes Compiled Java classes lib Additional Java libraries
71
WAR Files Web application ARchive
A JAR file for packaging, distributing, and deploying Java web applications Create WAR files The command line tool jar Eclipse Export -> Web -> WAR file mvn package
72
Deploy WAR Files to a Tomcat Server
Copy the WAR file to the webapps folder Use the Manager App Need a user with the manager-gui role More options at
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.