Wicket: Getting Tags Attribute - java

I am combining wicket and jQuery for some project.
I have in HTML:
<a wicket:id="link" testAttr="test"></a>
And using jQuery I modify this attribute when other components on the page are clicked. My question here is how to obtain the current value of attribute "testAttr" from Java? I am fetching the value on every ajax call and see with inspect element that is changed, so no problem with that.
I have tried with getMarkupAttributes() but I always get value "test" and not the current one which I see on the page with inspect element. Also tried with AttributeModifier and Appender, onComponentTag, but had no luck.
Does anybody have an idea what to do here?

You have to send the current attribute value to the server as a 'dynamic extra parameter':
link.add(new AjaxEventBehavior("click") {
updateAjaxAttributes(ARA ara) {
super.updateAttributes(ara);
ara.getDynamicExtraParameters()
.add("return {'q' : jQuery('#' + attrs.c).attr('testAttr') };");
}
onEvent(ART art) {
RequestCycle requestCycle = RequestCycle.get();
String val = requestCycle.getRequest()
.getRequestParameters()
.getParameterValue("q")
.toString();
// ...
}
});

Related

JxBrowser How to get value from a html node within java

Hello guys I am trying out the jxBrowser component and I am unable to the value of selected html component...
List<DOMElement> paragraphs = divRoot.findElements(By.cssSelector("p"));
for (DOMElement paragraph : paragraphs) {
System.out.println("paragraph.getNodeValue() = " +
paragraph.getNodeValue());
}
I am able to find paragraphs.. But can't get their node's value.. or simply <p>I cant get this value<p/> The code must be okay because its just a pure copy of their own sample code: here
So my question is... What have I done wrong? It seems properly imported.. I am using library version 6.19.1 on a macbook. ( And I even tried it on a windows 10 with same result.. )
Or if there is other java browser solution with similar functions.. What I need is to load a page, get some values out of some divs and then simulate click.
DOMElement.getNodeValue() returns the value of this node, depending on its DOMNodeType. The text you are trying to get is a children node for the node, so you need to get it with the following code paragraph.getChildren().get(0).
So, the final code will look like the following:
for (DOMElement paragraph : paragraphs) {
System.out.println("paragraph.getNodeValue() = " +
paragraph.getChildren().get(0).getNodeValue());
}

PF datatable value and filteredValue - best practise

I should have asked this question way earlier but now I am really tired of dodging around this problem:
I have a normal datatable like
<p:dataTable id="dt1" var="tVar" value="#{mrBean.queriedElements}" filteredValue="#{mrBean.filteredElements}" ...
Now in addition to the primefaces filters, I made my own panelGrid in which you can apply filters to the data base which work before any PF action.
The following lists exist: queriedElements which holds all the data that is returned after my personal filter applied and filteredElements which is needed for primefaces datatable filtering. In addition, I am not exactly sure whether I need an element list that represents all the data from the database. If no personal filter is applied, queriedElements = allElements.
The datatable displays a lot of information on the objects contained and you can change these objects via a dialog. I want the following:
When saved, update all changes made to the selectedElement
When cancelled, revert all changes in the datatable (I dont use a temporary object that is edited but the very object from the list)
When closing the dialog, remember all filters and paginator position
What is the best practise to do so and how can I avoid redundant code for queriedElements and filteredElements (in case I must iterate through it to change it explicitly in addition to database merges)? I found the first attribute for pagination, but I'm not really sure how to use it properly combined with my other requirements. My main problem is that the datatable almost never displays the right values if I don't refetch from database.
PF 4.0
I don't know why PF 4.0 doesn't do this by itself, but something that worked for me can be found at http://www.brainhemorage.com/?p=258
Although I had to replaced the lines
ValueExpression filterBy = column.getValueExpression("filterBy");
String filterField = null;
if (filterBy != null)
filterField = table.resolveStaticField(filterBy);
String filterId = column.getContainerClientId(context) + separator + "filter";
String filterValue = params.containsKey(filterId) && !table.isReset() ? params.get(filterId) :
table.getFilters().get(filterField); // <-- and here, was ""
String filterStyleClass = column.getFilterStyleClass();
by
String filterId = column.getContainerClientId(context) + separator + "filter";
String filterValue = params.containsKey(filterId) && !table.isReset() ? params.get(filterId) :
table.getFilters().get(column.getFilterBy());
because getValueExpression always returned null.
Although this doesn't answer my question about the BP, this will surely help others with the filteredValue problem.

