Hello please help I have done a text to speech java application using free tts now I'm trying to do the same thing with struts 2. I created a button in my table the idea is that when I click the button I'll invoke a struts action called pronounce that extends the freetts class which will read my table's content but I have no idea how to do that this is my old free tts class
package com.hello;
import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;
public class myfreetts {
private String text; // string to speech
Voice voice;
public Prononcer(String text) {
this.text = text;
}
public void execute() {
System.setProperty("mbrola.base", "C:\\Users\\iup\\workspace\\newpro\\mbrola");
VoiceManager voiceManager = VoiceManager.getInstance();
voice = voiceManager.getVoice("mbrola_en1");
voice.allocate();
voice.speak(text);
}
public static void main(String[] args) {
String text = "FreeTTS was written by the Sun Microsystems Laboratories "
+ "Speech Team and is based on CMU's Flite engine.";
myfreetts freeTTS = new myfreetts(text);
freeTTS.execute();
}
}
and this is my jsp page
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>profile success</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#p").click(function(){
alert("Le bouton a été cliqué.");
});
});
</script>
</head>
<body background="images\25.jpg">
<div style="text-align: center"> <div style="color:WHITE"> <h1> Les informations de votre commande </h1></div></div>
<hr/>
<table border="2">
<tr>
<td><div style="color:cc9999"><h3>No_commande </h3> </div></td>
<td><div style="color:cc9999"><h3>Nom </h3> </div></td>
<td><div style="color:cc9999"><h3>Date </h3> </div></td>
<td><div style="color:cc9999"><h3>Etat </h3> </div></td>
<td><div style="color:cc9999"><h3>Tel </h3> </div></td>
<td><div style="color:cc9999"><h3>Prononcer </h3> </div></td>
<td><div style="color:cc9999"><h3>Test </h3> </div></td>
</tr>
<s:iterator value="list" id="message">
<tr>
<td><div style="color:WHITE"><h3> <s:property value="no_commande"/></h3> </div></td>
<td><div style="color:WHITE"><h3><s:property value="nom_client"/></h3> </div></td>
<td><div style="color:WHITE"><h3><s:property value="date"/></h3> </div></td>
<td><div style="color:WHITE"><h3><s:property value="etat"/></h3> </div></td>
<td><div style="color:WHITE"><h3><s:property value="tel"/></h3> </div></td>
<td><div style="color:WHITE"><h3><button id="p">Cliquez ici</button>
<td><div style="color:WHITE"><h3>test </h3> </div></td>
</h3> </div></td>
</tr>
</s:iterator>
</table>
</body>
</html>
ps:I'm still testing the button thats why I used alert
and 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>
<constant name="struts.devMode" value="false" />
<constant name="struts.enable.DynamicMethodInvocation" value="true"/>
<package name="default" namespace="/" extends="struts-default">
<action name="login">
<result >login.jsp</result>
</action>
<action name="loginprocess" class="com.hello.Login" method="execute">
<result name="success" >loginsucces.jsp</result>
<result name="error" >loginerror.jsp</result>
</action>
<action name="logout" class="com.hello.Login" method="logout">
<result name="success" >logoutsuccess.jsp</result>
</action>
<action name="profile" class="com.hello.Profile">
<result name="success" >profilesuccess.jsp</result>
<result name="error" >profileerror.jsp</result>
</action>
<action name="loginprocess" class="com.hello.Login" method="execute">
<result name="success" >loginsucces.jsp</result>
<result name="error" >loginerror.jsp</result>
</action>
<action name="viewrecords" class="com.hello.RetrieveRecords">
<result name="success">viewrecords.jsp</result>
</action>
<action name="prononce" class="com.hello.myfreetts">
<result>test.jsp</result>
</action>
</package>
</struts>
Please help I'm desperate.
Related
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:
I have a struts 2 application in which i want to use datatables to get results for a search and display them. the screen looks like below.
I want it to look like this finally and i want to use data tables to get the results from an ajax call.
I have an action class (Dashboard.java) with a method called viewSearchResult() as below.
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
import com.schenker.ocean.dao.SearchUpdateDAO;
import com.schenker.ocean.vo.Shipment;
public class Dashboard extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
//members
private String stt;
private String hawb;
private String chi;
private String invoice;
private String shipment;
private String Search;
private String tabIndex;
private String searchType;
private List<Shipment> aaData;
public String getTabIndex() {
return tabIndex;
}
public void setTabIndex(String tabIndex) {
this.tabIndex = tabIndex;
}
public String getSearch() {
return Search;
}
public void setSearch(String search) {
Search = search;
}
//getters and setters for members
public String getStt() {
return stt;
}
public void setStt(String stt) {
this.stt = stt;
}
public String getHawb() {
return hawb;
}
public void setHawb(String hawb) {
this.hawb = hawb;
}
public String getChi() {
return chi;
}
public void setChi(String chi) {
this.chi = chi;
}
public String getInvoice() {
return invoice;
}
public void setInvoice(String invoice) {
this.invoice = invoice;
}
public String getShipment() {
return shipment;
}
public void setShipment(String shipment) {
this.shipment = shipment;
}
//methods
public String getDashboard(){
return "success";
}
public String viewSearchResult(){
SearchUpdateDAO sudao= new SearchUpdateDAO();
aaData=sudao.getViewSearch(chi, stt, hawb, invoice, shipment, "");
return "success";
}
public String assignSearchResult(){
return "success";
}
public String shipDocsResult(){
return "success";
}
public String assignUpdateResult(){
return "success";
}
public String getSearchType() {
return searchType;
}
public void setSearchType(String searchType) {
this.searchType = searchType;
}
public List<Shipment> getAaData() {
return aaData;
}
public void setAaData(List<Shipment> aaData) {
this.aaData = aaData;
}
}
And my jsp page (which also has the search menu on the left hand side) is below.
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" HREF="css/styles.css">
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/smoothness/jquery-ui.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
<script type="text/javascript">
/* $(document).ready(function() { */
function postJSONData(){
var view = $('#view').val();
var assign = $('#assign').val();
var search=$('').val();
var stt=$('[name="stt"]').val();
var hawb=$('[name="hawb"]').val();
var chi=$('[name="chi"]').val();
var invoice=$('[name="invoice"]').val();
var shipment=$('[name="shipment"]').val();
$('#viewTable').dataTable( {
} );
};
/* }); */
</script>
<title></title>
<style type="text/css" media="screen">
body {
font-family: verdana, sans-serif;
font-size: 12px;
}
#header {
/* background: #ccc; */
padding: 0px;
}
#sidebar {
float: left;
width: 20%;
background: #C7C7C7;
}
#content {
margin-left: 22%;
}
#footer {
clear: right;
/* background: #eee; */
padding: 0px;
}
</style>
</head>
<body bgcolor="#ffffff" style="border: none; padding: 0px;">
<div id="header">
<table width="100%" height="20%">
<tr>
<td width="50%" height="1"
style="font-family: arial; font-size: 15px;" id="ezlogowrap" colspan="5"><img
src="images/ez-view-logo.png"></td>
<td width="50%" valign="top" style="padding-right: 15px;" colspan="5"><div
id="logowrap" align="right">
<img src="images/DbSchenkerLogo.gif" alt="DB Schenker logo">
</div></td>
</tr>
<!-- <tr><td colspan="10" height="25%"></td></tr> -->
<tr>
<td colspan="10"
style="background: #000066; width: 100%; height: 36px;"> </td>
</tr>
<tr><td colspan="10" height="25%"></td></tr>
</table>
</div>
<div id="sidebar">
<table width="20%" align="left">
<s:form name="searchForm" action="getDashboard" method="post">
<tr>
<th align="center" colspan="2">Search</th>
</tr>
<tr>
<td colspan="1"><s:textfield size="20" maxlength="20" name="stt" key="label.stt"></s:textfield> </td>
</tr>
<tr>
<td colspan="1"><s:textfield size="20" maxlength="20" name="hawb" key="label.hawb"></s:textfield> </td>
</tr>
<tr>
<td colspan="1"><s:textfield size="20" maxlength="20" name="chi" key="label.chi"></s:textfield> </td>
</tr>
<tr>
<td colspan="1"><s:textfield size="20" maxlength="20" name="invoice" key="label.invoice"></s:textfield> </td>
</tr>
<tr>
<td colspan="1"><s:textfield size="20" maxlength="20" name="shipment" key="label.shipment"></s:textfield> </td>
</tr>
<tr>
<td align="right" style="padding-top: 2px;" colspan="2"><s:submit key="label.search" onclick="postJSONData();" ></s:submit> </td>
</tr>
</s:form>
</table>
</div>
<div id="content">
<table align="left">
<tbody>
<tr>
<td colspan="8">
<div id="display jqueryDataTable">
<table id="viewTable">
<thead>
<tr>
<th>System</th>
<th>Doctype</th>
<th>STT</th>
<th>HAWB</th>
<th>CHI</th>
<th>Invoice</th>
<th>Shipment</th>
<th>Shipdate</th>
</tr>
</thead>
<tfoot>
<tr>
<th>System</th>
<th>Doctype</th>
<th>STT</th>
<th>HAWB</th>
<th>CHI</th>
<th>Invoice</th>
<th>Shipment</th>
<th>Shipdate</th>
</tr>
</tfoot>
</table>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div id="footer">
<table width="100%" height="20%">
<tr>
<td colspan="10"
style="background: #000066; width: 100%; height: 25px;"><div
align="center" class="style1"
style="font-size: 11px; color: #ffffff; font-family: Arial, Helvetica, sans-serif; padding-left: 5px;">DB
Schenker, Inc. © 2014</div></td>
</tr>
</table>
</div>
</body>
</html>
Below is the struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- <constant name="struts.enable.DynamicMethodInvocation" value="true" /> -->
<constant name="struts.devMode" value="true"/>
<constant name="struts.custom.i18n.resources" value="ApplicationResources"/>
<!-- <constant name="struts.enable.SlashesInActionNames" value="true" />
<constant name="struts.mapper.alwaysSelectFullNamespace" value="true" /> -->
<package name="logindefault" extends="struts-default,json-default">
<action name="login" method="execute" class="com.schenker.ocean.actions.LoginAction">
<result name="success">/searchpage.jsp</result>
<result name="input">/login.jsp</result>
<result name="fail">/login.jsp</result>
</action>
</package>
<package name="default" extends="logindefault" namespace="/">
<action name="login" method="execute" class="com.schenker.ocean.actions.LoginAction">
<result name="success">/searchpage.jsp</result>
<result name="input">/login.jsp</result>
<result name="fail">/login.jsp</result>
</action>
<action name="getDashboard" method="getDashboard" class="com.schenker.ocean.actions.Dashboard">
<result name="success">/searchpage.jsp</result>
<result name="input">/login.jsp</result>
<result name="fail">/login.jsp</result>
</action>
<action name="viewSearchResult" method="viewSearchResult" class="com.schenker.ocean.actions.Dashboard">
<result name="success">/searchpage.jsp</result>
<result name="input">/login.jsp</result>
<result name="fail">/login.jsp</result>
</action>
</package>
</struts>
My question is how can i get datatables to call viewSearchResult() and pass the parameters in the searchform? And how can i make sure the response is handled by datatables and not forwarded to another page by struts?
You can use struts-json plugin to get the response from action class in json format. Later to render use any one javascript approach (jQuery,jTable,dojo,etc.,)
To return as json object from a action class you have to set the return type as json in the struts action definition like below.
<action name="writeJSON" class="com.rajesh.json.ReadJSON" method="writeJSON">
<result type="json" />
To send and receive data to server and get response as json via ajax refer the below links.
Send json data to struts 2 action
Read json data from struts 2 action
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
from so many days i am trying to get this done,but m failing.
Have a look at my jsp once below:
Here i have one table and all each row i have refresh icon,i want to refresh individual row when clicked the icon.
onclick i am calling a function-> refreshRecord(value); value(parameter) is the fileid(unique)->i.e the first column of the table i am passing as a parameter to the function.
ajax is calling the checkStatusAndNumRecs aciton with the fileId,in action class i am calling my JPA method to get data from the database,its reading the row with that fileId what i have passed and putting it in JSONObject.
In jsp in ajax part its executing suuccess some time and error its executing most of the time,
when it is success,inside success part ,its failing to execute this line->var obj = jQuery.parseJSON(eval(data));
that means some times data is returning to ajax sometimes data is not coming back to ajax from action class.
THis is my jsp page:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>File Upload</title>
<script type="text/javascript" src="js/jquery-1.4.1.min.js"></script>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/style1.css" />
<link rel="stylesheet" type="text/css" href="css/button.css" />
<link href="css/common-style.css" rel="stylesheet" type="text/css" />
<style>
a{
color:white;
text-decoration:none;
}
</style>
<script type="text/javascript">
var id;
function refreshRecord(value)
{
id = value;
}
$(document).ready(function(){
$("#refresh").click(function(){
var fileId=id;
$.ajax({
type:"post",
url:"checkStatusAndNumRecs",
data:{fileId:fileId},
success:function(data)
{
alert(data);
var obj = jQuery.parseJSON(eval(data));->THis statement is not executing
aler("after JSON OBJECT"+obj.status);
$("#div1").html(obj.status);
$("#div2").html(obj.records);
},
error:function(data)
{
$("#div1").html("It was a failure !!!");
}
});
});
});
</script>
</head>
<body>
<%#include file="index1.html" %>
<div class="box2">
<div class="box3">
<s:property value="userId"/>
</div>
<center><h2>FILE STATUS</h2></center>
<center>
<form action="Upload" method="post" enctype="multipart/form-data">
<label for="myFile" class="text">Upload your file:</label>
<input type="hidden" name="upload" value="upload"/>
<input type="file" name="myFile" size="40" class="file"/>
<input type="submit" value="Upload" class="button"/>
<input type="submit" value="Refresh" class="button"/>
</form>
</center>
<center>
<s:if test="%{user.roles == 'admin'}">
<form action="manage" method="post" enctype="multipart/form-data">
<label for="myFile" class="text">Click to manage service providers:</label>
<input type="submit" value="Manage" class="button"/>
</form>
</s:if>
</center>
<center>
<table border="1" class="displaytab" id="rtable">
<s:if test="%{user.roles == 'admin'}">
<tr> <td colspan="10" style="background:#7395B8;color:white;font-size:18px;font-weight:bold;"><center>Admin</center></td></tr>
</s:if>
<tr>
<th>FileId</th><th>File Name</th><th>Upload Date</th><th>#Records</th><th>Status</th><th>Estimated Time</th><th>Processed Records</th><th>Generate Report</th><th></th><s:if test="%{user.roles == 'admin'}"><th>Controls</th></s:if>
</tr>
<s:iterator value="uploadList" var="m">
<tr>
<td><s:property value="%{#m.fileId}" /></td>
<td><s:property value="%{#m.fileName}" /></td>
<td><s:property value="%{#m.uploadDate}" /></td>
<td><div id="div2"><s:property value="%{#m.numRecords}" /></div></td>
<td><div id="div1"><s:property value="%{#m.status}" /></div></td>
<td>tbd</td>
<td><s:property value="%{#m.numRecords}" /></td>
<td><img src="images/generate.png" title="Generate Report"></td>
<td><img src="images/refresh.png" title="Refresh" id="refresh" onclick="refreshRecord(<s:property value="%{#m.fileId}" />);"></td>
<s:if test="%{user.roles == 'admin'}">
<td><img src="images/details.png">
<img src="images/plus.png" title="Add Instance">
<img src="images/minus.png" title="Remove Instance">
<img src="images/download.png" title="Download">
<img src="images/reconnect.png" title="Reconnect"></td>
</s:if>
</tr>
</s:iterator>
</table>
</center>
<br>
<br>
<br>
<br>
<center>
<s:if test="%{user.roles == 'admin'}">
<!-- <select name="user names">
<s:iterator value="userNamesList">
<option value="emailColumn" > <s:property/>
</option>
</s:iterator>
</select> -->
<table border="1" class="displaytab" id="usertab">
<s:if test="%{uploadListMap.size() != 0}">
<tr> <td colspan="10" style="background:#7395B8;color:white;font-size:18px;font-weight:bold;">User Job Details</center></td></tr>
<tr>
<th>FileId</th><th>File Name</th><th>Upload Date</th><th>#Records</th><th>Status</th><th>Estimated Time</th><th>Processed Records</th><th>Generate Report</th><th></th><s:if test="%{user.roles == 'admin'}"><th>Controls</th></s:if>
</tr>
<s:iterator value="%{uploadListMap}">
<tr> <td colspan="10" style="background:#7395B8;color:white;font-size:18px;font-weight:bold;"><center><s:property value="key"/></center></td>
<s:iterator value="value" var="u">
<tr>
<td><s:property value="%{#u.fileId}" /></td>
<td><s:property value="%{#u.fileName}" /></td>
<td><s:property value="%{#u.uploadDate}" /></td>
<td><s:property value="%{#u.numRecords}" /></td>
<td><s:property value="%{#u.status}" /></td>
<td>tbd</td>
<td><s:property value="%{#m.numRecords}" /></td>
<td><img src="images/generate.png" title="Generate Report"></td>
<td><img src="images/refresh.png" title="Refresh" id="refresh" onclick="refreshRecord(<s:property value="%{#u.fileId}" />);"></td>
<td><img src="images/details.png">
<img src="images/plus.png" title="Add Instance">
<img src="images/minus.png" title="Remove Instance">
<img src="images/download.png" title="Download">
<img src="images/reconnect.png" title="Reconnect"></td>
</tr>
</s:iterator>
</tr>
</s:iterator>
</s:if>
</table>
</s:if>
</center>
</div>
</body>
</html>
This is my action class:
p
ackage com.mxui;
import com.mxui.db.api.PersistenceService;
import com.mxui.db.service.*;
import org.json.simple.JSONObject;
import com.opensymphony.xwork2.ActionSupport;
public class checkStatusAndNumRecsAction extends ActionSupport
{
/**
*
*/
private String status;
public String getStatus()
{
return status;
}
public void setStatus(String status)
{
this.status = status;
}
private long numRecords;
public long getNumRecords()
{
return numRecords;
}
public void setNumRecords(long numRecords)
{
this.numRecords= numRecords;
}
private String fileId;
public String getFileId()
{
return fileId;
}
public void setFileId(String fileId)
{
this.fileId = fileId;
}
public String execute()
{
JSONObject obj = new JSONObject();
System.out.println("here inside action-------------");
PersistenceService svc = PersistenceServiceImpl.getInstance();
status = svc.getStatusByFileId(fileId);
System.out.println("status is "+status);
numRecords = svc.getNumRecordsByFileId(fileId);
System.out.println("num records are "+numRecords);
obj.put("status", status);
obj.put("records", numRecords);
System.out.print("json data is "+obj);
return "SUCCESS";
}
}
Please guide me in this ,i am struggling for this from so many days,and also i am new to ajax.
Thankyou in advance.
This is my struts.xml file:
<?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="false" />
<constant name="struts.multipart.maxSize" value="1000000" />
<result-type name="json" class="org.apache.struts2.json.JSONResult" default="false" />
<package name="struts" extends="struts-default">
<action name="RegisterationProcess" class="com.mxui.RegisterationFormAction">
<result name="SUCCESS">registerationform.jsp</result>
<result name="customerRegister">successregisteration.jsp</result>
</action>
<action name="CheckUserValidation" class="com.mxui.CheckUserAction">
<result name="SUCCESS">noofrows.jsp</result>
</action>
<action name="ProcessLogin" class="com.mxui.LoginAction">
<result name="LOGIN" >login.jsp</result>
<result name="REGISTER">registerationform.jsp</result>
<result name="ERROR" type="redirect">login.jsp</result>
<result name="FILEUPLOAD" type="redirect">Upload</result>
</action>
<action name="Upload" class="com.mxui.UploadFileAction">
<result name="SUCCESS">fileupload.jsp</result>
<result name="LOGINERROR" type="redirect">ProcessLogin</result>
<result name="PREVIEW" type="redirect">FilePreviewAction</result>
<result name="ERROR">error.jsp</result>
</action>
<action name="FilePreviewAction" class="com.mxui.FilePreviewAction">
<result name="SUCCESS">filepreview.jsp</result>
<result name="JOBCREATED" type="redirect">Upload</result>
<result name="ERROR" type="redirect">ProcessLogin</result>
</action>
<action name="ServiceProviderProcess" class="com.mxui.ServiceProviderAction">
<result name="SUCCESS">CreateProvider.jsp</result>
<result name="serviceprovider" type="redirect">Upload</result>
</action>
<action name="UpdateServiceProviderProcess" class="com.mxui.UpdateServiceProviderAction">
<result name="SUCCESS">updateserviceprovider.jsp</result>
<result name="updated" type="redirect">Upload</result>
</action>
<action name="manage" class="com.mxui.ManageServiceProviderAction">
<result name="SUCCESS">manageserviceprovider.jsp</result>
</action>
</package>
<package extends="struts-default,json-default" name="name" namespace="">
<interceptor name="json" class="org.apache.struts2.json.JSONInterceptor" />
<action name="checkStatusAndNumRecs" class="com.mxui.checkStatusAndNumRecsAction" method="execute">
<result type="json"></result>
</action>
</package>
</struts>
In JSP Page
$.ajax({
type: 'POST',
url: 'checkStatusAndNumRecs',
data:{fileId:fileId},
dataType: 'json',
async: false ,
contentType: 'application/json; charset=utf-8',
success: function(data){
alert(data);
var obj = jQuery.parseJSON(eval(data));->THis statement is not executing
alert("after JSON OBJECT"+obj.status);
$("#div1").html(obj.status);
$("#div2").html(obj.records);
},
error:function(data)
{
$("#div1").html("It was a failure !!!");
}
});
});
});
Struts.xml
Define a global result as
<result-type name="json" class="org.apache.struts2.json.JSONResult" default="false" />
For the action
<package extends="struts-default,json-default" name="name" namespace="">
<interceptor name="json" class="org.apache.struts2.json.JSONInterceptor" />
<action name="YouAction" class="YourActionClass" method="executeMethod">
<result type="json"></result>
</action>
</package>
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 .