Accessing HashMap action variables using JSONObject in JSP file - json

I am working with Struts2 with java action class and view JSP file.
My Action class has a variable named:
HashMap<Integer, Boolean> pcksHavingFet;
List<pck> pcks;
int fet;
In pcks, I am having a list of pck's with primary key pckId.
I am having a code function in action class that evaluates pcks and assign true/false based on if pck is/is not associated with fet in Database. So we get a fully evaluated expression for pcksHavingFet Map.
//Code that evaluates and set pcksHavingFet varaible.
//Create A JSON Object to access this Map variable in JSP.
public void function()
{
// code to populate pcksHavingFet with key/value pair.
//e.g, pcksHavingFet = {1:true, 2:fALSE, 6:TRUE, 17:false, 11:true .....}
//Create JSON Object to access Map in JSP file
JSONObject jasonfeat = new JSONObject();
jasonfeat.accumulateAll(pcksHavingFet );
}
In Jsp File,
I need to access this pcksHavingFet Map Variable.
I am using below function to show/hide fetDropdown drop down based on pckId is true/false calculated from Map pcksHavingFet.
function pcksOnChange(pckId)
{
var pcksHavingFet = <ww:property value="pcksHavingFet "/> ;
<ww:set name="pcksHavingFet" value="%{JSONObject.fromObject(pcksHavingFet)}">
</ww:set>
fetDropdown.style.display = (pcksHavingFet [pckId]) ? "" : "none";
}
But I am able to see populated values in my action class for pcksHavingFet variables. But In JSP file, unable to access it though. Its coming as empty Map.
Please help me in accessing successfully this variable. It will be a gr8 help. I am new to JSON, Please elaborate your suggestion/help.
Thanks in advance.

Why you are not using Struts2 Build in mechanism to handle JSON.Struts2 provide [Json-plugin].1
The JSON plugin is bundled with Struts since 2.1.7+
All you need to do is to add the plugin jar jar in your class path and need to extends json-default in place of struts-default and you are good to go.
Suggest you to read plugin page for details and example how to work with JSON inside Struts2
Strus2-Json
just as a side note ww represent web-work which has now merged in to Struts2 so its a bit more clear to use tag- alias as s in-place of ww, but the end choice is all yours.
When you are asking question about Struts2 better tag them with struts2 not struts :)

Related

How to pass viewData back to the controller from partial view?

I have a main view using several partial Views.
Each of these partials use a different model and have post action.
My problem is I need one property from my main view's model to be used in one of my partials.
The partial view which I need to pass this property view is the last stage in the process.
The application reaches a partial view that contains a switch statement , based on the status on the item being queried, decides which partial will be rendered.
I have the property passing that far and even have it included in the Renderaction for the partial but I don't know how to retrieve it in the controller, PartialViewResult.
In the main view:
#{Html.RenderPartial("StatusForm", Model.HeadingDataModel.Status, new ViewDataDictionary { { "PurchaseOrderNumber", Model.AccordionModel.LtsSpecific.PurchaseOrderNumber } });}
PurchaseOrderNumber is what I'm after. The value gets passed to the next stage:
#{
var obj = ViewData["PurchaseOrderNumber"];
}
And within the same view:
Html.RenderAction("FinishedCalibrationForm", obj);
How can I retreive this in my controller ?? The following is not correct I know, but you get the idea.
public PartialViewResult FinishedCalibrationForm( string obj)
All help is appreciated.
Calling Html.RenderAction or Html.Action is largely the same as Url.Action. There's many different overloads, but essentially, the first parameter is the action name, the second parameter is going to be either the controller name or an anonymous object of route values, and the third parameter will be an anonymous object of route values if the second parameter was used for the controller name.
Anyways, whatever you pass in the route values will be used to find and call the associated action, which includes parameters for the action. So, for your example:
Html.RenderAction("FinishedCalibrationForm", new { obj = obj })
Would properly pass obj into your action method. As you have it now, it's going to interpret the value of obj as the controller name the action is within, which is obviously not correct.

Creating custom ExpandableListView, how to bind to "GroupTemplate" in axml

