Displaying SimpleCaptcha in Struts 2 Form - java

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="someone#domain.com" size="30" />
<s:textfield label="Re-enter email" key="userEmail2" type="email"
placeholder="someone#domain.com" 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 below
Add the jar to your web project classpath: simplecaptcha-1.2.1.jar.
Typically inside web-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:
<constant name="struts.enable.DynamicMethodInvocation" value="true"/>
RegisterAction.java:
public class RegisterAction extends ActionSupport {
private String userId;
private String userEmail1;
private String userEmail2;
private String userPassword1;
private String userPassword2;
private String captchaResponse;
private InputStream inputStream;
//getters and setters
public String create() {
//RegisterAction is the form bean of the current action and captchaResponse is the field of user input
String answer = (String) ActionContext.getContext().getSession().get("CorrectAnswer");
if (answer == null || getCaptchaResponse()==null || !answer.equals(getCaptchaResponse())){
addFieldError("captchaResponse", getText("error.captcha"));
}
return SUCCESS;
}
#Action(value = "captcha", results = {#Result(type="stream", params = {"contentType", "image/jpeg"})})
public String captcha() {
try {
Captcha captcha = new Captcha.Builder(200, 50).addText(new DefaultTextProducer()).gimp(new DropShadowGimpyRenderer()).build();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//write the image
CaptchaServletUtil.writeImage(outputStream, captcha.getImage());
//store the answer for this in session
ActionContext.getContext().getSession().put("CorrectAnswer", captcha.getAnswer());
//return image
inputStream = new ByteArrayInputStream(outputStream.toByteArray());
return SUCCESS;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
}
RegisterAction.properties contains the following value for the error key:
RegisterAction.properties:
error.captcha=Invalid value of shown text!
so we check either pass successfully or add to errors error regarding captcha.
Add register.jsp Typically in web-inf\content
register.jsp:
<!DOCTYPE html>
<%# taglib prefix="s" uri="/struts-tags"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta charset="UTF-8">
<title>Register</title>
</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="someone#domain.com" size="30" />
<s:textfield label="Re-enter email" key="userEmail2" type="email"
placeholder="someone#domain.com" size="30" />
<s:password label="Enter password" key="userPassword1" size="30" />
<s:password label="Re-enter password" key="userPassword2"
size="30" />
<tr><td>
<img id="captchaImg" src="<s:url action='captcha'/>" alt="Captcha Image" height="45">
<img src="<c:url value='/images/reload.jpg' />" alt="Reload" onclick="document.forms[0].captchaImg.src='<s:url action='captcha'/>'+'?id='+Math.random();" style="cursor:pointer"/>
<s:textfield label="Enter CAPTCHA" key="captchaResponse" size="30" requiredLabel="*"/>
<tr><td>
Cannot read? Refresh page for new CAPTCHA.
</td></tr>
<s:submit method="create" value="Register" />
</s:form>
</body>
</html>
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

This is just to show how I went about the solution. I was unaware you can put <tr><td> inside the <s:form>. Thanks to Roman C, I got the CAPTCHA image to display where I wanted it to.
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"
placeholder="someone" size="30" />
<s:textfield label="Enter email" key="userEmail1"
placeholder="someone#domain.com" size="30" />
<s:textfield label="Confirm email" key="userEmail2"
placeholder="someone#domain.com" size="30" />
<s:password label="Enter password" key="userPassword1" size="30" />
<s:password label="Confirm password" key="userPassword2"
size="30" />
<tr>
<td></td>
<td>
<img src="<c:url value='simple-captcha.png' />" />
<br />
Cannot read? Press F5 to refresh.
</td>
</tr>
<s:textfield label="Enter code" key="captchaAnswer" size="30" />
<s:submit value="Register" />
</s:form>
</body>
RegisterAction.java:
import nl.captcha.Captcha;
...
public class RegisterAction extends ActionSupport implements SessionAware, Message {
private static final long serialVersionUID = 1L;
private Map<String, Object> session;
private String userId;
private String userEmail1;
private String userEmail2;
private String userPassword1;
private String userPassword2;
private String captchaAnswer;
#Override
public String execute() throws Exception {
// business logic to insert user into database
return SUCCESS;
}
#Override
public void validate() {
Captcha captcha = (Captcha) session.get(Captcha.NAME);
if(!captcha.isCorrect(getCaptchaAnswer())) {
addFieldError("captchaAnswer", INCORRECT_CAPTCHA);
}
// other validations
}
#Override
public void setSession(Map<String, Object> session) {
this.session = session;
}
// getters and setters
}
struts.xml:
<struts>
<constant name="struts.devMode" value="true" />
<package name="default" extends="struts-default">
<action name="register" class="com.mypackage.action.RegisterAction">
<result name="success">/login.jsp</result>
<result name="input">/register.jsp</result>
</action>
<!-- other actions -->
</package>
</struts>
web.xml:
(The <init-param> is optional.)
<servlet>
<servlet-name>SimpleCaptcha</servlet-name>
<servlet-class>nl.captcha.servlet.SimpleCaptchaServlet</servlet-class>
<init-param>
<param-name>captcha-width</param-name>
<param-value>200</param-value>
</init-param>
<init-param>
<param-name>captcha-height</param-name>
<param-value>50</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>SimpleCaptcha</servlet-name>
<url-pattern>/simple-captcha.png</url-pattern>
</servlet-mapping>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
OUTPUT:

Related

Accessing JSP form data with in the Struts 2 Action class

I don't understand how to access form data within the JSP page inside my Action class
login.jsp:
<div class="well">
<form id="loginForm" method="POST" action="hr/login/" novalidate="novalidate">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon" id="UserEmail"><i class="fa fa-user" title="Enter Your username"></i></span>
<input type="text" class="form-control" id="username" name="username" value="" required title="Please enter you username" placeholder="Enter Username" />
</div>
<span class="help-block"></span>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon" id="UserPasswordMatch"><i class="fa fa-lock" title="Choose password"></i></span>
<input type="password" class="form-control" id="passwordmatch" name="passwordmatch" value="" required title="Enter your password" placeholder="Enter Password" />
</div>
</div>
<button type="submit" class="btn btn-success btn-block">Login</button>
</form>
</div>
BookingAction.java:
public class BookingAction {
private String name;
HotelReservationServceImpl service = new HotelReservationServceImpl();
public String execute() throws Exception {
return "success";
}
public String loginExecute()
{
return "success";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I also have a User class with private attributes which include username and password with getters and setters.
service.java:
public class HotelReservationServceImpl implements IHotelReservationService {
HotelReservationDAOImpl dbcon = new HotelReservationDAOImpl();
#Override
public int login(String username, String passwrd) {
if(username.isEmpty() || passwrd.isEmpty())
{
System.out.print(" Enter username and password ");
}
else
{
int i = dbcon.login(username, passwrd);
}
//dbcon.dbConnector();
return 0;
}
}
struts.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="helloworld" extends="struts-default">
<action name="hello"
class="com.reservation.action.BookingAction"
method="execute">
<result name="success">/HelloWorld.jsp</result>
</action>
<action name="login"
class="com.reservation.action.BookingAction"
method="loginExecute">
<result name="success">/HelloWorld.jsp</result>
</action>
</package>
</struts>
Use Struts tags to bind the form to the action and input fields to action properties.
<%# taglib prefix="s" uri="/struts-tags" %>
<s:form id="loginForm" method="POST" action="login" novalidate="novalidate">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon" id="UserEmail"><i class="fa fa-user" title="Enter Your username"></i></span>
<s:textfield cssClass="form-control" id="username" name="user.username" value="" required title="Please enter you username" placeholder="Enter Username" />
</div>
<span class="help-block"></span>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon" id="UserPasswordMatch"><i class="fa fa-lock" title="Choose password"></i></span>
<s:password cssClass="form-control" id="passwordmatch" name="user.password" value="" required title="Enter your password" placeholder="Enter Password" />
</div>
</div>
<button type="submit" class="btn btn-success btn-block">Login</button>
</s:form>
To bind the form you should set the action name to the form tag. To bind input fields you should set property names to the struts input tags.
The properties are in the User bean that you should aggregate to the action class.
private User user;
public User getUser() { return user; }
public void setUser(User user) { this.user = user; }
If you don't want to generate extra HTML to the page use
<constant name="struts.ui.theme" value="simple"/>

How to display a dijit.Dialog as a popup up

I am trying to display a dijit.Dialog as a popup window. This is a new feature addition to an existing project and as I have never woked wth Dojo;s before I am struggling a bit.
I have created the pop up window but it keeps displaying as a seperate page than a popup, what am I doing wrong? Please help!
THe page where the button to show the popup
<input class="style_off pink_button ft_white" onclick='submitOnclick()' id="show_popup" type="submit" name="showPopup" value="Generate PopUp"/>
<span id="validationPopUp" style="display:none;"><c:out value=""/></span>
The script page:
function submitOnclick() {
dojo.xhrPost({
url: "${get_valpopup_url}",
form: dojo.byId("searchResults"),
load: function(data){
//Destroy widget to avoid reallocating it during parse.
if(valDialog) {
valDialog.destroy();
}
dojo.place(data, "validationPopUp", "only");
dojo.parser.parse("validationPopUp");
valDialog = dijit.byId('inputPopUpId');
valDialog.show();
},
error: function(e) {
console.log("Ajax call failed", e);
}
});
return false;
}
the pop up window
<?xml version="1.0" encoding="UTF-8"?>
<div id="inputPopUpId" dojotype="dijit.Dialog" title="${popup_title}"
height="500px;" xmlns:f="http://www.twister.total.com/taglib"
xmlns:fn="http://java.sun.com/jsp/jstl/functions"
xmlns:fmt="http://java.sun.com/jsp/jstl/fmt"
xmlns:tiles="http://tiles.apache.org/tags-tiles"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:util="urn:jsptagdir:/WEB-INF/tags/util"
xmlns:form="http://www.springframework.org/tags/form"
xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:s="http://www.twister.total.com/taglib/sessionAttr"
xmlns:spring="http://www.springframework.org/tags" version="2.0">
<jsp:directive.page contentType="text/html;charset=UTF-8" />
<jsp:output omit-xml-declaration="yes" />
<spring:message code="random_extract_popup_title" var="popup_title" htmlEscape="false" />
<p>
<spring:message code="random_extract_popup_message" />
</p>
<form:form method="post" modelAttribute="inputPopup" action="reports" enctype="application/x-www-form-urlencoded">
<s:insertSessionConversationId attributeName="searchResults"/>
<s:insertSessionConversationId attributeName="searchDto"/>
<div>
<label for="noOfRecords">
<spring:message code="random_extract_popup_form_label" />
</label>
<input id="noOfRecords" type='text' name='noOfRecords' style="width:150px" />
<spring:message code="random_extract_popup_form_message" var="name_msg" htmlEscape="false" />
<script type="text/javascript">
<c:set var="sec_name_msg">
<spring:escapeBody javaScriptEscape="true">${name_msg}</spring:escapeBody>
</c:set>
Spring.addDecoration(new Spring.ElementDecoration({elementId : "noOfRecords", widgetType : "dijit.form.NumberTextBox", widgetAttrs : {promptMessage: "${sec_name_msg}", required : true, constraints: {pattern: "0, ####"}}}));
</script>
</div>
<br />
<br />
<div class="submit">
<spring:message code="button_extract_random_report" var="extract_random_report" htmlEscape="false" />
<script type="text/javascript">Spring.addDecoration(new Spring.ValidateAllDecoration({elementId:'extract_random_report', event:'onclick'}));</script>
<input class="startLoading style_off pink_button ft_white" id="extract_random_report" type="submit" name="extractrandom" value="${fn:escapeXml(extract_random_report)}"/>
</div>
</form:form>
</div>
The views.xml
<definition extends="empty" name="a/s/validationPopUpId">
<put-attribute name="body" value="validation-dialog.jspx"/>
</definition>
The code in the controller
#RequestMapping(value = "sox/search/reports", params="showPopup", method = RequestMethod.POST)
public String generatePopup(#ModelAttribute(TwisterConstants.SEARCH_RESULTS) AuditSoxListResultsDto searchResults, #ModelAttribute(TwisterConstants.SEARCH_DTO) AuditSoxSearchRequest searchDto,
Model uiModel, Locale selectedLocale, HttpServletRequest request, HttpServletResponse response){
uiModel.addAttribute(TwisterConstants.SEARCH_RESULTS, TwisterConstants.SEARCH_DTO);
addDateTimeFormatPatterns(uiModel,"S-");
return "a/s/validationPopUpId";
}

Can't set up a proper ajax call using struts2 and ajax

I've been trying to get this code to work. THe basic idea is I want to create an ajax request when the textbox whose id is "user" to go back to the server (apache) via an ajax call.
The error I get is a 404 when doing a http://localhost:8080/CheckUserAvailabilityAction.do?username=ds request.
This is my code.
Struts2 class CheckUserAvailabilityAction.java:
public class CheckUserAvailabilityAction extends ActionSupport implements
ServletRequestAware {
//struts action
public String execute() {
String output = "success";
/*
SOME CODE
*/
return output;
}
}
Here's my jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<%# taglib uri="http://jakarta.apache.org/struts/tags-bean"
prefix="bean"%>
<%# taglib uri="http://jakarta.apache.org/struts/tags-html"
prefix="html"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="js/scripts.js" type="text/javascript"></script>
<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
<script>
var url = "HelloWorld.jsp";
function makeRequest(url) {
if (window.XMLHttpRequest) {
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { }
}
}
if (!httpRequest) {
return false;
}
httpRequest.onreadystatechange = alertContents();
httpRequest.open('GET', url);
httpRequest.send();
//Redirecting to the HelloUser.jsp
window.location.replace(url);
}
function alertContents() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
$(function(){
$("#username").blur("/CheckUserAvailability");
});
function checkUserAvailability(){
var name = $("#username").val();
$.get(
"/CheckUserAvailabilityAction.do",
{ 'username': name },
function () {
var response = $(data).find("response").text();
$("#response").hide();
$("#response").empty();
$("#response").append(response);
$("#response").show("slow");
}
);
}
</script>
<link rel="stylesheet" type="text/css" href="css/styles.css">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>New user - Registration form</title>
</head>
<body id="bodyStyling">
<%
if ("noSexSelected".equalsIgnoreCase(request
.getParameter("register"))) {
%>
<div id="registrationFailure">
<h4>Please select a Sex</h4>
</div>
<%
}
%>
<form name="myForm" action="checkUserNameAvailability" method="post">
<!-- onsubmit="return validateForm(this);" -->
<table>
<tr>
<td><h2 id="IntroductionReg">New User Registration</h2></td>
</tr>
<tr>
<td class="myTableDataStyling">Name:</td>
<td><input name="username" id="username" type="text"
onblur="checkUserAvailability()" /></td>
<td><label id="usrLabel"></label></td>
</tr>
<tr>
<td class="myTableDataStyling">Password:</td>
<td><input name="password" type="password" onclick= /></td>
</tr>
<tr>
<td class="myTableDataStyling">Confirm password:</td>
<td><input name="passwordConfirmation" type="password"
onclick="this.value''" /></td>
</tr>
<tr>
<td class="myTableDataStyling">Age:</td>
<td><input name="age" onclick="this.value=''" /></td>
</tr>
<tr>
<td class="myTableDataStyling">Sex:</td>
<td><select name="sex">
<option value="">- Select -</option>
<option value="M">M</option>
<option value="F">F</option>
</select>
</tr>
<tr>
<td class="myTableDataStyling">Address:</td>
<td><input name="address" onclick="this.value=''" /></td>
</tr>
<tr>
<td class="myTableDataStyling">E-mail:</td>
<td><input name="email" onclick="this.value=''" /></td>
</tr>
<tr>
</tr>
</table>
<input type="submit" value="Register user" />
</form>
<div id="outputDiv"></div>
<div id="response"></div>
</body>
</html>
This is my struts.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- Here, I declare the actions for the com.tcs.controller package classes -->
<package name="damo" extends="struts-default">
<action name="process" class="com.tcs.controller.User">
<result name="success">/process.jsp</result>
</action>
<action name="login" class="com.tcs.action.LoginAction">
<result name="success">HelloUser.jsp</result>
<result name="error">Login.jsp</result>
</action>
<action name="register" class="com.tcs.action.RegisterUserAction">
<result name="success">process.jsp</result>
<result name="error">process.jsp</result>
</action>
<action name="checkUserNameAvailability" class="com.tcs.action.CheckUserAvailabilityAction">
<result name="success" type='redirect'>register.action</result>
<result name="error">process.jsp</result>
</action>
</package>
</struts>
I'm struggling to get my checkUserAvailability function to make a valid request, I'm lost since I have minimal knowledge of struts.
Help is greatly appreciated
Thanks.
Please refer the below url for exact solution.
Send json data to struts 2 ajax
Dynamic Drop Down List
I think you're missing your project name from the url. Could you test
http://localhost:8080/[yourProjectName]/CheckUserAvailabilityAction.do?username=ds
so that if your project in your workspace is called foo you'd call url
http://localhost:8080/foo/CheckUserAvailabilityAction.do?username=ds

Struts 2 file upload : File object being null

I am trying to use Struts 2 file upload but it seems to me that its not working. Below is my code.
UploadAction.java:
public class UploadAction extends ActionSupport{
private File file;
private String orgFileName;
private String orgContentType;
public void setUpload(File file){
this.file=file;
}
public void setUploadContentType(String contentType){
this.orgContentType=contentType;
}
public void setUploadFileName(String fileName){
this.orgFileName=fileName;
}
#Override
public String execute(){
if(file==null)
{
System.out.println("No file....");
}
System.out.println(orgContentType);
System.out.println(orgFileName);
return SUCCESS;
}
}
struts.xml:
<constant name="struts.multipart.maxSize" value="20971520" />
<constant name="struts2.multipart.saveDir" value="C:/users/sabertooth/desktop/upload" />
<include file="example.xml"/>
<!-- Configuration for the default package. -->
<package name="default" extends="struts-default">
<action name="upload" class="UploadAction">
<result name="success">/example/HelloWorld.jsp</result>
</action>
</package>
I am also trying to set struts2.multipart.saveDir property as you can see above but when I read the server logs I see this line
unable to find `struts.multipart.saveDir` defaulting to `javax.servlet.dir`
Also the file object is null as no file... gets printed out on console.
I can't figure out what is wrong here.
EDIT:
fileupload.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>upload file below</h1>
<s:form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="uploadfile" />
<input type="submit" id="submit" />
</s:form>
</body>
</html>
Apart from changing the saveDir (really not necessary, and dangerous), your are not following the conventions in the Action class: the name of an private variable must match the names of its Getters and Setters; and finally, in page you are mismatching the name by pointing to the private variable, not the setter. Change it to:
public class UploadAction extends ActionSupport{
private File upload;
private String uploadFileName;
private String uploadContentType;
public void setUpload(File upload){
this.upload=upload;
}
public void setUploadContentType(String uploadContentType){
this.uploadContentType=uploadContentType;
}
public void setUploadFileName(String uploadFileName){
this.uploadFileName=uploadFileName;
}
#Override
public String execute(){
if(upload==null)
{
System.out.println("No file....");
}
System.out.println(uploadContentType);
System.out.println(uploadFileName);
return SUCCESS;
}
}
JSP
<s:form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="upload" id="uploadfile" />
<input type="submit" id="submit" />
</s:form>
Change this
<input type="file" name="file" id="uploadfile" />
to
<input type="file" name="upload" id="uploadfile" />
Your setter in your action class is setUpload so it is looking for a request parameter called upload, not file. For the sake of convention you should also change
private File file;
public void setUpload(File file){
this.file=file;
}
to
private File upload;
public void setUpload(File file){
this.upload=file;
}

Ajax with struts

I have a problem using ajax with struts
I want to load dependent dropdown list using ajax. I am using struts2.
Below is the code for the jsp.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Enter Product</title>
<script type="text/javascript">
var request;
function findindex1()
{
var temp=document.getElementById("country").value;
if(window.ActiveXObject){ request = new ActiveXObject("Microsoft.XMLHTTP"); }
else if(window.XMLHttpRequest){ request = new XMLHttpRequest(); } request.onreadystatechange = showResult;
request.open("POST",'temp.action?index='+temp,true);
request.send(null);
}
function showResult(){
if(request.readyState == 4){
alert(request.responseText+"1");
document.getElementById("text").innerHTML=request.responseText; //Just to test
var val=<%=request.getParameter("index") %> -
/* document.getElementById("city").flush(); */
}
alert(request.responseText+"1");
}
function change(){
var temp=document.getElementById("country").value;
location.href='loadProduct.action';
}
</script>
</head>
<body onload="fill()">
<s:form method="post" action="product.action" name="product" theme="simple">
<table id="table">
<tr><td>Country</td><td><s:select id="country" name="country.countryId" list="countryList" listKey="countryId"
listValue="name" onchange="findindex1()" ></s:select></td></tr>
<tr>
<td>City</td>
<td><s:select id="city" name="city.id" list="cities" listKey="id"
listValue="name" headerKey="city.id" ></s:select></td>
</tr>
<tr>
<td>Product Desc</td>
<td><s:textfield name="product.description"></s:textfield></td>
</tr>
<tr>
<td>Product Name</td>
<td><s:textfield name="product.name"></s:textfield></td>
</tr>
<tr>
<td><s:submit id="search" name="submit" value="Search"></s:submit></td>
<td><s:submit name="submit" value="Create"></s:submit>
</td>
</tr>
<tr>
<td></td>
<td><s:label id="text" name="text">Text to change</s:label>
</td>
</tr>
</table>
</s:form>
</body>
</html>
I have checked the code and it sets the value of the List cities in the action class on changing the value of the country dropdown in the jsp. But i am unable to reflect the changes in the jsp .
The action class function is :
public String temp()
{
String[] id=(String[])getParameters().get("index");
index=Integer.parseInt(id[0]);
cities=(ArrayList<City>)productCreateService.selectCities(Integer.parseInt(id[0]));
for(Iterator<Country> i=countryList.iterator();i.hasNext();)
{
Country c = i.next();
if(c.getCountryId()==Integer.parseInt(id[0]))
{
Country c1= countryList.get(0);
country=c;
break;
}
}
String out="";
for(Iterator<City> i=cities.iterator();i.hasNext();)
{
}
inputStream = new StringBufferInputStream("Hello World! This is a text string response from a Struts 2 Action.");
return SUCCESS;
}
All the varibles have getter setters . I know the code is messed up . Initially i testes it for cities tag. When that didnt work i tried testing on a simple tag (here id="text") . But even that didnt work .
The model, Services and DAO(though not here) are all correct.
The struts.xml file is as follows .
<!-- Some or all of these can be flipped to true for debugging -->
<constant name="struts.i18n.reload" value="true" />
<constant name="struts.devMode" value="true" />
<constant name="struts.configuration.xml.reload" value="false" />
<constant name="struts.custom.i18n.resources" value="global" />
<constant name="struts.action.extension" value="action" />
<constant name="struts.serve.static" value="true" />
<constant name="struts.serve.static.browserCache" value="false" />
<constant name="actionPackages" value="com.oxxo.pilot.web.action" />
<package name="default" extends="struts-default" namespace = "/">
<global-results>
<result name="custom_error">/jsp/exception.jsp</result>
<result name="input">/jsp/fail.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping exception="java.lang.Exception"
result="custom_error" />
<action name="temp" class="ProductAction" method="temp">
<result type="stream">
<param name="contentType">text/html</param>
<param name="inputName">inputStream</param>
</result>
</action>
</package>
Could somebody please tell me what am i doing wrong. If you need any part of the code please let me know . Thanks .

Categories