Download - 06 - MVC with Struts (Logon Example)db.ucsd.edu/static/cse135w10--archive/lectures/06 - MVC with Struts... · • Collections of custom JSP tags – Hide Java from JSPs – Java classes

Transcript
Page 1: 06 - MVC with Struts (Logon Example)db.ucsd.edu/static/cse135w10--archive/lectures/06 - MVC with Struts... · • Collections of custom JSP tags – Hide Java from JSPs – Java classes

1

CSE 135

MVC with Struts Logon Example

2

Example

•  The example implements a dummy logon functionality –  Do not consider this example to be the best way to

implement authorization and access control –  The example is used only to demonstrate the Struts

framework –  Appropriate authorization and access control will be

covered in a separate lecture shortly

Page 2: 06 - MVC with Struts (Logon Example)db.ucsd.edu/static/cse135w10--archive/lectures/06 - MVC with Struts... · • Collections of custom JSP tags – Hide Java from JSPs – Java classes

2

3

WorkFlow

welcome

!validate

Welcome.do

Logon.do LogonSubmit.dologonForm

Start

forward

Signout(hyperlink)

success

Welcome.jsp

Signin(hyperlink)

Logon.jspforward

success

Logoff.do

Submit(buBon)

4

SessionScope

user:logonForm

WorkFlow

UserDirectoryisValidPassword(Stringusername,Stringpassword)

get

setremove

welcome

!validate

Welcome.do

Logon.do LogonSubmit.dologonForm

Start

forward

Signout(hyperlink)

success

Welcome.jsp

Signin(hyperlink)

Logon.jspforward

success

Logoff.do

Submit(buBon)

Page 3: 06 - MVC with Struts (Logon Example)db.ucsd.edu/static/cse135w10--archive/lectures/06 - MVC with Struts... · • Collections of custom JSP tags – Hide Java from JSPs – Java classes

3

5

Welcome.do

6

Logon.do

Page 4: 06 - MVC with Struts (Logon Example)db.ucsd.edu/static/cse135w10--archive/lectures/06 - MVC with Struts... · • Collections of custom JSP tags – Hide Java from JSPs – Java classes

4

7

LogonSubmit.do (no password)

8

LogonSubmit.do (wrong pasword)

Page 5: 06 - MVC with Struts (Logon Example)db.ucsd.edu/static/cse135w10--archive/lectures/06 - MVC with Struts... · • Collections of custom JSP tags – Hide Java from JSPs – Java classes

5

9

LogonSubmit.do (success)

10

Logoff.do

Page 6: 06 - MVC with Struts (Logon Example)db.ucsd.edu/static/cse135w10--archive/lectures/06 - MVC with Struts... · • Collections of custom JSP tags – Hide Java from JSPs – Java classes

6

11

/index.jsp

<%@tagliburi="hBp://struts.apache.org/tags‐logic"

prefix="logic"%>

<logic:redirectforward="welcome"/>

<%‐‐

RedirectdefaultrequeststoWelcomeglobalAcRonForward.

‐‐%>

12

/pages/Welcome.jsp

<%@tagliburi="hBp://struts.apache.org/tags‐bean"prefix="bean"%>

<%@tagliburi="hBp://struts.apache.org/tags‐html"prefix="html"%>

<%@tagliburi="hBp://struts.apache.org/tags‐logic"prefix="logic"%><html:html>

<head>

<Rtle><bean:messagekey="app.Atle"/></Rtle>

<html:base/>

</head>

<body>

<logic:presentname="user">

<h3>Welcome<bean:writename="user"property="username"/>!</h3>

</logic:present>

Page 7: 06 - MVC with Struts (Logon Example)db.ucsd.edu/static/cse135w10--archive/lectures/06 - MVC with Struts... · • Collections of custom JSP tags – Hide Java from JSPs – Java classes

7

13

/pages/Welcome.jsp (cont’d)

...

<logic:notPresentscope="session"name="user">

<h3><bean:messagekey="welcome.heading"/></h3></logic:notPresent>

<html:errors/>

<ul>

<li><html:linkforward="logon">Signin</html:link></li>

<logic:presentname="user">

<li><html:linkforward="logoff">Signout</html:link></li>

</logic:present>

</ul>

</body>

</html:html>

14

Edge Labels In struts-config.xml

<!‐‐=========GlobalForwardDefiniRons

<global‐forwards>

<forward

name="logoff"path="/Logoff.do"/>

<forward

name="logon"

path="/Logon.do"/>

<forwardname="welcome"

path="/Welcome.do"/>

</global‐forwards>

