I have an iterator which requires to use mapped properties or indexed properties but my getter-setter are not getting those values.
For Ex:
(This is just an example. Ultimately the idea is whether I can use mapped property in struts 2 or not. If yes, then how.)
index.jsp:
<s:form action="hello" namespace="foo">
<s:textfield name="arp(0)" /> <br/>
<s:textfield name="prp(0)" /> <br/>
<s:textfield name="arp(1)" /> <br/>
<s:textfield name="prp(1)" /> <br/>
<s:submit value="Say Hello" />
</s:form>
helloWorld.action:
class PRLists {
String arp;
String prp;
public String getArp() {
return Arp;
}
public void setArp(String aRP) {
arp = aRP;
}
public String getPrp() {
return prp;
}
public void setPrp(String pRP) {
prp = pRP;
}
}
public class HelloWorldAction {
ArrayList<PRLists> prlist = new ArrayList<PRLists>();
public String execute() throws Exception {
System.out.println("ruuning execute");
return "success";
}
public ArrayList<PRLists> getPrlist() {
return prlist;
}
public void setPrlist(ArrayList<PRLists> prlist) {
this.prlist = prlist;
}
public String getArp(String key) {
int index = Integer.parseInt(key);
return prlist[index].arp;
}
public void setArp(String key, Object value) {
System.out.println("set ARP: index:" + index + ", value" + value);
int index = Integer.parseInt(key);
prlist[index].arp = value.toString();
}
public String getPrp(String key) {
int index = Integer.parseInt(key);
return prlist[index].prp;
}
public void setPrp(String key, Object value) {
System.out.println("set PRP, Key:" + key + ", value:" + value);
int index = Integer.parseInt(key);
prlist[index].prp = value.toString();
}
}
Earlier I was having this kind of working functions in struts 1 but now I am trying to move it to struts 2. Now my setter functions in HelloWorldAction.java for arp and prp are not getting called upon form submit.
public void setArp(String key, Object value);
public void setPrp(String key, Object value);
<s:textfield name="prlist[0].arp" /> can work but we have some dependent code which requires to use fields with name such as <s:textfield name="arp(0)" />.
I do not know whether struts 2 supports mapped properties or not. If it supports, then how can I use it.
I also found a related issue: https://issues.liferay.com/browse/LPS-14128
Note: I have made some modifications in question description
Thanks in advance.
You're violating a lot of "rules" here, other than avoiding almost any mechanism provided by the framework. Never put logic in accessors / mutators (getters / setters), never use capitalized variable names, avoid using variables starting with an uppercase letter, read struts Type Conversion, use Struts tags (eg. <s:textfield/> instead of <input type="text" />) whenever possible, and reduce your code to:
public class HelloWorldAction{
private String name;
private List<PRLists> arnList = new ArrayList<PRLists>();
public String execute() throws Exception {
System.out.println("running execute");
return "success";
}
public List<PRLists> getArnList(){
return arnList;
}
public void setArnList(List<PRLists> arnList){
this.arnList = arnList;
}
public String getName() {
return name;
}
public void setName(String name) {
System.out.println("set name: "+name);
this.name = name;
}
}
<s:form action="hello" namespace="foo">
<s:textfield name="name" label="name" />
<s:textfield name="arnList[0].arp" /> <br/>
<s:textfield name="arnList[0].prp" /> <br/>
<s:textfield name="arnList[1].arp" /> <br/>
<s:textfield name="arnList[1].prp" /> <br/>
<s:submit value="Say Hello" />
</s:form>
of in an iterator, as you said (without showing it), like
<s:form action="hello" namespace="foo">
<s:textfield name="name" label="name" />
<s:iterator value="arnList" status="rowStatus">
<s:textfield name="arnList[%{#rowStatus.index}].arp" /> <br/>
<s:textfield name="arnList[%{#rowStatus.index}].prp" /> <br/>
</s:iterator>
<s:submit value="Say Hello" />
</s:form>
Related
creating a webserver in netbeans with I have 3 files index.jsp, response.jsp and client.java.
the idea is to create a temperature converter, but only takes the input and not doing the calculator job.
please any help!?
index.jsp
<form name="Input Form" id="ftemp" action="response.jsp">
<input type="text" name="temp" />
<select name="conv1">
<option>Celsius</option>
<option>Fahrenheit</option>
</select>
<select name="conv2">
<option>Fahrenheit</option>
<option>Celsius</option>
</select>
<input type="submit" value="Submit" />
</form>
response.jsp
<body>
<h1>your list is in order</h1>
<jsp:useBean id="sortbean" scope="session" class="sortclient.SortClient" />
<jsp:setProperty name="sortbean" property="input" />
<jsp:setProperty name="sortbean" property="cel" />
<jsp:setProperty name="sortbean" property="fahr" />
<jsp:getProperty name="sortbean" property="input" />
</body>
client.java
public class SortClient {
private String input;
double cel = 0;
double fahr = 0;
public SortClient (){
input = null;
}
public String getInput() {
try{
String key = getKey();
input = mergeSort (input,key);
double tempCelsius = input.nextDouble();
double tempFahrenheit = input.nextDouble();
return input;
}catch (Exception ex){
System.out.println(ex); //we would log this
return "That is not a valid list";
}
}
public void setInput(String input) {
this.input = input;
}
public double toCelsius( double tempFahrenheit )
{
return ((5.0 / 9.0) * ( tempFahrenheit - 32 ));
}
public double toFahrenheit( double tempCelsius )
{
return (tempCelsius * 9.0 / 5.0) + 32;
}
private static String mergeSort(java.lang.String input, java.lang.String userKey) {
org.tempuri.Service service = new org.tempuri.Service();
org.tempuri.IService port = service.getBasicHttpBindingIService();
return port.mergeSort(input, userKey);
}
private static String getKey() {
org.tempuri.Service service = new org.tempuri.Service();
org.tempuri.IService port = service.getBasicHttpBindingIService();
return port.getKey();
}
You have multiple problems in your code. Here are some suggestions:
Match the input names in index.html and SortClient.java to avoid confusion and simplify property assignments
Create setter and getter for all fields or else jsp:setProperty and jsp:getProperty won't work
Pay attention on your data types: String doesn't have nextDouble(). If you haven't please use IDE (Eclipse, Netbeans, Intellij .etc) assistance.
Remove unnecessary libraries and code eg. org.tempuri.*
Here are codes implementing suggestions above:
index.jsp
<form name="Input Form" id="ftemp" action="response.jsp">
<input type="text" name="temp" />
<select name="conv1">
<option>Celsius</option>
<option>Fahrenheit</option>
</select>
<select name="conv2">
<option>Fahrenheit</option>
<option>Celsius</option>
</select>
<input type="submit" value="Submit" />
</form>
response.jsp
<h1>your list is in order</h1>
<jsp:useBean id="sortbean" scope="session" class="sortclient.SortClient" />
<jsp:setProperty name="sortbean" property="*" />
Input: <jsp:getProperty name="sortbean" property="temp" /><br>
Conv1: <jsp:getProperty name="sortbean" property="conv1" /><br>
Conv2: <jsp:getProperty name="sortbean" property="conv2" /><br>
Result: <jsp:getProperty name="sortbean" property="result" />
SortClient.java
package sortclient;
public class SortClient {
private String temp;
private String conv1;
private String conv2;
private Double result;
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
public String getConv1() {
return conv1;
}
public void setConv1(String conv1) {
this.conv1 = conv1;
}
public String getConv2() {
return conv2;
}
public void setConv2(String conv2) {
this.conv2 = conv2;
}
public Double getResult() {
result = Double.parseDouble(temp);
if (conv1.equalsIgnoreCase(conv2)) {
return result;
} else if (conv2.equalsIgnoreCase("Celsius")) {
return toCelsius(result);
} else if (conv2.equalsIgnoreCase("Fahrenheit")) {
return toFahrenheit(result);
}
return 0.0;
}
public double toCelsius(double tempFahrenheit )
{
return ((5.0 / 9.0) * ( tempFahrenheit - 32 ));
}
public double toFahrenheit( double tempCelsius )
{
return (tempCelsius * 9.0 / 5.0) + 32;
}
}
Refer to this tutorial for detailed guide.
As other have suggested, this approach is actually considered obsolete as it's tightly coupled and not maintainable on big scale. So I'd also suggest you to learn MVC pattern as from tutorial such as:
http://courses.coreservlets.com/Course-Materials/csajsp2.html
http://www.thejavageek.com/2013/08/11/mvc-architecture-with-servlets-and-jsp/
I am using Struts2 tags in JSP. Below is the Action class.
package com.action;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
public class EmpLeavePlan extends ActionSupport{
private String bankId;
private String empName;
private String monthYear;
private String leaves;
private Map<String,String> bankIds;
public String display() {
return "SUCESS";
}
public String getDefaultSearchEngine() {
return "yahoo.com";
}
public String execute() throws Exception
{
bankIds = new HashMap<String,String>();
bankIds.put("1541742","h6");
bankIds.put("1541742","eft");
bankIds.put("1394842","dfd");
bankIds.put("1541742","dfee");
return "SUCCESS";}
public String getBankId() {
return bankId;
}
public Map<String, String> getBankIds() {
return bankIds;
}
public void setBankIds(Map<String, String> bankIds) {
this.bankIds = bankIds;
}
public void setBankId(String bankId) {
this.bankId = bankId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getMonthYear() {
return monthYear;
}
public void setMonthYear(String monthYear) {
this.monthYear = monthYear;
}
public String getLeaves() {
return leaves;
}
public void setLeaves(String leaves) {
this.leaves = leaves;
}}
JSP:
<%# taglib uri="/struts-tags" prefix="s" %>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
var currentDate = new Date();
$("#datepicker").datepicker( {
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'MM yy'
/* onClose: function(dateText, inst) {
$(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1));
} */
});
$("#datepicker").datepicker("setDate", currentDate);
});
</script>
<style>
.ui-datepicker-calendar {
display: none;
}
.ui-datepicker-year{
width: 70px !important;
height: 25px;
}
.ui-datepicker-month{
width: 60px !important;
height: 25px;
}
.ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all{
width: 213px !important;
}
</style>
<h1> Leave Plan Management!!! </h1>
<body style="background-color:lightgrey;">
<s:form action="bankgen">
<s:textfield name="monthYear" label="Month/Year" id="datepicker"></s:textfield>
<%-- <s:select label="Select Bank ID"
headerKey="-1" headerValue="Select bank id" list="bankIds"
name="bankIdd" id="bankChange" /> --%>
<s:select label="Select Bank ID"
headerKey="-1" headerValue="Select bank id" list="bankIds"
name="bankId" id="bankChange" />
<s:textfield name="empName" label="Name" id="empName"></s:textfield>
<s:textarea name="leaves" label="Leaves :" id="leaves"></s:textarea>
<s:submit value="save"></s:submit>
</s:form>
</body>
However, I am not getting the output. In the dropdown the values alone are reflection and not the key which is the bank id. I want the bank ids to be in the bank id column and the key values to be in the emp name column.
The bankIds with corresponding empName are populated in the action method
public String execute() throws Exception {
bankIds = new HashMap<String,String>();
bankIds.put("1541742","h6");
bankIds.put("1541742","eft");
bankIds.put("1394842","dfd");
bankIds.put("1541742","dfee");
//before returning to JSP you should set empName
empName = bankIds.get(bankId);
return "SUCCESS";
}
You didn't initialize bankId so it would be empty at the first time. After you submit the form the bankId will be populated and corresponding empName will be initialized. Both values will be pre-selected in Struts tags. Because you didn't use value attribute the value will be evaluated using name attribute.
You can use two action methods: one for rendering JSP using GET http method and another for submitting a form using POST http method. When bankId is posted the bankIds map should be already populated. So you should use another method prepare() to populate the map bankIds. To be called automatically before the action is executed and result JSP is returned the action class should implement Preparable interface.
public class EmpLeavePlan extends ActionSupport implements Preparable {
...
public void prepare() {
bankIds = new HashMap<String,String>();
bankIds.put("1541742","h6");
bankIds.put("1541742","eft");
bankIds.put("1394842","dfd");
bankIds.put("1541742","dfee");
}
public String executeGet() throws Exception {
//before returning to JSP you should set empName
empName = bankIds.get(bankId);
return "SUCCESS";
}
public String executePost() throws Exception {
//before returning to JSP you should set empName
empName = bankIds.get(bankId);
return "SUCCESS";
}
...
}
If you want to update empName when you select from the dropdown dynamically with javascript
<s:select label="Select Bank ID"
headerKey="-1" headerValue="Select bank id" list="bankIds"
name="bankId" id="bankChange" />
<s:textfield name="empName" label="Name" id="empName" />
<script>
$(function(){
$("#bankChange").change(function(){
$("#empName").val($(this).val());
});
});
</script>
I have tried this a lot since last couple of days, but still not able to solve this.
I am using liferay 6.1 and struts 2. Basically i have two dropdowns in my liferay portlet, one for country and other for states. When selecting the country, state list needs to be in drop down list according to the country selected. I am trying to do this through AJAX. (Below code I found from google, its working in a separate Dynamic Web Project, but when i tried this in liferay portlet its throwing error.
Below is my Code:
StartPage.jsp
<script >
$(document).ready(function() {
$('#country').change(function(event) {
var country = $("select#country").val();
alert(country);
$.getJSON("<s:url action='ajaxAction' namespace='ajax' includeParams='none' />", {countryName : country}, function(jsonResponse) {
$('#ajaxResponse').text(jsonResponse.dummyMsg);
alert($('#ajaxResponse').text(jsonResponse.dummyMsg));
var select = $('#states');
select.find('option').remove();
$.each(jsonResponse.stateMap, function(key, value) {
$('<option>').val(key).text(value).appendTo(select);
});
});
});
});
</script>
<s:form name="StartPage" id="StartPage">
<s:select id="country" name="country"
list="{'Select Country','India','US'}" label="Select Country" />
<br />
<br />
<s:select id="states" name="states" list="{'Select State'}"
label="Select State" />
<br />
<br />
<div id="ajaxResponse"></div>
</s:form>
struts.xml
<package name="default" extends="json-default">
<action name="ajaxAction" class="com.action.AjaxJsonAction">
<result type="json">/WEB-INF/view/StartPage.jsp
</result>
</action>
</package>
Action Class:
public class AjaxJsonAction extends DefaultActionSupport{
private Map<String, String> stateMap = new LinkedHashMap<String, String>();
private String dummyMsg;
//Parameter for Jquery
private String countryName;
#Override
public String execute() {
System.out.println("i am executed...");
System.out.println("CountryName: " + countryName);
if (countryName.equals("India")) {
stateMap.put("1", "Kerala");
stateMap.put("2", "Tamil Nadu");
stateMap.put("3", "Jammu Kashmir");
stateMap.put("4", "Assam");
} else if (countryName.equals("US")) {
stateMap.put("1", "Georgia");
stateMap.put("2", "Utah");
stateMap.put("3", "Texas");
stateMap.put("4", "New Jersey");
} else if (countryName.equals("Select Country")) {
stateMap.put("1", "Select State");
}
dummyMsg = "Ajax action Triggered";
System.out.println("exiting.....");
return "success";
}
public Map<String, String> getStateMap() {
return stateMap;
}
public String getDummyMsg() {
return dummyMsg;
}
public String getCountryName() {
return countryName;
}
public void setStateMap(Map<String, String> stateMap) {
this.stateMap = stateMap;
}
public void setDummyMsg(String dummyMsg) {
this.dummyMsg = dummyMsg;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
}
Errro Log:
java.lang.IllegalArgumentException: application/json;charset=UTF-8 is not a supported mime type
at com.liferay.portlet.MimeResponseImpl.setContentType(MimeResponseImpl.java:159)
at org.apache.struts2.portlet.servlet.PortletServletResponse.setContentType(PortletServletResponse.java:219)
at org.apache.struts2.json.JSONUtil.writeJSONToResponse(JSONUtil.java:225)
at org.apache.struts2.json.JSONResult.writeToResponse(JSONResult.java:211)
at org.apache.struts2.json.JSONResult.execute(JSONResult.java:172)
at com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:373)
You can use AJAX AUI script for this. I am using Liferay 6.2 sp2 SDK and Liferay MVC portlet. You can try this with struts approach to see if it helps you.
Use liferay.provide function in your AUI script.
<aui:script>
Liferay.provide(
window,
'<portlet:namespace />updatePermState',
function() {
var A = AUI();
var url = '<%= ajaxCallResourceURL.toString() %>';
A.io.request(
url,
{
//data to be sent to server
data: {
<portlet:namespace />param1: (document.getElementById('<portlet:namespace/>mCountry').value),
}, .....
}
Create servResource function in your portlet class. This will be wired with your AUI call:
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws IOException, PortletException {
resourceResponse.setContentType("text/javascript");
... ...
//Send Data Back
resourceResponse.setContentType("text/html");
}
In your calling JSP file add this:
<!-- Create a serveResource URL -->
<portlet:resourceURL var="ajaxCallResourceURL" />
AJAX call. I am using onChange method when on the Country field. My UpdatePermState() function is creating a div with the states dynamically.
<aui:select name="mCountry" id="mCountry" label="Country of permanent address*" inlineLabel="left" onChange='<%= renderResponse.getNamespace() + "updatePermState();" %>'>
I have a form in JSP having two fields, and in action class I have an instance variable for each field, but those attributes are null when action class is executing.
I have used validate() method that is not even executing.
JSP
<s:form action="addAuthority">
<table>
<caption> <b><big>Add New Authority</big></b>
</caption>
<s:if test="hasActionErrors()">
<tr>
<td><s:actionerror />
</td>
</tr>
</s:if>
<s:if test="hasActionMessages()">
<tr>
<td><s:actionmessage />
</td>
</tr>
</s:if>
<tr>
<td></td>
<td>
<s:textfield name="role" label="Authority Name"></s:textfield </td>
<td></td>
<td>
<s:select name="dependentAuthority" list="#request.authorityList" label="Dependent Authority" listKey="roleId" listValue="role"></s:select>
</td>
<td>
<s:submit value="Add"></s:submit>
</td>
</tr>
</table>
</s:form>
Action
public class AddAuthorityAction extends ActionSupport {
private String dependentAuthority;
private String role;
private Map<String, Object> session;
private HttpServletRequest request;
public String execute() throws Exception{
HttpServletRequest request = ServletActionContext.getRequest();
//System.out.print(role + " " + dependentAuthority+" ");
role = request.getParameter("role");
dependentAuthority = request.getParameter("dependentAuthority");
//System.out.print(role+" "+ dependentAuthority);
//insert the data
int count = new DBInsert().addRoleDependency(role, Integer.parseInt(dependentAuthority));
if(count==0){
addActionError("There is some error while inserting. Please try again");
}else{
addActionMessage("Information successfully inserted");
}
return SUCCESS;
}
#SuppressWarnings("unchecked")
public String moveAddAuthority() {
Map request = (Map) ActionContext.getContext().get("request");
List<Role> authorityList = new DBSelect().getAuthorityId();
request.put("authorityList", authorityList);
List<Role> roleWithDependency = new DBSelect().getRoleWithDependence();
request.put("roleWithDependency", roleWithDependency);
return SUCCESS;
}
public void validate() {
if (role == null || role.trim().equals("")) {
addFieldError("role", "The name is required");
}
}
public String getDependentAuthority() {
return dependentAuthority;
}
public void setDependentAuthority(String dependentAuthority) {
this.dependentAuthority = dependentAuthority;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}}
when I am using HttpServletRequest request = ServletActionContext.getRequest(); I can get the value;
but through implementing ServletRequestAware request become null;
without using both instance variable is null;
I could not get ActionMessage in JSP page.
struts.xml
<action name="addAuthority" class="nodue.action.AddAuthorityAction"
method="execute" >
<interceptor-ref name="authonticateInterceptor"></interceptor-ref>
<result name="success" type="redirect">moveAddAuthority</result>
</action>
<action name="moveAddAuthority" class="nodue.action.AddAuthorityAction"
method="moveAddAuthority">
<interceptor-ref name="authonticateInterceptor"></interceptor-ref>
<result name="success">/authority.jsp</result>
</action>
I have made some modification on datatype of dependentAuthority previously it was Integer, and also added in JSP page the <s:if> tag.
You are probably using a single Interceptor, while you should use an entire stack with your interceptor in it.
You are returning the redirect result that should be used to reach external URLs or non-action URLs. To redirect to an action you should use redirectAction result.
No matter if redirect or redirectAction, when you redirect you lose the request parameters, and this is why you don't see action errors and messages. There are different solutions to this.
You use the validate() method, that returns INPUT result when things go south. But you haven't defined any INPUT result for your actions; be sure to understand how the INPUT result works, along with ValidationInterceptor and ParameterInterceptor.
I have got a little problem with Struts2, and I don't know why it doesn't work ...
I want to pass 2 variables between two JSP, via an Action class :
view1.jsp :
<s:form action="myAction">
<input id="var1" name="var1" type="text" />
<input id="var2" name="var2" type="text" />
<button type="submit"> Ok </button>
</s:form>
-> var1 and var2 are the variables that I want to pass to the Action class
struts.xml:
<action name="myAction" class="MyAction" method="execute">
<result name="success">view2.jsp</result>
</action>
Action.java :
public class MyAction extends DefaultActionSupport
{
private String var1;
private String var2;
public String execute() throws Exception
{
// ... Some actions ...
return SUCCESS;
}
// Getters & Setters for var1 and var2 (generated by Eclipse)
public String getVar1()
{
return var1;
}
public void setVar1(String var1)
{
this.var1 = var1;
}
public String getVar2()
{
return var2;
}
public void setVar2(String var2)
{
this.var2 = var2;
}
-> This works correctly ; if I put "System.out.print" with the getters, it shows me the good values of var1 (content1) and var2 (content2)
view2.jsp :
Values of var1 = <s:property value="var1" />
Values of var2 = <s:property value="var2" />
Textfield with var1 in default-value : <s:textfield value="%{var1}" />
Textfield with var2 in default-value : <s:textfield value="%{var2}" />
-> There is a problem here :
I can't get the content of var1 and var2 !
-> <s:property value="var1" /> and <s:textfield value="%{var1} are returning "null"
Where is my error ? I don't understand ... I followed what the others said on the internet ...
Thank you !
I finally found the answer to my problem !
To get the value of var1and var2I had to use those following lines :
view1.jsp :
<s:form action="myAction">
<input id="var1" name="var1" type="text" />
<input id="var2" name="var2" type="text" />
<button type="submit"> Ok </button>
</s:form>
struts.xml:
<action name="myAction" class="MyAction" method="execute">
<result name="success">view2.jsp</result>
</action>
Action.java :
public class MyAction extends DefaultActionSupport{
private String var1;
private String var2;
public String execute() throws Exception{
// ... Some actions ...
ActionContext.getContext().getSession().put("var1", getVar1());
ActionContext.getContext().getSession().put("var2", getVar2());
return SUCCESS;
}
// Getters & Setters for var1 and var2 (generated by Eclipse)
public String getVar1(){
return var1;
}
public void setVar1(String var1){
this.var1 = var1;
}
public String getVar2(){
return var2;
}
public void setVar2(String var2){
this.var2 = var2;
}
}
view2.jsp :
Values of var1 = <s:property value="#session.var1" />
Values of var2 = <s:property value="#session.var2" />
//To transform var1 and var2 into JSP variables :
<s:set var="var1 " value="#session.var1 " />
<s:set var="var2 " value="#session.var2" />
<jsp:useBean id="var1 " type="java.lang.String" />
<jsp:useBean id="var2 " type="java.lang.String" />
<%
String myString1 = var1;
String myString2 = var2
%>