To fill a dropdown from servelet using ajax

I need to fill a drop down from database using ajax, Iam using two drop downs, if first drop down value is selected the second drop down value(have to be retrieved from DB based on the values selected in the first drop down) must have to be displayed. The DAO(Data Access Layer) returns 4 results as arraylist object but in http responsetext it is printing as object not the values.I tried using for loop to iterate it but i can't achieve it. Please assist me on this.
HTML Code:
// First Drop Down
Question Field :<select name="ddlAddQuestionField" id='ddlAddQuestionField' onchange="getFieldPosition()">
<option value=''>Select Question Field</option>
<option value='Security Question'>Security Question</option>
<option value='Personal Info'>Personal Info</option>
</select>
// Second DropDown
User Field Position:<select name="userFieldPosition" id="userFieldPosition" disabled="disabled"> </select>
Javascript Code
function getFieldPosition(){
var fieldName =$("#ddlAddQuestionField").val();
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("userFieldPosition").disabled=false;
alert(xmlhttp.responseText);
var response =xmlhttp.responseText;
for(var i=0;i<response.length;i++) {
var elements = "<option value='"+response[i]+"'>"+response[i]+"</option>";
$("#userFieldPosition").append(elements);
}
}
}
xmlhttp.open("POST","ApplicationController",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fieldAction=fieldPosition&fieldName="+fieldName);
}
Servelet Code
fieldPositionObj = fieldPositionDaoObj.getFieldPosition(fieldName); //Hitting the Dao
// In dao it returns arraylist object.
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(fieldPositionDaoObj);
Your Problem is line
response.getWriter().write(fieldPositionDaoObj);
You are writing java Obejct Directly on Response.. I think fieldPositionDaoObj is list or aray.. so toString Representation is
(com.bean.QuestionInfoBean#23d275, com.bean.QuestionInfoBean#1ce15f6, com.bean.QuestionInfoBean#103fcaa, com.bean.QuestionInfoBean#c135d6)
Where com.bean.QuestionInfoBean#c135d6 is toString Representation of your Java Object.
I think wat you need to return there is JSON respresentation of Java Object/List/Array and your code will work
JSON (JavaScript Object Notation), is a simple and easy to read and write data exchange format. It’s popular and implemented in countless projects worldwide, for those don’t like XML, JSON is a very good alternative solution.
Your JSON Representation should look like
[ First,Middle,Full,Last]
or
[{First},{Middle},{Full},{Last}]
you can write your own method somethinglike public String getJSOnRepresentation();
and then do
response.getWriter().write(fieldPositionDaoObj.getJSOnRepresentation());
Sample example on What and how to code
Also see
http://json.org/java/
https://github.com/douglascrockford/JSON-java/blob/master/JSONString.java
https://github.com/douglascrockford/JSON-java/blob/master/JSONArray.java
https://github.com/douglascrockford/JSON-java/blob/master/JSONObject.java
I tried the below mentioned code it's working fine now.
JAVA SCRIPT:
if(xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("userFieldPosition").disabled=false;
var response = JSON.parse(xmlhttp.responseText);
for(var i=0;i<response.length;i++){
elements += "<option value='"+response[i].fieldPosition+"'>"+response[i].fieldPosition+"</option>";
}
$("#userFieldPosition").append(elements);
}
}
SERVELET:
Gson gson = new Gson();
String json = new Gson().toJson(fieldPositionObj);
response.getWriter().print(json);
There are certain frameworks such as ExtJs which allow you to do this with out much code. The only way I can think of doing this is by placing your second drop down box inside a div tag. On selection of the 1st drop down box, call a function which will make the ajax request. Once you obtain a success response, rewrite the content of your div by creating a new drop down box with these values.