Page 8: 06 - MVC with Struts (Logon Example)db.ucsd.edu/static/cse135w10--archive/lectures/06 - MVC with Struts... · • Collections of custom JSP tags – Hide Java from JSPs – Java classes

8

15

/pages/Logon.jsp

<body>

<html:errors/><h3><bean:messagekey=”logon.heading"/></h3>

<html:formacAon="/LogonSubmit"focus="username">

<tablewidth="100%">

<tr><thalign="right">Username:</th>

<td><html:textproperty="username"/></td></tr>

<tr><thalign="right">Password:</th>

<td><html:passwordproperty="password"/></td></tr>

<tr><tdalign="right"><html:submit/></td>

<td><html:reset/></td></tr>

</table>

</html:form>

</body>…

16

Associating the ActionForm Bean with the HTML Form

<acRon

path="/LogonSubmit”

type="app.LogonAcAon"

name="logonForm"scope="request"

validate="true"

input="/pages/Logon.jsp">

<forward

name="success"path="/pages/Welcome.jsp"/>

</acRon>

Page 9: 06 - MVC with Struts (Logon Example)db.ucsd.edu/static/cse135w10--archive/lectures/06 - MVC with Struts... · • Collections of custom JSP tags – Hide Java from JSPs – Java classes

9

17

Form Beans Also Provide Values

/pages/Logon.jsp …

<h3><bean:messagekey=”logon.heading"/></h3><html:formacAon="/LogonSubmit"focus="username">

<tablewidth="100%">

<tr><thalign="right">Username:</th>

<td><html:textproperty="username"/></td></tr>

<tr><thalign="right">Password:</th>

<td><html:passwordproperty="password"/></td></tr>

<tr><tdalign="right"><html:submit/></td>

<td><html:reset/></td></tr>

</table>

</html:form>

18

Typical Code Of A LogonForm Bean

publicfinalclassLogonFormextendsAcRonForm{

privateStringpassword=null;

privateStringusername=null;

publicStringgetPassword(){return(this.password);}

publicvoidsetPassword(Stringpassword){this.password=password;}

publicStringgetUsername(){return(this.username);}

publicvoidsetUsername(Stringusername){this.username=username;}

publicvoidreset(AcRonMappingmapping,HBpServletRequestrequest){

setPassword(null);

setUsername(null);

}

}

Page 10: 06 - MVC with Struts (Logon Example)db.ucsd.edu/static/cse135w10--archive/lectures/06 - MVC with Struts... · • Collections of custom JSP tags – Hide Java from JSPs – Java classes

10

19

The Art of Balancing How Many Actions & JSPs to Use

•  Consider the “logon” application •  We could have one JSP for each kind of login error •  However, we will see technologies that help

consolidate within a few JSPs –  Form validation features –  Logic tag library

•  Deciding the number of actions and JSPs is an art of design – not a science –  Examples, practice, then more practice…

20

Validation

publicAcRonErrorsvalidate(AcRonMappingmapping,

HBpServletRequestrequest){

AcRonErrorserrors=newAcRonErrors();

if((username==null)||(username.length()<1))

errors.add("username",newAcRonMessage("error.username.required"));

if((password==null)||(password.length()<1))errors.add("password",newAcRonMessage("error.password.required"));

returnerrors;

}

Page 11: 06 - MVC with Struts (Logon Example)db.ucsd.edu/static/cse135w10--archive/lectures/06 - MVC with Struts... · • Collections of custom JSP tags – Hide Java from JSPs – Java classes

11

21

Resource File & Internationalization

MessageResources.properties app.Rtle=StrutsLogonApplicaRon

welcome.heading=WelcomeUser!logon.heading=Signin,Please!

errors.header=<h3><fontcolor="red">ValidaRonError</font></h3>Youmust…

errors.prefix=<li>

errors.suffix=</li>

errors.footer=</ul><hr>error.username.required=Usernameisrequired

error.password.required=Passwordisrequired

error.logon.invalid=Usernameandpasswordprovidednotfoundinuser…

error.logon.connect=Couldnotconnecttouserdirectory.

22

Action Bean LogonAction.java

packageapp;

importjava.io.IOExcepRon;importjavax.servlet.ServletExcepRon;importjavax.servlet.hBp.HBpServletRequest;importjavax.servlet.hBp.HBpServletResponse;importjavax.servlet.hBp.HBpSession;importorg.apache.struts.acRon.AcRon;importorg.apache.struts.acRon.AcRonErrors;importorg.apache.struts.acRon.AcRonForm;importorg.apache.struts.acRon.AcRonForward;importorg.apache.struts.acRon.AcRonMapping;importorg.apache.struts.acRon.AcRonMessage;importorg.apache.struts.acRon.AcRonMessages;

