I am trying to implement SimpleCaptcha
with Struts 2, so far the image is displaying. However, it is displaying at the top of the <s:form>
.
register.jsp:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<head>
...
<s:head />
</head>
<body>
<b>REGISTER</b>
<p>Please fill up the form below.</p>
<s:form action="register" method="post">
<s:textfield label="Enter username" key="userId" maxlength="25"
size="30" />
<s:textfield label="Enter email" key="userEmail1" type="email"
placeholder="[email protected]" size="30" />
<s:textfield label="Re-enter email" key="userEmail2" type="email"
placeholder="[email protected]" size="30" />
<s:password label="Enter password" key="userPassword1" size="30" />
<s:password label="Re-enter password" key="userPassword2"
size="30" />
<img src="<c:url value='simple-captcha.png' />" />
<br />
Cannot read? Refresh page for new CAPTCHA.
<s:textfield label="Enter CAPTCHA" key="captchaAnswer" size="30" />
<s:submit value="Register" />
</s:form>
</body>
How do I make the image appear above the Enter CAPTCHA
textfield as specified in the code?
The image should be generated by the
captcha
action. Then you provide the URL to this action in<img>
tag. To implement captcha in your project follow steps belowAdd the jar to your web project classpath:
simplecaptcha-1.2.1.jar
. Typically insideweb-inf/lib
folder.Add new action class
RegisterAction
Note: The following code is using convention plugin to map actions and for simplicity DMI is used to invoke some methods of the action class when form is submitted. To turn on DMI use a constant in
struts.xml
:RegisterAction.java
:RegisterAction.properties
contains the following value for the error key:RegisterAction.properties
:so we check either pass successfully or add to errors error regarding captcha.
register.jsp
Typically inweb-inf\content
register.jsp
:This will construct the Captcha and the text field to enter the value and Struts error message to show errors in
captchaResponse
field, plus the refresh icon.NOTE: a good trick we used here is the javascript
Math.random()
function, this way prevent certain browsers like Firefox to cache the URL and keep posting the same Captcha image, this enforce it to get the new value without doing any more effort.Here is how it will looks like:
For more details refer to the web site : SimpleCaptcha