CGS – 4854 Summer 2012 Web Site Construction and Management Instructor: Francisco R. Ortega...
Preview:
Citation preview
- Slide 1
- Slide 2
- CGS 4854 Summer 2012 Web Site Construction and Management
Instructor: Francisco R. Ortega Chapter 5
- Slide 3
- Todays Lecture Brief review of Log4J Chapter 5 Remember
Mid-Term next class
- Slide 4
- Mid-Term Mid-Term June 21 st. Chapters 1,2,3 and 4. Possible
review for mid-term June 14 (after quiz 4) or June 19 Extra Credit
for Mid-Term Extra credit question : Regular Expressions (if
covered before the exam) You are allowed to bring two letter size
paper to the exam
- Slide 5
- ASCII Table (Part 1)
- Slide 6
- Regular Expressions Match strings of text (wiki) Sequence of
regular expressions is known as a pattern Regular expressions
contain Wildcards Special characters Escape sequences
- Slide 7
- Regular Expressions 101 Characters match themselves except:
[\^$.|?*+() \ suppresses the meaning of special characters []
starts a character class. We match one from the class. - specifies
a range of characters ^ negates a character class. matches any
single character except line break | matches either the left, or
the right (or)
- Slide 8
- Character Classes [xyz] : will match x or y or z [a-z] : will
match lowercase letters [a-zA-Z] : will match all letters [a-Z]
:will not match any letters (why?) [A-z] : will match all letters
but additional symbols. Why? [^abc] : Any character except for a,b
or c.
- Slide 9
- Predefined classes Character classMeaning.Any character except
line termination \dA digit: [0-9] \DA non digit [^0-9] \sA
whitespace character \SA non-whitespace character \wA word
character [a-zA-Z_0-9] \WA non word character
- Slide 10
- Escape Sequence \. : would match a period [.] : would match a
period \ does not lose special meaning inside square brackets
[\d]
- Slide 11
- Alternation yes|no yes|no|maybe It will match either yes,no or
maybae. But only one of them.
- Slide 12
- Grouping and Capturing (pattern) Capturing pattern. Can
retrieve values from \1 thru \9 Example Text: abyes3 [a-z] ([a-z])
(yes|no) \d \1 is equal to b \2 is equal to yes (?:pattern) Only
used for grouping
- Slide 13
- Ignoring case (?i)yes|no [yY] [eE] [sS] | [Nn] [Oo]
- Slide 14
- Repetition Repetition SymbolMeaning *Matches zero or more
occurrences of the preceding pattern ?Matches zero or one
occurrences of the preceding pattern +Matches one or more
occurrences of the preceding pattern {m,n}Range of times that the
pattern can repeat. ? Same as {0,1} {m}Range of exactly how many
times that will match the pattern. {m,}Range of at least times that
will match the pattern. + same as {1,}
- Slide 15
- Regex in java You will need to use two backslashes Regex: \d
Java regex: \\d
- Slide 16
- Hibernate (wiki) Mapping from Java classes to database tables
Mapping Java data types to SQL data types Data query and retrieval
facilities. Generates the SQL calls Required Validation
- Slide 17
- Hibernate Required Validation Uses annotations @Pattern(regexp
= , message = Some Message) There is a default message Annotations
@Pattern @NotNull (do not use with primitives) Annotations to be
used with Numbers @Min ( value = 20) @Max (value = 100) @Range(min=
0, max =100) Annotations for Collections will be covered in Ch.
6
- Slide 18
- Required Validation @Pattern(regex=".*\\S.*", message="cannot
be empty") @NotNull public String getHobby() { return hobby; } If
more than one annotation, then is assume that logical operator is
AND
- Slide 19
- Question.*\S.* In java .*\\S.*
- Slide 20 Aversion ${helper.errors.aversion} Aversion
${helper.errors.aversion}
- JSP Hobby ${helper.errors.hobby} Aversion
${helper.errors.aversion}
- Slide 21
- Min/Max
- Slide 22
- Creating Error Messages Class that performs validation is:
Validator Only one instance is needed Created from Validator
Factory Only one instance is needed
- Slide 23
- Creating Error Messages Protected static final ValidatorFactory
validatorFactory = Validation.buildDefaultValidatorFactory();
Protected static final Validator validator =
validatorFactory.getValidator(); Array of validation is created by
calling validators validate method. Set > violations =
validator.validate(data);
- Slide 24
- Implementing Validation Using the array provided by hibernate
Linear Search Using a Map (HashMap) Insert O(1) Get/Set O(1)
Contain Key Average O(1 + n/k) worst case is O(n) Where have we
seen something similar to the map structure in this class?
Request.getSession().setAttribute(helper,this);
- Slide 25
- Changes to Helper 1.errorMap 2.setErrors 3.getErrors()
4.clearErrors() All of this can be found in HelperBaseCh5 in the
shared folder.
- Slide 26
- HelperBaseCh5 HelperBase HttpServletRequest request
HttpServletResponse response Logger logger Map errorMap Abstract
copyFromSession() addHelperToSession() executeButtonMethod()
fillBeanFromRequest() setErrors() getErrors() isValid()
- Slide 27
- java.util.Map Example Map myMap = new HashMap "
title="Retrieving the Error Messages Hobby ${helper.errors.hobby}
">
- Retrieving the Error Messages Hobby ${helper.errors.hobby}
- Slide 33
- The Big Picture!
- Slide 34
- Summary Bean Validation annotations Helper Base (HelperBaseCh5)
Error map and interfaces for the error Controller Helper Modify the
logic for the buttons/actions JSP ${helper.errors.someField}
- Slide 35
- Post versus Get? Post does not encode data in URL Post has two
additional headers Content-Type Content-Length A blank line follows
content-length and then data is encoded in the request.
- Slide 36
- Post Request
- Slide 37
- Using Post Change the form method.
- Slide 38
- POST Request is only generated when button is clicked It allows
to know if is the first time in the form or not Hide Data No limit
to the amount of data. More secure??? GET Request is created when
Types url into browser Follows Hypertext link Click in button of
form
- Slide 39
- Controller Protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException
{ ControllerHelper helper = new
ControllerHelper(this,request,response); Helper.doPost(); }
- Slide 40
- ControllerHelper Public void doPost() throws ServletException,
IOException { addHelperToSession(helper,SessionData.READ); String
address = executeButtonMethod();
request.getRequestDispatcher(address).forward( request, response);
}
- Slide 41
- ControllerHelper Public void doGet() throws ServletException,
IOException { addHelperToSession(helper,SessionData.IGNORE); String
address = editMethod();
request.getRequestDispatcher(address).forward( request, response);
}
- Slide 42
- Hibernate: BEAN DB Focuses in the data Generate SQL statements
to save the bean Update a bean Remote a bean Create tables into
database
- Slide 43
- Hibertante jar files Zip files in moodle site and book site
Hibernate.zip and non-hibernate.zip Jar files needed for hibernate
(table 5.3)
- Slide 44
- Configuration Use java program Use XML
- Slide 45
- Configuration via java InitHibernate method in Controller
Helper Properties props = new Properties();
props.setProperty("hibernate.dialect","org.hibernate.dialect.MySQLDialect");
props.setProperty("hibernate.connection.driver_class",
"com.mysql.jdbc.Driver");
props.setProperty("hibernate.c3p0.min_size", "1");
props.setProperty("hibernate.c3p0.max_size", "5");
props.setProperty("hibernate.c3p0.timeout", "300");
props.setProperty("hibernate.c3p0.max_statements", "50");
props.setProperty("hibernate.c3p0.idle_test_period", "300");
props.setProperty("hibernate.connection.url","jdbc:mysql://SERVER:PORT
/DATABASE"); props.setProperty("hibernate.connection.username",
"USERNAME"); props.setProperty("hibernate.connection.password",
"PASSWORD");
initSessionFactory(props,RequestDataPersistent.class);
- Slide 46
- Configuration via XML XML overrides java configuration Place
file in the same directory as your classes. File name
hibernate.cfg.xml
- Slide 47
- Slide 48
- Creating Tables 1. Manually create the database 2. Add a
conditional statement in web.xml and created them in the
java.code
- Slide 49
- web.xml PersistentController ch5.persistentData.Controller
create false
- Slide 50
- Reading CREATE Boolean create =
Boolean.parseBoolean(servlet.getInitParame ter(create); if (create)
{ HibernateHelper.createTable(RequestDataPersistent.class); }
- Slide 51
- Simplify initHibernate Static public void initHibernate(boolean
create) { if (create) {
HibernateHelper.createTable(RequestDataPersistent.class); }
HibernateHelper.initSessionFactory(RequestDataPersistent.class)
}
- Slide 52
- Init controller See initHibernate page 165 If you are not using
xml See initHibernate page 181 If you are using xml In the
Controller public void init() {
ControllerHelper.initHibernate(this); }
- Slide 53
- Controller
- Slide 54
- Closing hibernate Configure a listener in web.xml
shared.WebappListener .
- Slide 55
- Closing hibernate use WebappListener in shared package. Why use
the listener?
- Slide 56
- WebappListener public class WebappListener implements
ServletContextListener { public void
contextInitialized(ServletContextEvent sce) {} public void
contextDestroyed(ServletContextEvent sce) { try { Enumeration
enumer = DriverManager.getDrivers(); while
(enumer.hasMoreElements()) {
DriverManager.deregisterDriver(enumer.nextElement()); } catch
(java.sql.SQLException se) { se.printStackTrace(); }
shared.HibernateHelper.closeFactory(); }
- Slide 57
- Persistent Annotations Annotate the bean with @Entity @Id
@GeneratedValue @Transient
- Slide 58
- @Entity Creates a table based on a bean Import
javax.persistence.Entity; @Entity public class
RequestDataPersistent implements Serializable { }
- Slide 59
- Primary Key @Id Specifies the primary key. Use @GeneratedValue
if you want automatic assigment. If Primary key is SSN, make sure
is not editable by the user.
- Slide 60
- Primary Key @Id Import javax.persistance.Id; Import
javax.persitance.GeneratedValue; Protected Long id; @Id @Generated
Value public Log getId() {return id;} private void setId(Long id) {
this.id = id;} ">
- Looping in JSP using JSTL ${row.id}, ${row.hobby},
${row.aversion}, ${row.daysPerWeek} {/core:foreEach>
- Slide 71
- Looping in JSP using JSTL
- Slide 72
- Using Persistent Data (page 177/178) 1.Add Hibernate Jar Files
2.Initialize Hibernate when controller is loaded into memory 3.Add
the WebappListener to shared Package 4.Add the Statements to the
web.xml file 5.Annotate the bean class as an entity 6.Add an Id
field to the bean (PersistentBase) 7.Add properties to bean
- Slide 73
- Using Persistent Data (page 177/178) 8.Add statements to
web.xml 9.Add initHibernate method to ControllerHelper 10.Modify
process Method (next slide) 11.In the process page, display the
data from the database using Expression Language
- Slide 74
- ControllerHelper: PersistentData Modify processMethod (see page
179) public String processMethod(){ if (!isValid(data)) { return
jspLocation(Expired.jsp); } HibernateHelper.updateDB(data); List
list = hibernateHelper.getListData(data.getClass());
Request.setAttribute(database,list); return
jsplocation(Process.jsp); }
- Slide 75
- PersistentBase Basic description of class follows
- Slide 76
- initSessionFactory Initialized hibernate for application static
public void initSessionFactory(Properties props, Class... mappings)
static public void initSessionFactory(Class... mappings) Examples
initSessionFactory(props,RequestDataPersistent. class)
initSessionFactory(props,bean1.class,
bean2.class,bean3.class,bean4.class,)
- Slide 77
- createTable Create tables from specified beans. static public
void createTable(Properties props, Class... mappings) Examples
createTable(props,RequestDataPersistent.class)
createTable(props,bean1.class,
bean2.class,bean3.class,bean4.class,)
- Slide 78
- closeFactory It closes the Hibernate Factory that was created
with the InitSessionFactory static public void closeFactory()
- Slide 79
- updateDB Updates database from bean or list of beans static
public void updateDB(Object obj) Single bean static public void
updateDB(java.util.List list) List of beans
- Slide 80
- saveDB Saves bean to Database. static public void saveDB(Object
obj)
- Slide 81
- removeDB Removes bean from DB static public void
removeDB(Object obj)
- Slide 82
- getListData static public java.util.List getListData( Class
classBean, String strKey, Object value) static public
java.util.List getListData( Class classBean, String strKey1, Object
value1, String strKey2, Object value2) static public java.util.List
getListData( Class classBean)
- Slide 83
- getListData
- Slide 84
- getFirstMatch static public Object getFirstMatch( Class
classBean, String strKey, Object value) static public Object
getFirstMatch
- Slide 85
- getKeyData static public Object getKeyData(Class beanClass,
long itemId)
- Slide 86
- isSessionOpen static public boolean isSessionOpen()
- Slide 87
- Next class We will start Chapter 6