publicfinalclassLogonAcRonextendsAcRon{…

Page 12: 06 - MVC with Struts (Logon Example)db.ucsd.edu/static/cse135w10--archive/lectures/06 - MVC with Struts... · • Collections of custom JSP tags – Hide Java from JSPs – Java classes

12

23

Action Bean LogonAction.java

/**

*ValidatecredenRalswithbusinessRer.*

*@paramusernameTheusernamecredenRal

*@parampasswordThepasswordcredenRal

*@returnstrueifcredenRalscanbevalidated

*@excepRonUserDirectoryExcepRonifcannotaccessdirectory

*/publicbooleanisUserLogon(Stringusername,Stringpassword)

throwsUserDirectoryExcepRon{

return(UserDirectory.getInstance().isValidPassword(username,password));//returntrue;

}…

24

Action Bean LogonAction.java

…publicAcRonForwardexecute(AcRonMappingmapping,AcRonFormform,

HBpServletRequestrequest,HBpServletResponseresponse)throwsExcepRon{//ObtainusernameandpasswordfromwebRerStringusername=((LogonForm)form).getUsername();Stringpassword=((LogonForm)form).getPassword();//ValidatecredenRalswithbusinessRerbooleanvalidated=false;try{ validated=isUserLogon(username,password);}catch(UserDirectoryExcepRonude){ //couldn'tconnecttouserdirectory AcRonErrorserrors=newAcRonErrors(); errors.add(…,newAcRonMessage("error.logon.connect")); saveErrors(request,errors); //returntoinputpage return(newAcRonForward(mapping.getInput()));}…

Page 13: 06 - MVC with Struts (Logon Example)db.ucsd.edu/static/cse135w10--archive/lectures/06 - MVC with Struts... · • Collections of custom JSP tags – Hide Java from JSPs – Java classes

13

25

Action Bean LogonAction.java

…if(!validated){ //credenRalsdon'tmatch AcRonErrorserrors=newAcRonErrors(); errors.add(…,newAcRonMessage("error.logon.invalid")); saveErrors(request,errors); //returntoinputpage return(newAcRonForward(mapping.getInput()));}//Saveourlogged‐inuserinthesession,//becauseweuseitagainlater.HBpSessionsession=request.getSession();session.setABribute(Constants.USER_KEY,form);

//Returnsuccessreturnmapping.findForward(Constants.SUCCESS);

}}//EndLogonAcRon

26

WorkFlow Variance

welcome

!validate

Welcome.do

Logon.do LogonSubmit.dologonForm

Start

forward

success

Welcome.jsp

Signin(hyperlink)

Logon.jspforward

success

Logoff.do

Submit(buBon)

Main.jsp

Signin(hyperlink)

Signout(hyperlink)

Page 14: 06 - MVC with Struts (Logon Example)db.ucsd.edu/static/cse135w10--archive/lectures/06 - MVC with Struts... · • Collections of custom JSP tags – Hide Java from JSPs – Java classes

14

27

WorkFlow Variance

•  The two variances share the same actions •  No modification in Actions source files •  Only need to change “view” (JSPs) and

“workflow” (struts-config.xml)

28

Tag Libraries

•  Collections of custom JSP tags –  Hide Java from JSPs –  Java classes in special format –  Methods invoked with XML tags –  Often looking like scripting languages

•  Load one of the many on the web, or build your own

–  Unlikely given the plenty of choices available

•  Struts Tag Libraries •  JSP Standard Tag Library (JSTL)

Page 15: 06 - MVC with Struts (Logon Example)db.ucsd.edu/static/cse135w10--archive/lectures/06 - MVC with Struts... · • Collections of custom JSP tags – Hide Java from JSPs – Java classes

15

29

Struts Tag Libraries

•  Four Struts Tag Libraries –  html Generate HTML dynamically –  bean Define beans, print bean properties, print

localized strings –  logic Manage conditionals, iterations, flow control –  nested

30

html Tag Library

•  Used to create input forms for your application •  A few other useful tags used in the creation and

rendering of HTML-based user interfaces –  html:form –  html:errors –  html:password –  html:submit –  html:text –  html:option

Page 16: 06 - MVC with Struts (Logon Example)db.ucsd.edu/static/cse135w10--archive/lectures/06 - MVC with Struts... · • Collections of custom JSP tags – Hide Java from JSPs – Java classes

16

31

html Tag Library: Example

<html:form action="/login" method="POST"> <h1>Login</h1> <html:errors/> <table> <tr> <td>User Name</td> <td><html:text property="userName"/></td></tr> <tr> <td>Password</td> <td><html:password property="password"/></td></tr> <tr> <td>&nbsp;</td> <td><html:submit value="Log in"/></td></tr> </table> </html:form>

32

bean Tag Library

•  Used for creating and accessing Java Beans and a few other general purpose uses

•  bean:define Define a scripting variable based on the value(s) of the specified bean property

•  bean:write Render the value of the specified bean property

•  bean:message Render an internationalized message string to the response

Page 17: 06 - MVC with Struts (Logon Example)db.ucsd.edu/static/cse135w10--archive/lectures/06 - MVC with Struts... · • Collections of custom JSP tags – Hide Java from JSPs – Java classes

17

33

bean Tag Library: Example

<html:html> <head> <title>Bean Define, Bean Write Tags</title> </head> <body> <bean:define id="message" type="java.lang.String" value="First message string"/> <p><b><bean:write name="message"/></b></p> </body> </html:html>

34

bean Tag Library: Another Example

<html:html> <head><title> <bean:message key="welcome.taglib.title"/> </title></head> <body> <h3><bean:message key="welcome.taglib.heading"/></h3> <p><bean:message key="welcome.taglib.message"/></p> </body> </html:html>

Message defined in: \WEB-INF\classes\MessageResources.properties

Page 18: 06 - MVC with Struts (Logon Example)db.ucsd.edu/static/cse135w10--archive/lectures/06 - MVC with Struts... · • Collections of custom JSP tags – Hide Java from JSPs – Java classes

18

35

logic Tag Library: Example

<logic:present name="itemsList”> Items available for the selected color <b><bean:write name="selectedColor"/></b>:<br/> <logic:iterate id="item" name="itemsList"> <b><bean:write name="item"/></b><br/> </logic:iterate> </logic:present> <logic:notPresent name="itemsList”> No Items available for selected color <bean:writename="selectedColor"/> </logic:notPresent>

36

JSTL

•  Core Lib (prefix c): scripting language •  Database Lib (sql): support for DB •  Functions Lib (fn): string manipulation etc. •  XML Lib (x): XML support •  Internationalization Lib (fmt): formatting

•  Installation: –  JSTL requires jstl.jar and standard.jar located in

apache-tomcat-6.0.20/webapps/examples/WEB-INF/lib/ –  Copy these two files into apache-tomcat-6.0.20/lib/

Page 19: 06 - MVC with Struts (Logon Example)db.ucsd.edu/static/cse135w10--archive/lectures/06 - MVC with Struts... · • Collections of custom JSP tags – Hide Java from JSPs – Java classes

19

37

JSTL Expressions

•  Many JSTL tags have attributes whose values are JSTL expressions –  Enclosed in ${...} –  <c:out value="${request.v}"/>

is shorthand for <% String attr=request.getParameter("v");%> ... <%= v %>

–  Declare on top of your JSP <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

38

Access to Bean Properties

•  Assume your JSP uses a bean named myBean that has property prop and corresponding getProp and setProp

<c:out value="${myBean.prop}"/> stands for <%= myBean.getProp() %>

Page 20: 06 - MVC with Struts (Logon Example)db.ucsd.edu/static/cse135w10--archive/lectures/06 - MVC with Struts... · • Collections of custom JSP tags – Hide Java from JSPs – Java classes

20

39

Scripting Language Features

•  Variable definition <c:set var="v" value="${...}" scope="session"/> <c:remove var="v"/>

•  Weak typing –  Strings to numbers –  Integers to reals –  and many more

40

Flow Control Tags

•  <c:if test="${booleanExpression}”> body of tag evaluated if boolean is true </c:if>

•  <c:choose> <c:when test="${booleanExpression}">...</c:when> <c:when test="${booleanExpression}">...</c:when> <c:otherwise>...</c:otherwise> </c:choose>

Page 21: 06 - MVC with Struts (Logon Example)db.ucsd.edu/static/cse135w10--archive/lectures/06 - MVC with Struts... · • Collections of custom JSP tags – Hide Java from JSPs – Java classes

21

41

Iteration

•  Iterate over start to end values, arrays, Collection, Iterator, Enumeration, Map, List, comma-separated string, etc.

•  <c:forEach var="i" begin="0" end="10" step="1"> loop body </c:forEach>

•  <c:forEach var="ck" items="${request.cookies}"> loop body </c:forEach>

Collection