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

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

Related

Drop down list is not getting displayed with spring mvc and jsp

I have an application where in a JSP page i am displaying a drop down list but i am getting an exception in my code.
public class ExpenseCreationBean {
private String color;
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
Controller Class:-
#RequestMapping(value = "/addDetails", method = RequestMethod.GET)
public String getExpenseEntryPage(Model model) {
ExpenseCreationBean expenseCreationBean = new ExpenseCreationBean();
model.addAttribute("expenseCreationBean", expenseCreationBean);
List<String> coloursList = new ArrayList<String>();
coloursList.add("red");
coloursList.add("green");
coloursList.add("yellow");
coloursList.add("pink");
coloursList.add("blue");
model.addAttribute("colours", coloursList);
System.out.println("I was here!!");
return "addDetails";
}
addDetails.jsp Page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<html>
<head>
<title>Add Details</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function() {
$("#datepicker").datepicker({
showOn : "button",
buttonImage : "images/calendar.png",
buttonImageOnly : true,
buttonText : "Select date"
});
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<h1>Expense Entry Details</h1>
<form:form method="post" action="savedata" modelAttribute="expenseCreationBean">
<table border="6px" cellspacing="10px" cellpadding="10px">
<tr>
<td>Date Of Purchase: <input type="text" id="datepicker"
name="date_of_purchase"></td>
<td>Item Name:<input type="text" name="description"></td>
<td>Please select:</td>
<td><form:select path="color">
<form:option value="" label="...." />
<form:options items="${colours}" />
</form:select>
</td>
<td>Paid By: <select name="paid_by"></td>
<td>Amount Paid:<input type="text" name="total_price"
id="total_price"></td>
<td>Quantity:<input type="text" name="quantity_purchased"></td>
<td>Unit:<input type="text" name="unit"></td>
</tr>
<tr>
<tr>
<tr>
<tr>
<td>Exclude:</td>
<td><input TYPE="checkbox" name="exclude">
</tr>
<tr>
<td>Comments:<textarea rows="3" cols="25" name="comments"></textarea>
</td>
</tr>
<tr>
            
<td><input type="submit" value="Save" align="middle"></td>
</table>
</form:form>
</body>
</html>
I am getting the below exception :-
javax.servlet.jsp.JspException: Type [java.lang.String] is not valid for option items
org.springframework.web.servlet.tags.form.OptionWriter.writeOptions(OptionWriter.java:143)
org.springframework.web.servlet.tags.form.OptionsTag.writeTagContent(OptionsTag.java:157)
org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:84)
It is just a Spring MVC Web application where i am trying to display the drow down list pre-populated with the colors data.
Any help is highly appreciated.
I added the below line on teh top of addDetails.jsp file and it worked:-
Try to add into Map, instead of ArrayList.
Map<String,String> coloursList = new HashMap<String,String>();
coloursList.put("R","red");
coloursList.put("R","green");
coloursList.put("Y","yellow");
coloursList.put("P","pink");

how to get search results and render them using datatables in a struts 2 application

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

Refreshing (updating) individual rows of a table with the data returned by the action class using ajax call

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>

Open a text file with jsp button click and java

am asking this question after some research. Am trying to open a text file located in my local maching with java and jsp. ie when I click a button in jsp it should open the text file for me. Could some one please help me on this.
Hi, Here is my code:
import java.awt.Desktop;
import java.io.File;
public class Start extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
try {
if ((new File("C:\\Debug\\log20.txt")).exists()) {
Process p = Runtime
.getRuntime()
.exec("C:\\Debug\\log20.txt");
p.waitFor();
} else {
System.out.println("File is not exists");
}
System.out.println("Done");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Web.xml:
<servlet>
<servlet-name>LogFile</servlet-name>
<servlet-class>com.abc.def.LogFile</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogFile</servlet-name>
<url-pattern>/logfile</url-pattern>
</servlet-mapping>
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">
<% String status=""; %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>EMC eLicensing</title>
<link rel="stylesheet" type="text/css" href="css/css_ngoe/headerDefault.css" />
<link rel="stylesheet" type="text/css" href="css/css_ngoe/bodyTemplate.css" />
<link rel="stylesheet" type="text/css" href="css/css_ngoe/footer.css" />
<link rel="stylesheet" type="text/css" href="css/css_ngoe/helperClasses.css" />
<link rel="stylesheet" type="text/css" href="css/css_ngoe/railPanel.css" />
<link rel="stylesheet" type="text/css" href="css/css_ngoe/buttons.css" />
</head>
<body>
<!-- Header Start -->
<div class="parentheader">
<div id="header">
<h1>
E
</h1>
<div id="header-text-position">
<div id="header-text"></div>
<br />
</div>
</div>
</div>
<!-- Header End -->
<br>
<br>
<table width=100% cellpadding=0 cellspacing=0 border=0>
<tr>
<td> </td>
<!-- START CONTENT -->
<td>
<P>
lmgrd options
<BR>
<BR>
<FORM action="start" METHOD="GET">
<table
cellspacing="5" cellpadding="1" border="0">
<tr>
<td>Start/Stop/Reread</td>
<td><input type=submit name=txtSubmit1 id=txtSubmit value="Start" /></td>
</tr>
</table>
</FORM>
<FORM action="stop" METHOD="GET">
<table
cellspacing="5" cellpadding="1" border="0">
<tr>
<td>Start/Stop/Reread</td>
<td><input type=submit name=txtSubmit2 id=txtSubmit value="Stop" /></td>
</tr>
</table>
</FORM>
<FORM action="logfile" METHOD="GET">
<table
cellspacing="5" cellpadding="1" border="0">
<tr>
<td>LOGFILE</td>
<td><input type=submit name=txtSubmit3 id=txtSubmit value=LOG /></td>
</tr>
</table>
</FORM>
<form action="start" method="GET"
enctype="multipart/form-data">
<input type="file" name="file"
value=text />
<input type="submit" />
</form>
<form action="status" method=GET>
<BR>
<BR>
<input type=submit name=Submit id=txtSubmit
value=Status>
</form>
<BR>
status: <%=status %>
<p>
<p>
<p>
</td>
</tr>
</table>
</body>
</html>
You Could you try it like this if you want to browse the file in an external program
Process p = Runtime.getRuntime().exec("C:\\Path\\to\\notepad.exe C:\\Debug\\log20.txt");
And if you want to browse the file in web page you could try the following:
PrintWriter out = res.getWriter();
File file = new File("C:\\Debug\\log20.txt");
if (file.exists()) {
BufferedReader input = new BufferedReader(new FileReader(file));
String line = "";
while ((line = input.readLine()) != null) {
out.println(line);
}
}

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