PJS Outline

download PJS Outline

of 40

Transcript of PJS Outline

  • 8/8/2019 PJS Outline

    1/46

    Professional Jakarta Struts (ISBN 0-7645-4437-3)by James Goodwill & Richard Hightower

    last change 4/14/10

    Java Review

    Flow charts:http://jdurrett.ba.ttu.edu/Resources/Programming/index.htmlBasic MyEclipseChapter by Chapter Debugging in MyEclipse

    1) Chapter 1:Struts Introa) Jakarta project

    i) http://jakarta.apache.org/ii) http://struts.apache.org/iii) Model-View-Controller design pattern

    (p2 note about other patterns)

    (1) Model: supporting data objects usually with jdbc connections(2) View: JSP driven GUI representation of current state of Model (extensive use of tag lib(3) Controller: View-Model interface

    iv) Struts version of MVC (p3 chart & steps involved)

    b) Java Web applicationsi) Servletsii) JSPiii) Custom tag librariesiv) java classesv) Static HTML, etcvi)

    Web app deployment descriptor (web.xml p7, 67))vii) Directory Structure(1) .../wroxapp(2) .../wroxapp/WEB-INF xml config & tld files go here(3) .../wroxapp/WEB-INF/classes(4) .../wroxapp/WEB-INF/lib

    c) Tomcat servlet container (The following assumes individual installs not the All-in-one MyEclipse)i) Install java jdk first

    (1) I am using the 1.7.0x version in Linux & 1.6.0 in Windows(2) http://java.sun.com(3) Important: make sure the versions (32bit or 64bit) of java & Eclipse match

    ii) Now install Apache Tomcat(1) http://tomcat.apache.org(2) Use only the release builds(3) If you have errors installing the first time, set an environment variable

    JAVA_HOME=C:\where\ever\jdk\is then try againiii) Then install your IDE

    (1) If using eclipse and MyEclipse (docs are here)(a) Eclipse (3.4 Works Now) first:http://www.eclipse.org/

    if you have zip problems get WinZip(b) then MyEclipse (8.0GA):http://www.myeclipseide.com

    if you have install problems use the manual install version

    http://jdurrett.ba.ttu.edu/Resources/Programming/index.htmlhttp://jakarta.apache.org/http://struts.apache.org/http://java.sun.com/http://www.myeclipseide.com/module-htmlpages-display-pid-7.htmlhttp://www.eclipse.org/http://www.myeclipseide.com/http://jdurrett.ba.ttu.edu/Resources/Programming/index.htmlhttp://jakarta.apache.org/http://struts.apache.org/http://java.sun.com/http://www.myeclipseide.com/module-htmlpages-display-pid-7.htmlhttp://www.eclipse.org/http://www.myeclipseide.com/
  • 8/8/2019 PJS Outline

    2/46

    (c) Put jdk bin directory at first of PATH

    (d) ** Note as of MyEclipse 6 the All in One installation does everything in Windows *==================================================

  • 8/8/2019 PJS Outline

    3/46

    2) Servlet & JSP Overviewa) I assume some familiarity from previous Classesb) JHTP 5th editionServlets (ch24), JSP (ch25)c) Servlets

    i) Figure 2.2: HttpServlet Object Model (Sun's Reference Site& Servlet API)

    ii) Setting up book code examplesiii) Lifecycle: contructor, init, service, destroyiv) SimpleServlet (L 2.1)v) Deploying a servlet exploded and as war filevi) Servlet Context

    (1) Facilitates servlet-container communication(2) Storage area for objects available to all components in a webapp(3) Every webapp has only one ServletContext(4) getAttribute(), setAttribute, getAttributeNames()(5) ContextServlet.java (p21): jsp will return could not find...

    (a) implicit objects in Context.jsp (23): application, out

    (6) run context servlet on zeus(7) then rerun Context.jspvii) Http data

    (1) ServletRequest methodsString getParameter(String name)String[] getParameterValues(String name)java.util.Enumeration getParameterNames()ParameterServlet.java (26) & Form.html(28)

    d) JSP: jsp quick reference cardsi) Steps of a JSP request (fig 2.9 p 31)

    (1) Request: container recognizes the extension & passes to JSP engine(2)

    First time requested since change, jsp is used to create a servlet(3) Servlet is compiled & run(4) Response is sent back to client

    ii) Components of a JSP(1) JSP Directives provide global info about a jsp page (p32)

    (a)

  • 8/8/2019 PJS Outline

    4/46

    (c) (i) more html

    etc

    (3) JSP Error Pages(a) errorpage.jsp (36)

    (b) testerror.jsp (37)(4) Implicit Objects

    (a) out(b) request (request.jsp 39)(c) response(d) pageContext(e) session (session.jsp 40)(f) application(g) config(h) pagesexception

    (5) Object scope: page vs request vs session vs application

    (6) Standard Actions (p42+)(a) (b) (c) (d) Example: Counter.java (45), counter.jsp (46)

    (e) providesparameters for include, forward, & plugin

    (f) evaluated each time page is requested asopposed to include directive include.jsp (48)

    (g) (i) forward.jsp (50), welcome.jsp (51), management.jsp (51)(ii) http://localhost:8080/ch02app/forward.jsp?role=user;user=Bob

    (h) ...

    (i) seequick reference card, Cheat-Sheets.org,==================================================

    e) JavaServer Facesi) Horstmann Core JSF links

    http://localhost:8080/ch02app/forward.jsp?role=user;user=Bobhttp://java.sun.com/products/jsp/docs.htmlhttp://java.sun.com/products/jsp/docs.htmlhttp://www.cheat-sheets.org/#JavaServerFaceshttp://horstmann.com/corejsf/http://localhost:8080/ch02app/forward.jsp?role=user;user=Bobhttp://java.sun.com/products/jsp/docs.htmlhttp://www.cheat-sheets.org/#JavaServerFaceshttp://horstmann.com/corejsf/
  • 8/8/2019 PJS Outline

    5/46

    3) Struts Apache User Guidea) jakarta.apache.org --> struts.apache.org --> why are we using struts 1.1 ???

    b) Installation with / without MyEclipsei) WEB-INF/lib Tomcat/common/libii) web.xmliii) struts-config.xmliv) tld definitions

    c) A New struts webapp using MyEclipsei) file-new-Web Application

    (1) gives directory structure & web.xml file (steps 2 & 4)

    ii) MyEclipse-Add Struts capabilities(1) look at config path, action servlet name, servlet url pattern, base package (ch03), instal(2) when Finished have jars, struts-config.xml, web.xml, tld files (steps 1, 3, & 5)

    -----------------------------------------------------------

    d) The first struts webapp

    i) index.jsp view: create the query view(1) file-new-jsp struts 1.1 with a form

    (a) lots of tag lib defs + basic jsp with html:form tags

    (2) fix form to match book index.jsp(3)

  • 8/8/2019 PJS Outline

    6/46

    (a) extend org.apache.struts.action.Action(2) paste code from example into new class(3) remove all the Wiley logging stuff (4) edit struts-config.xml file to match p65

    (a) be careful using right click on the outline

    v) Deploying: MyEclipse changed the web.xml file already(1) servlet def in p66(2) servlet-mapping on p66(3) web.xml file on p67

    vi) Run it, remember to use SUNW if you want a quote(1)

    (a) 1 creates necessary html code for form

    (b) 2 checks for instance of LookupForm in session scope

    (c) 3 submit causes/ch03app/Lookup.do to be called(i) this uses the action-mapping to call the ActionServlet

    (d) 4 ActionServlet looks for an ActionMapping entry that matches Lookup(i) creates ActionMapping objects for all values in action-mapping element(ii) creates LookupAction(iii) calls LookupAction.execute(...)(iv)when control returned to ActionServlet it uses returned ActionForward to call ap

    view

    vii) Other ways to create simple web app

    ==================================================

  • 8/8/2019 PJS Outline

    7/46

    4) Actions & ActionServletThe Controller components: ActionServlet.class, Action.class, Plugins (which we will mostly ignoRequestProcessor

    a) ActionServlet

    When a request is received:i) doGet() or doPost() invoke the process() methodii) process() gets current RequestProcess and calls process() methodiii) RequestProcessor.process()

    (1) Uses struts-config action element to match request path(2) Uses action name attribute to match form-bean

    iv) Creates or retrieves form beanv) Populations the beanvi) Validates using ActionForm.validate() method if requiredvii) Creates an Action class and calls Action.execute()

    viii)When processing returns a ActionForward object uses it to send control to targetix) Configuring ActionServlet:

    (1) Init parameters in web.xml (table 4.1 pg 76)

    b) Action ClassThe most common component in struts webapps

    i) Create class that extends Actionii) Implement the execute() methodiii) Return ActionForward object

    iv) Put action element in struts-config.xmlv) Put class and xml files on server

    vi) Configuring Action classes(1) Path attribute in action element must be unique(2) Class can be reused as required by other unique paths(3) Forward, input, path, & type attributes in Table 4.3 pg 82

    c) Pluginsi) Must implement the org.apache.struts.action.Plugin interfaceii) Useful for allocating resources (properties files), setting up jdbc or jndi, & other init functio

    ex: tiles.TilesPlugin & validator.ValidatorPluginiii) Create a class that implements the Plugin interfaceiv) Add an empty constructor, a init(ActionServlet, ModuleConfig), & a destroy() method

    v) Put what you want to happen at application startup in the init methodWe will use logging fromhttp://logging.apache.org/log4j/1.2/index.html & reading a properties fil

    vi) Add the to the main struts-config.xml filePlease note from the example that this must be the last element in the config file

    vii) Put controller element in struts-config file after action-mapping and before message-resour(listing 4.3 pg 89)

    http://logging.apache.org/log4j/docs/http://logging.apache.org/log4j/docs/http://logging.apache.org/log4j/docs/
  • 8/8/2019 PJS Outline

    8/46

    d) Logging with log4ji) Logging in any webapp is critical to track problems, use of the system, &/or development pii) System.out.println or err.println can be used but is not as effectiveiii) Get the log4j jar file from the apache.org web site aboveiv) Put the jar file in your projects WEB-INF/lib folder and click Refresh in eclipse

    v) Theonline docsat the apache site are the best source of info on the properties file and its logappenders, conversion patterns, log levels, etc vi) Please note priority of log levels is debug < info < warn < error < fatal and that incoming lo

    request must be equal to or greater than the system loggers level set in the properties file to printed

    --- To use the default tomcat logging system --- vii) Create a log4j.properties file (leave that as the name) and put it in the root of your src folde

    #Example log4j.properties filelog4j.rootLogger=INFO, fileoutlog4j.appender.fileout=org.apache.log4j.RollingFileAppender

    log4j.appender.fileout.File=/home/durrett/temp/durrett.loglog4j.appender.fileout.MaxFileSize=10MBlog4j.appender.fileout.MaxBackupIndex=10

    log4j.appender.fileout.layout=org.apache.log4j.PatternLayoutlog4j.appender.fileout.layout.ConversionPattern=%d %-5p %-30.30c{1} %x - %m%n

    viii)For any class where you wish to use logging(1) import the commons logging jars

    import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;

    (2) Create a class level static attribute private static Log log = LogFactory.getLog(FindDogAction.class);Please note the logger naming convention

    (3) Anytime you wish to output logging informationif (log.isInfoEnabled()) { log.info("Getting dogtype property"); }

    -- The next part assumes you are creating a Plugin to initialize your own logging system ---ix) Create a log4j.properties (log4j.pjsprops) file and put it in your WEB-INF folder

    Please note that putting the log4j.properties file in WEB-INF/classes overrides the default lx) Initialize a static Logger object in your PlugIn class

    public static Logger pjsLog = Logger.getLogger(A1);xi) Configure the pjsLog object

    String fullPathtoYourWebapp = servlet.getServletContext().getRealPath("/");PropertyConfigurator.configure(fullPathtoYourWebapp + /WEB-INF/log4j.pjsprops);

    xii) Anywhere in your application that you want to log use the instructions from viii above andLogger pjsLog = Logger.getLogger("A1"); // get the specific logger you created in your pjsLog.info("Symbol: " + sStk);

    http://logging.apache.org/log4j/1.2/index.htmlhttp://logging.apache.org/log4j/1.2/index.html
  • 8/8/2019 PJS Outline

    9/46

    e) Properties filesi) Setup a properties file. This can be xml or java properties (the version I use in the pjs proje

    SYSTEM_TITLE=Professional Jakarta Strutsii) Save the file in the WEB-INF folder of your appiii) Create a file object

    File file = new File(fullPathtoYourWebapp + "/WEB-INF/props.txt");iv) Open a FileInputStream: FileInputStream fis = new FileInputStream(file);v) Load the properties: properties.load(fis);vi) Add the properties to the ServletContext (the webapplication memory space)

    ServletContext context = servlet.getServletContext();context.setAttribute(PROPERTIES, properties);

    vii) You can use the set properties anywhere in your webapp like this:ServletContext context = request.getSession().getServletContext();Properties rProperties = (Properties)context.getAttribute("PROPERTIES");String sTitle = rProperties.getProperty("SYSTEM_TITLE");

    f) RequestProcessorWhen customizing ActionServlet this is where to start

    i) Create a class that extends action.RequestProcessor ii) Override processPreprocess() methodiii) Return true for success ie continue as normaliv) Return false for processing completed, ie do not call Action

    v) Put controller element in struts-config file after action-mapping and before message-resour(listing 4.3 pg 89)

    ============================================

  • 8/8/2019 PJS Outline

    10/46

    5) Advanced Action Classes

    a) Design Notesi) Limit the business logic in your jsp

    (1) jsp's are for user views,

    they DO NOT talk to the model, they only display pieces of it(2) Actions are for control & select the next view not the jsp(3) the struts-config.xml file controls ALL system flow(4) Helper object models implement business logic

    b) Forward Actions (basic)i) Typical link:

  • 8/8/2019 PJS Outline

    11/46

    e) DynaLookupForm

  • 8/8/2019 PJS Outline

    12/46

    6) The Presentation Layer: Struts Views

    a) Building aViewA view is a combination of JSP's, Tag libraries, and Form beans

    i) JSP's serve two main functions:1) to present results of controller actions2) to gather data

    ii) Gathering Data

    (1) action must match complete path defined in struts-config fileActionForm must be defined in action name attribute

    optional attributes(a) focus=name of initial focus attribute

    (2) resulting html:

    (3) property must be a property in the ActionForm class

    optional attributes(a) value=initial value of attribute(b) readonly=true if desired

    (4) resulting html

    userid :

    (5) struts-config

    iii) ActionForm Beans(1) get & set Methods for each attribute(2) reset() method called to reset all attributes to default values This help avoid stale being left in form bean

    (3) struts-config

  • 8/8/2019 PJS Outline

    13/46

  • 8/8/2019 PJS Outline

    14/46

    iv) Steps in submission of struts form

    (1) Controller creates (or retrieves) instance of LoginForm & stores it in session(2) Controller calls LoginForm.reset()(3) Controller populates LoginForm object with data from html:form attributes

    (4) Controller invokes LoginAction.execute method(5) Controller forwards processing to appropriate jsp after execute returns ActionFor

    v) DynaActionFormDynamic ActionForm for use with simple data inputs

    (1) Add form-bean element to struts-config file

    (2) Create data input jsp (DynamicLogin.jsp)only difference is the action name

    (3) Create new action class (DynamicLoginAction)the only changes needed are to the followinglines

    // Use the DynamicForm to get the request parameters

    //LoginForm lf = (LoginForm) form;DynaActionForm lf = (DynaActionForm)form;

    // make sure arguments match form-property names//String su = lf.getUserid(), sp = lf.getPassword();String su = (String)lf.get("userid"),

    sp = (String)lf.get("password");

    (4) Add DynamicAction to struts-config file

    ============================================

  • 8/8/2019 PJS Outline

    15/46

    7) Debugging Struts

    8) Custom Action Mappingshttp://struts.apache.org/userGuide/index.html

    a) ActionMapping class

    i) An ActionMapping object describes an Action instance to the ActionServletIt uniquely defines an instance of a particular action classThey are setup / defined by the action element in the struts-config file

    b) CustomAction Mappings

    i) allow addition of parameters to custom ActionMapping classes

    c) Attributesof ActionMapping Object in struts-config file (p 144)

    i) className -- fully qualified ActionMapping class nametypically used for custom ActionMappings

    ii) type Action class that will process the request

    iii) input where to return control if ActionErrors are returned

    iv) name ActionForm key

    v) path Context relative path of submitted request, must start with /used by ActionServlet to determine which Action to call for each request

    vi) parameter used to pass additional arguments to Action objectfor instance the parameter=method in the DispatchAction

    d) Creating acustom ActionMapping

    (1) Extend ActionMapping(a) Create new class such as:public class WroxActionMapping extends ActionMapping

    (b)Add new properties: add property, get and set methods

    (c) make sure to call super() as first line in constructor

    (2) Setup struts-config file action element to use new ActionMapping(a) add className attribute to action element definitionclassName=ch08.WroxActionMapping

    (b) add new set-property element

    (3) Create Action class that utilizes new Attribute in ActionMapping sub classWroxActionMapping wm = (WroxActionMapping) mapping;if (wm.getLogResults()) ...

    http://struts.apache.org/userGuide/index.htmlhttp://struts.apache.org/userGuide/index.html
  • 8/8/2019 PJS Outline

    16/46

    9) Internationalizing Struts (i18n)

    a) i18n Componentsi) Resource bundle based Message classii) tag

    b) Controller i) java properties file containing key=value pairs

    ex:app.symbol=Symbol

    ii) ApplicationResources.properties (default file)iii) ApplicationResources_ language _ COUNTRY .properties (naming pattern)

    (1) ApplicationResources_en_US.properties(2) ApplicationResources_it_IT.properties

    (3) supported locales:http://java.sun.com/j2se/1.4.2/docs/guide/intl/locale.doc.html

    iv) Resources filename can be anything. Depends on config file settingv) When changing resource messages webapp must be reloaded or tomcat restarted

    c) Deployment of resource bundle

    EITHER i) web.xml file

    (1) servlet element(2)

    (3) ex:

    applicationApplicationResources

    OR ii) struts-config.xml file

    (1)

  • 8/8/2019 PJS Outline

    17/46

    10) Managing Errorsa) ActionError pattern is key, placeholder, may have 0-4 placeholders or use array

    i) new ActionError(String key)

    ii) new ActionError(String key, Object objRef)iii) new ActionError(String key, Object ...)

    iv) ex new ActionError(errors.sql.insert.one);

    b) ActionErrors

    i) ActionErrors errs = new ActionErrors()ii) errs.add(some_property_value, new ActionError(somekey));iii) property value is the property in the input jsp that caused the error

    c) ActionForm validate method returns ActionErrors Object Reference

    d) struts-config (pg 162)

    i) validate=trueii) input=/where_the_error_came_from.jspusually a jsp with a struts-based input form

    e) ActionForm

    i) public ActionErrors validate(ActionMapping mapping, HttpServletRequest request)

    ii) ex: (pg 164) public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {ActionErrors errs = new ActionErrors(); if (some test is true) {

    errs.add(this param, new ActionError(errors.sql.select.only));}

    return errs;

    f) ApplicationResources.properties (pg 165)

    i) errors.header= Error Listii) errors.footer= iii) errors.sql.select.only= Sorry only select is currently supportediv) errors.sql.sqlerror= {0} Note the use of the {0} as placeholderplaceholders are formatted according to java.text.MessageFormat

    g) jsp'si) tag (pg 166)

  • 8/8/2019 PJS Outline

    18/46

    (1) any where in jsp(2) be careful of tags inserted by MyEclipse

    h) Action.exec

    ute (pg 168)

    (1) test for error condition

    (2) set forward string to failure

    (3) create ActionErrors objectActionErrors errs = new ActionErrors();

    (4) add ActionError to ActionErrors objecterrs.add("sql", new ActionError("errors.sql.sqlerror", sqlException.getMessage())); (5) save ActionErros if not empty collectionsaveErrors(request, errs);

    (6) return ActionForward

    (7) As long asthe key used in the ActionError constructor is in the ApplicationResources.properties fi or is in the input or failure forward jsp

    IT WILL WORK, hopefully :-)

    Example Steps

    1. Create /ch10/index.jsp copy index.jsp from ch09/2. Change actions in ch10/index.jsp3. Change struts-config: add new actions for ch10 (copy ch9, change paths & forwa4. Edit ch09.LookupForm: change validate method & add ActionError import5. Add error message key used in 4 to ApplicationResources files6. Add error.header & error.footer to ApplicationResources files

    Run the project in tomcat, put in no symbol

    7. Edit the struts-config file and put in validate=false in the ch10 actionReload & run test it again

    8. Change the validate to true9. Edit the ch09.LookupAction & add no symbol found error check 10. Add unknown symbol error to ApplicationResources files11. Remove

  • 8/8/2019 PJS Outline

    19/46

    11) Jakarta Commons Database Connection Pool (DBCP)a) Provides afaster reusable pool of datasourcesb) does NOT provide transaction management, (please see ibatis notes that follow this chapter)

    c) Manages thdriver loading and connection process for youd) Steps:

    (1) Create the database and add rows (p 172-173)(2) Create a ch11 directory(3) Copy the displaytag/index.jsp file to the new dir (or create a new jsp that inputs a sql statement and allows display of the result set)(4) Copy (or create new) displaytag package to ch11 package dir (5) Edit ch11/index.jsp & ch11/SQLForm (I eliminated all inputs except sql)(6) Edit ch11/SQLAction(a) Change source from

    Class.forName( com.mysql.jdbc.Driver ):connection = DriverManager.getConnection (

    to

    javax.sql.DataSource ds = getDataSource(httpservletrequestObj, DATASOURCE_Kconnection = ds.getConnection();

    (7) Edit struts-config (for Eclipse V 3.1.0 MyEclipse V 4.0.3):(a) new form to match new ch11.SQLForm above (do not duplicated form-bean name)(b) new action to match new ch11.SQLAction (do not duplicate path & use new input &(c) create new DataSource making sure to:

    (i) put in correct user and password(ii) put in correct url (jdbc:mysql://localhost:3306/Reference)(iii) have a minimum count of at least 1(iv)put in correct driver (com.mysql.jdbc.Driver)(v) if creating more than one DataSource put in unique key

    (8) Edit master index if you have one(9) Redeploy (sometimes you have to recreate the deployment description in MyEclipse)

    (10) Copy the mysql.connector jar file to the tomcat/common/lib folderMyEclipse does not deploy it and will erase it from the WEB-INF/lib folder

    (11) Run the query and process the results

    (12) Note in Tomcat output:(a) createConnection(b) getConnection(c) releaseConnection instead of closing if you have con.close() in your code

  • 8/8/2019 PJS Outline

    20/46

    ============================================

  • 8/8/2019 PJS Outline

    21/46

    12) Validator PluginValidation of form input while not required is good practice, enables reuse, & follows MVCThis chapter shows how to use the Validator Plugin to replace or augment the validate method

    ---- validator.xml in the text is validation.xml in the blank struts app ----

    a) Steps increating a form (pg 182) Note:if using modules remember to place the struts-config file in a sub folder of WEB-INF

    i) 1. Create an ActionForm class or decide to use DynaActionForm (p183)ii) 2. Create an Action (LoginAction) (p183)iii) 3. Setup a resource bundle (ch12.ApplicationResources)Convention is: formName.propertyName = Some error message

    iv) 4. As you work add keys & labels to the jsp's and resource bundleRemember the goal is that all static text is removed from the jsp

    v) 5. Create an input jsp (login,jsp) using the action form & fields (step 1) above (p184) be careful using value=something attributes in the html:text element.They will override previous entries in the form

    vi) 6. Use keys from resource bundle for all prompts (step 4)vii) 7. Add form bean declaration to the module (or default) struts config file (p185)viii) 8. Add Action mapping to the module (or default) struts config fileix) 9. Create a response page to return as the success view

    To add validation to the project

    x) 10. Add the Validator plugin to the config file

    xi) 11. Copy the validator-rules.xml and validation.xml files into WEB-INFor the module folder under WEB-INF

    GOTCHA:be very sure you are using the same versions of your struts.jar & the validator xmif you do not you will get strange errors like this:

    java.lang.NoSuchMethodException:org.apache.struts.validator.FieldChecks.validateRequired(java.lang.Object,org.apache.commons.validator.ValidatorAction,org.apache.commons.validator.Field, org.apache.struts.action.ActionMessages,javax.servlet.http.HttpServletRequest)

    xii) 12. Subclass ValidatorForm instead of ActionForm in your form (step 1 above)public class RegistrationForm extends ValidatorForm {GOTCHA: if you have a validate method make sure to call super.validate and assign the res

  • 8/8/2019 PJS Outline

    22/46

    ActionErrors object. Only then can you run your own validation logic and add errors to thActionErrors object.

    xiii) 13. Add a form to the form sets in the validation.xml file Note: When debugging watch the console output in Eclipse.Small errors like zipcode instead of zipCode will show up easily

    Note: regular expressions and the mask rule are very powerful

    xiv)14. Add a field, rules, errors, & error arguments to the form set created in step 13xv) 15. Add error messages to the resource bundle for all errors created in step 14 Note: use the examples from the top of the validator-rules.xml file as a start

    xvi)Misc. Points:Two Rules with one depends, regular expression masks, constants, dates

    b) Overriding the validate method, ex:validation between two fields

    public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {ActionErrors errs = super.validate(mapping, request);

    if (!password.equals(passwordChk)) {errs.add("password", new ActionError("errors.password.mismatch"));

    }return errs;

    }

    c) Writing Your own rulesi) 1. Create a java class (it can extend anything you wish)

    public class ValidatePassword

    ii) 2. Add a static validation methodpublic static boolean matchPasswords(Object bean, ValidatorAction va, Fieldpass1,

    ActionErrors errors,HttpServletRequest request) {

    return true if everything is ok false if not

    iii) 3. Create an entry in the validator-rules.xml file< validator name ="passwordmatch"

    classname ="util.ValidatePassword" method = "matchPasswords" methodParams ="java.lang.Object,

    org.apache.commons.validator.ValidatorAction,

    org.apache.commons.validator.Field,org.apache.struts.action.Actio

    nErrors,javax.servlet.http.HttpServlet

    Request" msg ="errors.password.mismatch" >

    iv) 4. To use your new rule simply follow steps 13 15 above

    d) DynaActionForms

  • 8/8/2019 PJS Outline

    23/46

    useDynaValidatorForminstead of DynaActionFormin the form-bean element

    < form-bean name ="inputform"type = "org.apache.struts.validator.DynaValidatorForm" > < form-property name ="userName" type ="java.lang.String" initial ="" />

    e) Client-Side JavaScriptSaves round trip communication requirementsEach validator in the validator-rules.xml file can have script associtated with itCan add a js file with all scripts to enable caching by browser

    (1) Add < title >< bean:message key ="registration.title" />

    (2) Add onsubmit attribute to html:form tagif return statement left out of submit both validations (client & server) will run

    (3) Add cancel Boolean variable to < li >

  • 8/8/2019 PJS Outline

    24/46

    g) Wizard style Work Flow: or multiple jsp for the same ActionForm / Validate processi) Benefits:

    Allows multiple jsp to access a single formAllows Wizard style input streams

    Basic Process (this is slightly different from the text)(1) Change Action to subclass DispatchAction (see ch5, p97)

    this makes small incremental actions possible

    public class PhasedRegisterAction extendsorg.apache.struts.actions.DispatchAction {

    public ActionForward step1(

    public ActionForward step2(

    (2) Create new Form to hold new stream of input data(3) Add parameter=method to new Form allow passing of method to Action

    ie. if method=step1 then the Action.step1 method will be usedremember to add getMethod() and setMethod()

    private String method;

    public String getMethod() { return method; }public void setMethod(String s) { this.method = s; }

    (4) Create two input jsp(my examples are reg1.jsp & reg2.jsp and are simply segments of the previous version)

    (5) Add two form & action-mappings to struts-config

    < forward name ="success" path = "/reg2.jsp" /> < forward name ="failure" path = "/reg1.jsp" />

    < forward name ="success" path = "/Welcome.jsp" /> < forward name ="failure" path = "/reg2.jsp" />

    (6) Create two input jsp, use the new form and actions created above(7) Add a hidden field to the jsp to identify the Action method to use

    for example on the first step input jsp:

  • 8/8/2019 PJS Outline

    25/46

    Test it now, if you look at the form data when you are in the second input phase (either debSystem.err.println) you will notice everything from the first input is gone.The problem is request scope.

    (8) In the action-mappings in the struts-config file, change form to session scope to allow access

    < forward name ="success" path = "/Welcome.jsp" /> < forward name ="failure" path = "/reg2.jsp" />

    (9) Modify validation.xml & make necessary changes to the Form and the Action classes tvalidationFollowing the books naming(a) Add an additional hidden field for page to each of the input jsp

    Notice that you can either set the page variable value in the Action as the book does or as a static value in the tag as I do above.

    (b) Add a new validation form to the validation.xml file & setup all field validation rul

    (c) Add a page=? attribute to each field element indicating where (on which jsp) the fshould be validated

  • 8/8/2019 PJS Outline

    26/46

    13) Tiles or visual struts componentsGoal is reusable presentation components & ability to standardize webapp views

    a) Definitions & Overviewi) Tiles are reusable visual components (page == tile)ii) Arguments are passed to Tiles as parameters in tile scopeiii) Tile scope is similar to page scope, less general than request scopeiv) Parameters and Arguments are available ONLY to the tile they are passed tov) Tile layouts can provide default argument to tiles

    That means the individual visual components need override only those args specific to themvi) A region is an area in a tile layoutvii) A TileDefinition defines parameters for calling a tile layoutviii)Tile definitions can extend other definitionsix) The tiles framework provides a custom RequestProcessor

    There are several ways to define a site layout in my opinion the xml version is best

    b) Steps in creating and using a tile layout (METHOD 1)(1) Find the similarities between jsp or design the structure of a web site(2) Create a new layout page

    (a) Import the Tiles taglib into the jsp

    versus

    (b) Use

    (c) Use

  • 8/8/2019 PJS Outline

    27/46

    < tiles:put name = "footer"value ="footer.jsp" /> < tiles:put name = "content"value ="indexContent.jsp" />

    Example passing text (html) as region component

    < tiles:put name ="title" type ="string"value ="Wrox Stock Quote" />

    < tiles:put name ="header"value ="header.jsp" /> < tiles:put name ="footer"value ="footer.jsp" /> < tiles:put name ="content"type = "string" >

    (d) Build the component pages (footer.jsp, header.jsp, & indexContent.jsp above)

    c) creating and using a tile layout definition in a non visual jsp (METHOD 2)tile definitions add the ability to pass default parameters, this ability helps limit code repetition

    (1) import the Tiles tag library(2) use < tiles:put name ="footer" value ="/footer.jsp" /> < tiles:put name ="content" type ="string" > Content goes here

    Create the page that uses the new layout definition(5) Use

  • 8/8/2019 PJS Outline

    28/46

    < tiles:put name ="content" value = "indexContent.jsp" />

    d) creating and using a tile layout definition in a non visual XML (METHOD 3)

    (1) Add the Tiles plugin for struts to the struts-config file

    (2) Create a new

    Content goes here

    .

    (3) Replace the beanName and beanScope tags in the previous index2.jsp (index3.jsp)

    < tiles:put name ="title" type ="string" value ="Get Wrox Stock Quote3" />

    < tiles:put name ="content" value ="indexContent.jsp" />

    e) Notes:i) If you are using modules remember to make all the jsp in tile:put tags relativeii) If you have set the validate xml property in the plugin to true

    < set-property property ="definitions-parser-validate" value ="true" />Remember to include a link to the dtd in the tiles-defs.xml file

  • 8/8/2019 PJS Outline

    29/46

    iii)

  • 8/8/2019 PJS Outline

    30/46

    14) Developing a Complete Struts applicationA link to a similar article from The Server Side:Struts Redirect-after-PostThese notes follow the creation of the employees application in PJS: Ch14 as adapted to our systea) Basic Tomcat / eclipse /MyEclipse / MySql webapp setup

    (1) Create anew Project (I followed the book and named mine employees)

    (2) Use MyEclipse toadd struts capabilities(I used com.wrox as the base package and employeesResources for the resource file)(3) Add themysql jdbc driver jar file to your java build path(4) Create an Englishresource bundle (Listing 14.3 pg 247)(5) Create the /WebRoot/images folder with required images(6) NOTE: Setting up the tag libraries. In the book the authors always put tag lib def

    web.xml file, however when using our environment none are ever found there. The folnote fromhttp://struts.apache.org/userGuide/configuration.htmlexplains why:

    Servlet 2.3 users only: The Servlet 2.3 specification simplifies the deployment and configuration of tag libraries. The instructions above will work on older containers as well as 2.3 containers (Strutsonly requires a servlet 2.2 container); however, if you're using a 2.3 container such as Tomcat 4.x,

    you can take advantage of a simplified deployment.

    All that's required to install the Struts tag libraries is to copy struts.jar into your /WEB-INF/libdirectory and reference the tags in your code like this:

    Note that you must use the full uri defined in the various tlds (see the example configuration for reference) so that the container knows where to find the tag's class files. You don't have to alter your web.xml file or copy tlds into any application directories.

    (7) Create the employeesdatabase :mysqladmin create employees -u root pgrant all privileges on employees.* to '4383'@'%' identified by 'durrett';grant all privileges on employees.* to '4383'@'localhost';mysql -p employees < mysqlscripts.sql(I removed the first two line so that I could add my own new db and user)

    b) Create the basic data model objects(1) com.wrox.Employee.java

    (a very simple struts form)

    (2) com.wrox.EmployeeData.javaProvides the webapp --- business model interface

    (3) Add thedata-source element to your struts-config fileRemember to change the username and password

    http://opt/scribd/conversion/notpublic/struts-Redirect-after-post-Jouravelev.pdfhttp://struts.apache.org/userGuide/configuration.htmlhttp://opt/scribd/conversion/notpublic/struts-Redirect-after-post-Jouravelev.pdfhttp://struts.apache.org/userGuide/configuration.html
  • 8/8/2019 PJS Outline

    31/46

    c) Create the list, add, edit, & delete transactions for the employee databasei) Welcome

    (1) create the index.jsp page (it is a simple forward to the EmployeeList action)

    (2) add the index.jsp url to the welcome-file-list element in the web.xml file

    ii) list employees(1) Create the com.wrox.EmployeeListAction .java

    (2) Create the /WebRoot/employeelist.jspSince we did not put the tag defs in web.xml, remember to change the uris in the jsp

    Also, note the edit and delete links for each employeeEdit Delete

    (3) Add the /EmployeeListaction-mapping to the struts-config file

    iii) add employee(1) Create the /WebRoot/addemployee.jsp

    (2) Create the com.wrox.EmployeeForm.javathe reset method simply sets the default valuesthe validate method enforces not null requirements of the employees table

    (3) Create the com.wrox.AddEmployeeAction.java

    (4) Add the employeeFormform-bean and the the /Addaction-mapping to the struts-config file

    iv) edit employee(1) Create the com.wrox.GetEmployee.java

    (2) Create the /WebRoot/editemployee.jsp(3) Create the com.wrox.EditEmployeeAction.java

    (4) Add the /Edit & /EditEmployee paths to theaction-mappings in the struts-config file

    v) delete employee(1) Create the com.wrox.DeleteEmployeeAction .java(2) Add the/Delete path to theaction-mappings in the struts-config file

    vi) test the webapp, every thing should work

  • 8/8/2019 PJS Outline

    32/46

    15) The struts-config.xml FileAn amplification / overview of the heart of any struts projecthttp://struts.apache.org/dtds/struts-config_1_2.dtd

    resources*, plug-in*)>

    The elements must be in exactly this order (they must follow the dtd listed above)

    a) XMLi) Elements are delimited by angle brackets and identify the nature of the content they surrouii) The elements content model follows the element name.iii) ? in the content model indicate optional sub-elements that can occur only onceiv) * in the content model indicate optional sub-elements that may occur zero or more timesv) + indicate optional sub-elements that must occur once but can more timesvi) Attributes are name-value pairs that occur inside start-tags after the element namevii) % identifies a parameter entry in an element definitionviii) Comments begin with

    (1) A CDATA section instructs the parser to ignore most markup characters

    What ever code>

    Between the start of the section, , all character data isdirectly to the application, without interpretation

    b) Top-level sub-elementsi)

    ii)

    iii)

    iv)

    < set-property property ="minCount" value ="" />

    c) data-sources

    < data-sources >

    http://struts.apache.org/dtds/struts-config_1_2.dtdhttp://struts.apache.org/dtds/struts-config_1_2.dtd
  • 8/8/2019 PJS Outline

    33/46

    < set-property property ="driverClassName" value ="com.mysql.jdbc.Driver" />

    i) type optional DataSource class (default: javax.sql.DataSource) must meet java bean specii) className optional configuration object must extend org.apche.struts.config.DataSourceiii) key unique identifier required if more than one data-source used

    d) form-beans`

    < form-beans > < form-bean name ="registrationform" type ="ch12.RegistrationForm" />

    i) name unique identifier ii) type class name of the form class

    e) global-exceptions

    defines an ExceptionHandler to execute when an Action's execute method throws an Exception

    (1) subclass org.apache.struts.action.ExceptionHandler and override the execute method(2) Your execute method should process the Exception and return an ActionForward (3) Edit struts-config

    This configuration element says that com.yourcorp.ExceptionHandler.execute will be calleany IOException is thrown by an Action. The key is a key into your message resources profile that can be used to retrieve an error message.

    ii) You can override exception handlers by defining an exception inside an action

    f) global-forwards

  • 8/8/2019 PJS Outline

    34/46

    i) name: The logical name for this forward. Used in Actions execute method to forward to tappropriate resource.

    ii) path: The context relative path to the resource. Example: /index.jsp or /index.doiii) redirect: True or false. Should ActionServlet redirect to the resource instead of forwardfalse]

    g) action-mappings

    < forward name = "success" path ="/Welcome.jsp" /> < forward name = "failure" path ="/registration.jsp" />

    h) controller ( all attributes are optional and can be selectively changed)http://struts.apache.org/userGuide/configuration.html

    i) For each request made of the controller, the method process(HttpServletRequest,HttpServletResponse) will be called. This method determines which module should servicerequest and then invokes that module'sRequest Processors process method, passing the same request aresponse.

    public class GaiteRequestProcessor extends TilesRequestProcessor { protected boolean processPreprocess(HttpServletRequest request,HttpServletResponse response) { // If user is trying to access login page // then don't check

    String sServletPath = request.getServletPath(); if ( sServletPath.equals( "/Login.do" ) ||sServletPath.equals( "/locale.do" ) ) return true ;

    // Check if userName attribute is there is session.

    // If so, it means user has allready logged inUser user =

    (User)request.getSession().getAttribute(GaiteSystemConstants.USERKEY);if ( user != null ) return true ;

    else { try { // If no redirect user to login Page

    request.getRequestDispatcher( "/Login.do" ).forward(request,response);

    } catch (Exception ex){}

    }

    http://struts.apache.org/userGuide/configuration.htmlhttp://jdurrett.ba.ttu.edu/4383/Notes/RequestProcessor.javahttp://struts.apache.org/userGuide/configuration.htmlhttp://jdurrett.ba.ttu.edu/4383/Notes/RequestProcessor.java
  • 8/8/2019 PJS Outline

    35/46

    return false ;}

    }

    ii) bufferSize size (bytes) of the input buffer used for processing file uploads. [4096]iii) className - Classname of configuration bean. [org.apache.struts.config.ControllerConfig]iv) contentType - Default content type (and optional character encoding) to be set on eachresponse. May be overridden by the Action, JSP, or other resource to which the request is f

    [text/html]v) forwardPattern - Replacement pattern defining how the "path" attribute of a ele

    mapped to a context-relative URL when it starts with a slash (and when the contextRelativeis false). This value may consist of any combination of the following:

    * $M - Replaced by the module prefix of this module.* $P - Replaced by the "path" attribute of the selected element.* $$ - Causes a literal dollar sign to be rendered.* $x - (Where "x" is any character not defined above) Silently swallowed, reserved for fu

    If not specified, the default forwardPattern is consistent with the previous behavior of forward[$M$P]

    vi) inputForward - Set to true if you want the input attribute of elements to be theof a local or global ActionForward, instead of as a module-relative path to the resource to bthe input form. [false]

    vii) locale - Set to true if you want a Locale object stored in the user's session if not presenttrue]viii) processorClass - The fully qualified Java class name of the RequestProcessor subclass t

    used with this module. [org.apache.struts.chain.ComposableRequestProcessor ]ix) maxFileSize - The maximum size (bytes) of a file to be accepted as a file upload. Can b

    expressed as a number followed by a "K", "M", or "G", [250M]

    i) message-resourcesmultiple resource files can be used

    j) plugins

    k) Gotcha:i) Forward vs. redirect: if you set the redirect attribute to true in the forward

    youloose the request scope objects(you keep the session scope object of course)

  • 8/8/2019 PJS Outline

    36/46

    16) The HTML tag library http://struts.apache.org/struts-taglib/tlddoTag library documentation is IMHO lacking. So what you are going to get here is interesting exam

    a) The Problem: you need to create a combo box from database informationfor example a set of departments from a dept table as in the chapter 14 employees app

    b) The solution

    (1) Create java bean class with all the properties necessary for each of your optionsIn my example project(jrd) this is the MenuItem class

    public class MenuItem {

    private String prompt; private String value; private String link;

    Note : the link attribute is not used in the html:select tag but in the logic:iterate example late

    (2) Create a collection (a simple array is the easiest) of the beans from your databaseIn my example I simply fake it

    MenuItem[] menu = new MenuItem[3];menu[0] = new MenuItem("BA", "3", "http://www.ba.ttu.edu/");menu[1] = new MenuItem("Accounting", "4", "http://accounting.ba.ttu.edu/");menu[2] = new MenuItem("Finance", "5", "http://finance.ba.ttu.edu/");

    GOTCHA : If any item in your collection is null you will get server errors

    (3) Save the collection you created in some scope (in my example request)request.setAttribute("menu", menu);

    (4) Create your standard struts jsp form-bean action to allow input(5) On the input jsp add the html:select tag

    department :

    < html:cancel />

    (a) property is the property in your input form-bean(b) size is the number of selections to allow

    (6) Add the html:options tag as a sub-element in the select element(a) collection is the name of the bean that you saved in some scope(b) property is the value(c) labelProperty is the prompt for each option

    http://struts.apache.org/struts-taglib/tlddoc/http://opt/scribd/conversion/tmp/Examples/jrd.ziphttp://struts.apache.org/struts-taglib/tlddoc/http://opt/scribd/conversion/tmp/Examples/jrd.zip
  • 8/8/2019 PJS Outline

    37/46

    (d) scope is the memory space in which to look for the collection bean17)

  • 8/8/2019 PJS Outline

    38/46

    18) The Logic Tag Libraryhttp://struts.apache.org/userGuide/dev_logic.html

    a) The Problem: you need to create a set of links from database informationfor example the main menu in a webapp depends on the role of the person who logs in

    b) The solution

    (1) (4) Follow the same pattern as in the html tag example above

    (5) On the input jsp add the logic:iterate code

    >< br >

    .

    (a) id is the object name used in the loop for the collection(b) name is the collection name in some memory space(c) scope is where to look for the collection of beans

    .(6) Add the bean:write tags in the logic:iterate element

    (a) name is the object name from id in the logic:iterate element(b) property is the bean property to call with a getSomeProperty query(c) The rest is normal html

    (7)

    http://struts.apache.org/userGuide/dev_logic.htmlhttp://struts.apache.org/userGuide/dev_logic.html
  • 8/8/2019 PJS Outline

    39/46

    Addendum

    1. ModulesUsing modules allows developers to partition a single web application into functional areas. This allows inddevelopment without struts-config, form, and action coordination problems.

    (a) Steps in Using Modulesi.Create a struts-config file for each moduleii.Configure the web.xml deployment descriptor for each moduleiii.Configure links to access module specific jsps

    (b) struts configuration filesHaving seperate config files allows independent forwards, forms, actions, etcThe only difference with module config files is how the Tiles and Validator plugins are setup

    i.The typical naming convention for module config files isstruts-config-MODULE.xml where MODULE is the name of the specific module

    ii.However when using Tiles and/or Validator this option is more practical/WEB-INF/moduleA/struts-config.xml/WEB-INF/moduleB/struts-config.xml

    this struture allows seperate placement of the Tiles and Validator config files:And in Eclipse allows adding forms, etc through the outline (Linux)/WEB-INF/moduleA/tiles-defs.xml/WEB-INF/moduleA/validation.xml/WEB-INF/moduleB/tiles-defs.xml/WEB-INF/moduleB/validation.xml

    (c) Configure the web.xml file foeach module

    i.The typical, single module web.xml file the struts-config file is specified as:

    config /WEB-INF/struts-config.xml

    ii.When using modules each config parameter must be named to exactly identify the module. T param-name must be: config/moduleName where moduleName is the exact name you wantyour module in this webapplication. For instance, assume you have two modules named ch0ch10:

    config/ch08

  • 8/8/2019 PJS Outline

    40/46

    /WEB-INF/struts-config-ch08.xml config/ch10 /WEB-INF/struts-config-ch10.xml

    iii.The name given to the module in the web.xml param-name is called themodule-prefix and is very important. It is used by struts to distinguish and route requests to eamodule. The module-prefix becomes part of the URL that is always used to access module jactions, etc>

    All of a module's action paths are relative to the module. For instance, if we have a webapp s05_4383 a module namedch08 and an action who's path is /query the URL becomes:

    http://someserver:someport/s05_4383/ch08/query

    iv.When using modules the standard config file, ie the one in the WEB-INF directory without aname and specified in the web.xml file as simply config, is the default struts-config file and iwhen no module is listed in the URL. Thus files placed in the webapp root or in folders not nafter modules will be controlled through this default config file.

    (d) Configure links and actions toaccess module specific jsps and actions When using modules you cannot simply link to the relative directory (ch08/index.jsp)The problem is that the jsp URL will not go through the struts servlet and thus the relative moduconfiguration will not be loaded and any tag libraries or actions used will be loaded from the deconfig file.

    To correct this problem all requests for module changing jsps must be routed through the struts This is accomplished as follows:

    i.Add the SwitchAction mapping to each struts-config fileYou may use any action path you wish

    ii.When linking from a jsp to go to a sub-module index.jsp use:

    to go to the top level default module index.jsp use:

    iii.You may also use any modular jsp rather than the index pages

    (e) Using Eclipse 3.1.0 withMyEclipse 3.8.4

  • 8/8/2019 PJS Outline

    41/46

    i.Create a web project, add struts capabilities (PJS in this example)Be sure to backup the project (or deploy it) before continuing just in case :-)

    ii.

    Add a new module to the new project (ch11)You will get an web.xml file with the correct config param:

    config/ch11/WEB-INF/struts-config-ch11.xml

    if you wish to use Tiles or the Validator remember to change the structure per b.ii. Above.And a blank module config file

    iii.Open the new config fileiv.Create a new formRight click on the form-beans element in the outline and chose new FormYou may use the default package or a package name for the form class Note that the new module is chosen by defaultCreate the form as you have before do not add the module name to any of the paths

    You will end up with a typical form-bean entry and a new ActionForm classMake the appropriate changes to the class

    v.

    Create a new actionRight click on the action-mapping element in the outline and chose new ActionFill out the appropriate entries as always, Remember thatall paths are relative to the module .

    You should now have an Action class and an action entry in the module struts-config file. EdAction class as you wish to accomplish your action.

    vi.Create a new folder that has the same name as the module in the WebRoot folder

    vii.

    Create the necessary jsps in this new folder viii.

    If you wish a module index add the necessary global forward and actions

  • 8/8/2019 PJS Outline

    42/46

  • 8/8/2019 PJS Outline

    43/46

    2. MyEclipseIDE Database ExplorerMyEclipse Database Explorer

    Requirements:1. Java 2 SDK, Standard Edition 1.4 or later installed2. Eclipse 3.0.x SDK 3. MyEclipse 3.8.3 at least4. A database server that is supported bythe MyEclipse Database Explorer 5. The MyEclipse Database Explorer configured to browse a sample database

    (a) Database Explorer

    i.Install Driver: /Window/Preferences/MyEclipse/Database Explorer/Drivers

    A. Disable Row LimitB. Load all database meta data

    ii. New profile (the icon on the browser pane)

    A. Change the driver to the one you just editedB. Change the URL to 129.118.51.6:20/yourdb_dbC. I suggest prompt for password

    iii.Right click on the new connection and pick open

    iv.Be careful playing around, you can change both the data and the table definitions

    (b) ER diagramsCurrently limited to creating diagrams from current databases

    i.Open database connectionii.Right click on database and choose create ER diagram

    iii. Notes:

    A. You might have to edit the diagram colors in PreferencesB. MySQL (version 4.1.7) supports foreign keys only in InnoDB tablesC. InnoDB create sqlD. InnoDB insert sql

    iv.Interesting sql commands (some are dependent on MySQL version 4.1.7 or greater)

    A. show engines;B. show create table SomeTableName;C. show table status;D. describe SomeTableName;

    http://myeclipseide.com/enterpriseworkbench/help/index.jsphttp://jdurrett.ba.ttu.edu/4383/Examples/innodb_create_gaite_db.sqlhttp://jdurrett.ba.ttu.edu/4383/Examples/innodb_insert_gaite.sqlhttp://myeclipseide.com/enterpriseworkbench/help/index.jsphttp://jdurrett.ba.ttu.edu/4383/Examples/innodb_create_gaite_db.sqlhttp://jdurrett.ba.ttu.edu/4383/Examples/innodb_insert_gaite.sql
  • 8/8/2019 PJS Outline

    44/46

    E.show tables;

  • 8/8/2019 PJS Outline

    45/46

    3. User authentication(a)Authentication

    i.Option 1: include a user table in the db schema

    A. This option assumes that your db contains a table something like this: (email is the uscreate table RefUsers (

    password varchar(20) NOT NULL, nickname varchar(20) NOT NULL,email varchar(50) NOT NULL, scope varchar(15) NOT NULL, lastname

    varchar(30),firstname varchar(30), bselect boolean default 1, binsert boolean

    default 0,bupdate boolean default 0, bdelete boolean default 0,PRIMARY KEY (email) );

    B. With insert statement like:insert into RefUsers values ("bob", "DrBob", "[email protected]", "select", "Bob","Bob");insert into RefUsers values ("durrett", "DrJohn", "[email protected]", "admin","Durrett", "John");

    C. And validation queries like (u is userid and p is password) :select * from RefUsers where email=\"" + u + "\" and password=\"" + p + "\"

    D. The problem here is that if I give the ability to do a generic sql query on the db and thedoes: select * from RefUsers

    They are going to get

    Password nickname email scope lastname firstname

    Bob DrBob [email protected] select BobDurrett DrJohn [email protected] admin Durrett

    Probably not what you would want

    The solution is to use encryption

    E. Leave the create table syntax the same but change the insert statements to:insert into RefUsers values(AES_ENCRYPT('Tom','DrJohnisaGreatTeacher!'), "Just Tom", "[email protected]", "select", "Tom","Thompson");

    F. And valiation queries like:select * from RefUsers where email=useridvar" andAES_DECRYPT(password,\'DrJohnisaGreatTeacher!\')

    ="passvar;

    G. Then your query results above look like:Password nickname Email scope Lastname firstnameBob DrBob [email protected] select Bob BoT6Mak/ Just Tom [email protected] select Tom Th

    Much less informative. The problem is keeping track of the encryption key

    mailto:[email protected]:[email protected]:[email protected]:[email protected]
  • 8/8/2019 PJS Outline

    46/46