How to add a parameter to a URL in GWT?

I have a Java/GWT application. In that there is a list of items. If I click on any item title then that item is opened with full description.
I am using Anchor for the item title, so what I want is when user clicks on item title then in the URL the id of that item is appended to the current URL.
For example, this is my URL:
"http://127.0.0.1:8888/MyApp.html?gwt.codesvr=127.0.0.1:9997#listItem?list"
and I have to append id to the end of the URL like:
"http://127.0.0.1:8888/MyApp.html?gwt.codesvr=127.0.0.1:9997#listItem?list&itemId=55"
Using Window.Location should do your trick : see the doc here
Something like this :
String url = Window.Location.getHref();
url = url + "&itemId=" + itemId;
Window.Location.replace(url);
Although of course, as Crollster pointed out, you should insert your url parameter before the # sign. Give more details on what you're looking for exactly (why do you have to add the parameter manually, does the page have to reload ...)
you can use redirect command in order to add this parameter
response.sendRedirect(your url + itemId=55);
Then you can extract this variable.
I hope this will help.
You can try with javascript coding.When the user clicks on link, get this URL and appends your id to it and reconstruct the URL.
You see that # in the URL? Thats an anchor - you will need your parameter to be added before that, so it looks like this:
http://127.0.0.1:8888/MyApp.html?gwt.codesvr=127.0.0.1:9997&itemId=55#listItem?list
HTH
URIBuilder of Apache HttpComponents offers a convenient method to add parameters and will deal with existing query parameters and anchors.

Using <jsp:include> to make a servlet call that returns additional <jsp:include>'s, but they're not being rendered

So this question suggested using a servlet to do the file check before doing the include:
How can you check if a file exists before including/importing it in JSP?
So I wrote a servlet that does that. I call it using something like
<jsp:include page='<%= "/servlet/fileChecker?section=THX&file=1138" &>'></jsp:include>
but the output of that servlet call contains a jsp:include tag, to the file I was checking for. Unfortunately, the browser doesn't "include" it. I'm getting errors like "there is no attribute 'page'" and "element 'jsp:include' undefined" -- which suggests the servlet output is not being rendered as Java but as HTML.
Here is the output:
<p>Text before the servlet call</p>
<p><h4>From THX1138</h4><jsp:include page='thx/results_1138.jsp'></jsp:include></p>
<p>Text after the servlet call</p>
Here is the main call of my servlet:
private String FileChecker(String section, String file) {
String result = ""; // assume file does not exist
String pathToCheck = section + "/results_" + file + ".jsp";
// realPath is defined in the init() method as config.getServletContext().getRealPath("/");
File fileToCheck = new File(realPath + pathToCheck);
if (fileToCheck.exists()) {
result = "<p><h4>" + section + "</h4><jsp:include page='" + pathToCheck + "'></jsp:include></p>";
}
return result;
}
I feel like the answer is close, but I'm not sure what curtain I should be looking behind. Any help?
Do not write a string with a bunch of HTML and JSP tags to the response. This makes no sense. The webbrowser does not understand JSP tags.
Call RequestDispatcher#include() instead.
request.getRequestDispatcher(checkedJspPath).include(request, response);
And move that HTML back into the JSP.
Unrelated to the concrete question, I know that you're referring to an old answer of me, but I realize that it's actually better to check if ServletContext#getResource() doesn't return null instead of using File#exists(). This way it'll work as well whenever the WAR is not expanded.

Categories

Resources