I've created a bindable version of ExpandableListView based off of https://github.com/hlogmans/MvvmCross.DeapExtensions/ and put it in my app. I want to add a GroupTemplate that I can bind to in the axml which would be similar to MvxListView's ItemTemplate.
Do I need to subclass MvxAndroidBindingResource? I'm also confused as to how the MvxBindingAttributes fits in.
The easiest route for this might be for you to take a read through how MvxListView and MvxAdapter work.
The MvxBindingAttributes (https://github.com/MvvmCross/MvvmCross/blob/v3.1/nuspec/DroidContent/MvxBindingAttributes.xml) allow MvvmCross to add new xml tags to the axml files.
The MvxAndroidBindingResource class (https://github.com/MvvmCross/MvvmCross/blob/v3.1/Cirrious/Cirrious.MvvmCross.Binding.Droid/ResourceHelpers/MvxAndroidBindingResource.cs) is the C# code to parse the values for the attribute tags defined in MvxBindingAttributes.
You can see this in action for an MvxListView in https://github.com/MvvmCross/MvvmCross/blob/v3.1/Cirrious/Cirrious.MvvmCross.Binding.Droid/Views/MvxListView.cs#L33
public MvxListView(Context context, IAttributeSet attrs, IMvxAdapter adapter)
: base(context, attrs)
{
// Note: Any calling derived class passing a null adapter is responsible for setting
// it's own itemTemplateId
if (adapter == null)
return;
var itemTemplateId = MvxAttributeHelpers.ReadListItemTemplateId(context, attrs);
adapter.ItemTemplateId = itemTemplateId;
Adapter = adapter;
}
In particular, the line:
var itemTemplateId = MvxAttributeHelpers.ReadListItemTemplateId(context, attrs);
This uses the id values parsed in MvxAndroidBindingResource to read the axml tag value for local:MvxItemTemplate

spring3mvcportlet populate JSON dojo select

I am new to Spring mvc3 portlet and dojo. I am trying to populate select dropdown with JSON data when jsp is loaded. I want to use dojo and give ajax call to controller and return JSON when jsp is loaded. Any tips will be helpful.
#Controller
#RequestMapping("/yourController")
public class YourController
{
#RequestMapping(value="/combo/{id}", method=ReqestNethod.GET)
public String getDropDownData(#ParamValue("id") long id)
{
List<Combo> combos = commonDao.getCombos(id);
String json = JsonUtil.toJson(combos); // or whichever way you use
return json;
}
}
Send requests from dojo to this url
<your-context-path>/yourController/combo/1
where 1 is your combo id.
I haven't checked the syntax here.. Wrote it blind. You might get compilation errors.
I get data in below format
How do I populate dojoType="xwt.widget.form.FilteringSelect"
{"ValuesDTO": {"items": [{},{"default": {"size": 5},"int": 10,"string": "Product1","string": "Product1 ","string": "product3","string": "product4","string": "product5"}]}}
I am sending dat in bean--->DTO--->List

Receiving data from a FormPanel in GWT

I have a FormPanel in GWT that should send a TextBox input to a new page (newPage.html). Below is my code. How do I receive this input in newPage.html, so that I can work with it from the associate newPage.java class? Thanks
final FormPanel form = new FormPanel();
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setMethod(FormPanel.METHOD_POST);
TextBox userid = new TextBox();
userid.setName("userid");
form.add(userid);
form.add(new Button("Submit", new ClickListener()
{
public void onClick(Widget sender)
{
form.submit();
}
}));
form.setAction("newPage.html");
RootPanel.get("demo").add(form);
If what you are trying to do is POST variables from one gwt-page using a formpanel to another gwt-page to process these POST results you can not, simply because gwt-pages are coded with java but in the end they are translated into javascript and javascript alone can not access POST variables.
You need to define a backend that can process your form in your form.setAction() method that should execute on the server-side and produce a valid html/text response. To get these results produced by your backend you need to add a FormHandler to your FormPanel. There is an example showing how to do that on javadocs. Then evaluating these results you can redirect accordingly.
If you want to handle what you send with a java class meaning you have a java backend, why not use GWT-RPC?

Spring MVC Request URLs in JSP

I am writing a web application using Spring MVC. I am using annotations for the controllers, etc. Everything is working fine, except when it comes to actual links in the application (form actions, <a> tags, etc.) Current, I have this (obviously abbreviated):
//In the controller
#RequestMapping(value="/admin/listPeople", method=RequestMethod.GET)
//In the JSP
Go to People List
When I directly enter the URL like "http://localhost:8080/MyApp/admin/listPeople", the page loads correctly. However, the link above does not work. It looses the application name "MyApp".
Does anyone know if there is a way to configure Spring to throw on the application name on there?
Let me know if you need to see any of my Spring configuration. I am using the standard dispatcher servlet with a view resolver, etc.
You need to prepend context path to your links.
// somewhere on the top of your JSP
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
...
Go to People List
The c:url tag will append the context path to your URL. For example:
<c:url value="/admin/listPeople"/>
Alternately, I prefer to use relative URLs as much as possible in my Spring MVC apps as well. So if the page is at /MyApp/index, the link <a href="admin/listPeople"> will take me to the listPeople page.
This also works if you are deeper in the URL hierarchy. You can use the .. to traverse back up a level. So on the page at/MyApp/admin/people/aPerson, using <a href="../listPeople"> will like back to the list page
I prefer to use BASE tag:
<base href="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/" />
Then, all your links can be like:
Go to People List
As i have just been trying to find the answer to this question and this is the first google result.
This can be done now using the MvcUriComponentsBuilder
This is part of the 4.0 version of Spring MVC
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilder.html
The method needed is fromMappingName
From the documentation :
Create a URL from the name of a Spring MVC controller method's request mapping.
The configured HandlerMethodMappingNamingStrategy determines the names of controller method request mappings at startup. By default all mappings are assigned a name based on the capital letters of the class name, followed by "#" as separator, and then the method name. For example "PC#getPerson" for a class named PersonController with method getPerson. In case the naming convention does not produce unique results, an explicit name may be assigned through the name attribute of the #RequestMapping annotation.
This is aimed primarily for use in view rendering technologies and EL expressions. The Spring URL tag library registers this method as a function called "mvcUrl".
For example, given this controller:
#RequestMapping("/people")
class PersonController {
#RequestMapping("/{id}")
public HttpEntity getPerson(#PathVariable String id) { ... }
}
A JSP can prepare a URL to the controller method as follows:
<%# taglib uri="http://www.springframework.org/tags" prefix="s" %>
Get Person
I usually configure tomcat to use context root of "/" or deploy the war as ROOT.war. Either way the war name does not become part of the URL.
You could use a servletRelativeAction. I'm not sure what versions this is available in (I'm using 4.0.x currently) and I haven't seen much documentation on this, but if you look at the code backing the spring form you can probably guess. Just make sure the path you pass it starts with a "/".
Example:
<form:form class="form-horizontal" name="form" servletRelativeAction="/j_spring_security_check" method="POST">
See org.springframework.web.servlet.tags.form.FormTag:
protected String resolveAction() throws JspException {
String action = getAction();
String servletRelativeAction = getServletRelativeAction();
if (StringUtils.hasText(action)) {
action = getDisplayString(evaluate(ACTION_ATTRIBUTE, action));
return processAction(action);
}
else if (StringUtils.hasText(servletRelativeAction)) {
String pathToServlet = getRequestContext().getPathToServlet();
if (servletRelativeAction.startsWith("/") && !servletRelativeAction.startsWith(getRequestContext().getContextPath())) {
servletRelativeAction = pathToServlet + servletRelativeAction;
}
servletRelativeAction = getDisplayString(evaluate(ACTION_ATTRIBUTE, servletRelativeAction));
return processAction(servletRelativeAction);
}
else {
String requestUri = getRequestContext().getRequestUri();
ServletResponse response = this.pageContext.getResponse();
if (response instanceof HttpServletResponse) {
requestUri = ((HttpServletResponse) response).encodeURL(requestUri);
String queryString = getRequestContext().getQueryString();
if (StringUtils.hasText(queryString)) {
requestUri += "?" + HtmlUtils.htmlEscape(queryString);
}
}
if (StringUtils.hasText(requestUri)) {
return processAction(requestUri);
}
else {
throw new IllegalArgumentException("Attribute 'action' is required. " +
"Attempted to resolve against current request URI but request URI was null.");
}
}
}
Since it's been some years I thought I'd chip in for others looking for this. If you are using annotations and have a controller action like this for instance:
#RequestMapping("/new") //<--- relative url
public ModelAndView newConsultant() {
ModelAndView mv = new ModelAndView("new_consultant");
try {
List<Consultant> list = ConsultantDAO.getConsultants();
mv.addObject("consultants", list);
} catch (Exception e) {
e.printStackTrace();
}
return mv;
}
in your .jsp (view) you add this directive
<%#taglib uri="http://www.springframework.org/tags" prefix="spring"%>
and simply use
<spring:url value="/new" var="url" htmlEscape="true"/>
New consultant
where
value's value should match #RequestMapping's argument in the controller action and
var's value is the name of the variable you use for href
HIH