i have jsp that call method in servlet. i tried to use System.out.println() to prove that my jsp success enter the servlet. The problem i face is i can't get the System.out.println() mean that my jsp can't go in the servlet. Please give some advice for this.
JSP:
<% SendPayment processPayment = new SendPayement();
success = processPayment.sendPayment( payMerInfoBean.getdbCon(), payOrderBean, payOrderParaBean, payMerInfoBean);%>
Servlet:
public boolean sendPayment(Connection con, B2cOrderBean payOrderBean,
B2cOrderParaBean payOrderParaBean, B2cMerInfoBean payMerInfoBean, B2cMcpOrderBean payMcpOrderBean, B2cEPayAlertBean ePayAlertBean) {
System.out.println("In SendPayment");
return false;
}
Related
I'm actually writing a java code in the setupRender() method. Depending of a value provided by the server side, i would like to display an Alert dialog box to the user. By clicking on ok, the application should be closed.
I have not already found how to display an Alert dialog box with tapestry. Do somebody know how to procedd?
Thanks
It's not quite clear to me what you are trying to achieve, but perhaps the following two suggestions are useful.
Suggestion 1 - Display a message using AlertManager
In the page class, inject AlertManager and add the message to it.
public class YourPage {
#Inject
AlertManager alertManager;
Object setupRender() {
// ...
alertManager.alert(Duration.UNTIL_DISMISSED, Severity.INFO, "Love Tapestry");
}
}
Then use the <t:alerts/> component in the page template file to have the message displayed.
Note: The user may dismiss the message, that is, make it disappear. But it doesn't 'close the application' (whatever it is that you mean by that).
Suggestion 2 - Redirect to another page
The setupRender method can return different things. For example, it could return another page class, causing a redirect to that page. On that page, you could have the messages displayed and the session subsequently invalidated (if that's what you meant by 'application should be closed'.
public class YourPage {
Object setupRender() {
// ...
return AnotherPage.class;
}
}
public class AnotherPage {
#Inject
Request request;
void afterRender() {
Session session = request.getSession(false);
session.invalidate();
}
}
See the Tapestry docs for details about what setupRender() can return.
Suggestion 3 - Use JavaScript to display Alert and trigger Component Event
This approach uses JavaScript to display an Alert and subsequently trigger a component event via ajax. The event handler takes care of invalidating the session.
Note: Closing the current browser windows/tab with JavaScript isn't as easy as it used to be. See this Stackoverflow question for details.
YourPage.java
public class YourPage {
boolean someCondition;
void setupRender() {
someCondition = true;
}
#Inject
private JavaScriptSupport javaScriptSupport;
#Inject
ComponentResources resources;
public static final String EVENT = "logout";
void afterRender() {
if (someCondition) {
Link link = resources.createEventLink(EVENT);
JSONObject config = new JSONObject(
"msg", "See ya.",
"link", link.toAbsoluteURI()
);
javaScriptSupport.require("LogoutAndCloseWindow").with(config);
}
}
#Inject Request request;
#OnEvent(value = EVENT)
void logout() {
Session session = request.getSession(false);
if (session != null) session.invalidate();
}
}
YourPage.tml
<!DOCTYPE html>
<html
xmlns:t="http://tapestry.apache.org/schema/tapestry_5_4.xsd"
xmlns:p="tapestry:parameter">
<h1>Hit the Road Jack</h1>
</html>
LogoutAndCloseWindow.js
define(["jquery"], function($) {
return function(config) {
alert(config.msg);
$.ajax({
type: "GET",
url: config.link
});
window.close(); // Legacy. Doesn't work in current browsers.
// See https://stackoverflow.com/questions/2076299/how-to-close-current-tab-in-a-browser-window
}
})
Is it possible to use AJAX in configuration mode?
I am using custom class extending DefaultConfigurationAction to customize my portlet in the configuration mode. I override processAction and render methods, which work OK, but when I try to implement serveResource method, it is never called (returned status is 200 OK, but no data is fetched and no debug message is printed to the Liferay console).
My code for serveResource method:
public class TestConfigurationController extends DefaultConfigurationAction {
...
#Override
public void serveResource(PortletConfig portletConfig, ResourceRequest resourceRequest,
ResourceResponse resourceResponse) throws PortletException, IOException, Exception {
String resourceID = resourceRequest.getResourceID();
System.out.println("Resource id=" + resourceID
+ " in TestConfigurationController.serveResource()."); // this message never prints, method is not invoked
if (IMG_EDIT_ADD_NEW.equals(resourceID)) {
// more code
include(EDIT_NEW_IMAGE, context, resourceRequest, resourceResponse); // uses PortletRequestDispatcher, returns a JSPF fragment
} else {
super.serveResource(portletConfig, resourceRequest, resourceResponse);
}
}
}
I tried all options on the JS side, including both JQuery and AUI. Here is relevant code in configuration.jsp:
<portlet:resourceURL var="newImageJsp" id = "<%=IMG_EDIT_ADD_NEW%>">
</portlet:resourceURL>
<aui:button name="addNewImage" type="button" value="${addImage}"/>
<div id="<portlet:namespace/>newImageContainer">
<aui:field-wrapper name="newImageContainer" label="${addImage}">
</aui:field-wrapper>
</div>
<script type="text/javascript" charset="utf-8">
// Even this simple AUI AJAX call does not trigger serveResource method!
// AUI().ready('aui-base', 'aui-module', 'node', 'aui-io-request', function (A) {
// A.io.request('<%=newImageJsp.toString()%>');
// });
jQuery(document).ready(function () {
jQuery('#<portlet:namespace/>addNewImage').on('click', function (event) {
console.log('addNewImage clicked, url: ${newImageJsp}'); // returns correct url
jQuery.ajax({
dataType: 'text',
url: '${newImageJsp}',
success: function (data, status) {
console.log('returned resource: ' + data); // returns empty string
console.log('returned status: ' + status); // returns 200 OK, which is also in the Firebunetwork panel
$('#<portlet:namespace/>newImageContainer').html(data);
}
});
return false;
});
});
</script>
Debugging in console revealed, JS is working fine, function was called and returned status was 200 OK. However, returned data was empty and serveResource method on the server was never called.
As an experiment, I also tried to set
<aui:form action="${newImageJsp}" method="get" name="fm1">
which didn't call the serveResource method either, instead, it returned the view.jsp of the configured portlet.
And finally my configuration, which is exactly as in this working case:
portlet.xml:
<portlet>
<portlet-name>test-portlet</portlet-name>
<portlet-class>org.springframework.web.portlet.DispatcherPortlet</portlet-class>
<init-param>
<name>contextConfigLocation</name>
<value>/WEB-INF/spring-context/portlet/test-portlet.xml</value>
</init-param>
<init-param>
<name>config-template</name>
<value>/WEB-INF/jsp/carousel/configuration.jsp</value>
</init-param>
<expiration-cache>0</expiration-cache>
<supports>
<mime-type>text/html</mime-type>
<portlet-mode>view</portlet-mode>
<portlet-mode>edit</portlet-mode>
</supports>
<portlet-info>
<title>Test</title>
</portlet-info>
</portlet>
and liferay-portlet.xml:
<liferay-portlet-app>
<portlet>
<portlet-name>test-portlet</portlet-name>
<icon>/icon.png</icon>
<configuration-action-class>com.test.TestConfigurationController</configuration-action-class>
<requires-namespaced-parameters>false</requires-namespaced-parameters>
<ajaxable>true</ajaxable>
<header-portlet-css>/css/main.css</header-portlet-css>
<header-portlet-javascript>/js/jquery-1.11.3.min.js</header-portlet-javascript>
<header-portlet-javascript>/js/main.js</header-portlet-javascript>
</portlet>
</liferay-portlet-app>
So, it seems I have a similar problem, as this unresolved issue
I was thinking, that maybe it is the window state? Configuration mode always uses 'pop-up', but in all examples I only found AJAX calls using 'normal' window state. Maybe that is the problem? Is it even possible to make asynchronous JSPF loadings in pop-up mode? And even in configuration window? I never found a working example of use of AJAX in configuration mode and official Liferay only has examples for view mode.
Last but not least, I tested the same code in view.jsp for view mode and the resource serving method in TestViewController was called OK. I used Spring annotations here (#ResourceMapping). So the problem must be with Liferay and configuration mode. A bug maybe?
Thank you!
I did something similar and use the PrintWriter Object in resourceResponse:
PrintWriter writer = resourceResponse.getWriter();
writer.print([yourResult]);
http://liferayiseasy.blogspot.hk/2015/03/ajax-call-in-spring-mvc-portlet.html
You can also add a class extends MVCPortlet
Your previous view.jsp
<portlet:resourceURL var="newImageJsp" name="newImageResource"
</portlet:resourceURL>
...
// create a new class:
public class CustomResourceController extends MVCPortlet {
...
#Override(name="newImageResource") // <---- define the name attribute which match with view.jsp
public void serveResource(PortletConfig portletConfig, ResourceRequest resourceRequest,
ResourceResponse resourceResponse) throws PortletException, IOException, Exception {
String resourceID = resourceRequest.getResourceID();
System.out.println("Resource id=" + resourceID
+ " in TestConfigurationController.serveResource()."); // this message never prints, method is not invoked
if (IMG_EDIT_ADD_NEW.equals(resourceID)) {
// more code
include(EDIT_NEW_IMAGE, context, resourceRequest, resourceResponse); // uses PortletRequestDispatcher, returns a JSPF fragment
} else {
super.serveResource(portletConfig, resourceRequest, resourceResponse);
}
}
}
So, I tried both liferay-portlet:resourceURL portletConfiguration="true" and portlet:resourceURL, also with manual parsing and modifying the url before sending. The resource serving method (whether implementation of the serveResource, or completely new method using either Spring MVC or Liferay MVC (implementation class of MVCPortlet)), none worked in configuration mode. Seems like a bug to me, as there is nowhere even a mention about this peculiarity in official documentation.
The solution for me was to avoid resource serving at all and instead choose action phase (p_p_lifecycle=1). It is completely doable in AJAX, just had to override processAction method in my DefaultConfigurationAction implementation class.
Hope this saves someone the countless hours I spent with it.
I'm trying to show in my App different errors when a user is already logged in and when the user wrote their username/password wrong. I have tried many ways but none of them is working. I don't know what else to try or if it's even possible. I don't know if I'm close to the solution either.
What I'm trying to do is:
Set the errorMessage in the request;
Set the SC_INTERNAL_SERVER_ERROR in the response so the AJAX function enters in ** and the HTML in the paramether is the one in the JSP with the specific Message.
Action
public class LogUser extends Action {
#Override
public void execute() throws Exception {
...
String pageToGo = this.tryLogUser(username, password);
request.getRequestDispatcher(pageToGo).forward(request, response);
}
private String tryLogUser(String username, String password) throws Exception {
String pageToGo = "page/userHome";
...
if(canLog) {
...
try {
...
Server.getInstance().logIn(user); // Throws an Exception if the User is already logged in.
...
} catch (ServerException e) {
this.setErrorMessage("That user is already logged in.");
pageToGo = "page/error.jsp";
}
} else {
this.setErrorMessage("User and/or Password are incorrect.");
pageToGo = "page/error.jsp";
}
return pageToGo;
}
private void setErrorMessage(String message) {
request.setAttribute("errorMessage", message);
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
JSP
<div class="alert alert-danger"> ${ requestScope.errorMessage } </div>
AJAX
function showUserHome() {
$.post( "${ sessionScope.ServletUrl }", $( "form#logForm" ).serialize() )
.done(function( html ) {
$( "div#toolbar" ).load("page/userToolbar.jsp");
$( "div#content" ).html( html );
})
.fail(function( html ) {
$( "#result" ).html( html );
});
}
Edit:
While trying to Debug it from the browser, it gets in the $.post and after that step, it jumps to the end of the function, skipping .done and .fail and the page remains the same. I'm not getting any error in the RAD Console or the Browser Console other than the SC_INTERNAL_SERVER_ERROR that I setted on the Action.
Calling setErrorPage method won't change your pageToGo local variable and thus always the same view is used. Change it to something like:
pageToGo = setErrorPage("That user is already logged in.");
(or even consider rename it to getErrorPage)
I have an old JSP application for which I cannot use Jquery or Ajax.
I have the following code snippet
function func(val){
if(val=="true"){
<%
myBean.myMethod("ABC","DET",0);
%>
myfrm.submit();
}
}
and I am calling this from a button's onClick event.
What I would like to do is invoke my Java method only when button is clicked. If page is refreshed java method should not be invoked.
How can I achieve this?
This is not possible. The java code is only executed when you refresh/load the page. Once the page is rendered, only client-side code can be executed.
You could have the button post to x.jsp and then do a redirect y.jsp
Looks like you have called your method within the jsp lifecycle.
As the jsp is parsed your method will be executed.
The functionallity you want you will most likely have to create an event.
<input type="hidden" value="" id="executeThis" onclick="document.forms[0].submit();"/>
<button id="doWork" type="button" onclick="execTheClick('executeThis', 'methodName');"/>
function execTheClick(linkId, methodName)
{
var fireOnThis = document.getElementById(linkId);
fireOnThis.value = methodName;
if (document.createEvent)
{
var evObj = document.createEvent('MouseEvents');
evObj.initEvent( 'click', true, false );
fireOnThis.dispatchEvent(evObj);
}
else if (document.createEventObject)
{
var evObj = document.createEventObject();
fireOnThis.fireEvent('onclick',evObj);
}
}
Hope that helps
I currently have the following:
cartServlet.java
public class CartServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
CartBean cartBean = new CartBean();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int counter = 0;
while (request.getParameterMap().containsKey("id" + counter)){
String songID = request.getParameter("id" + counter);
cartBean.setCartInfo(songID);
++counter;
}
request.setAttribute("cart", cartBean);
RequestDispatcher rd = request.getRequestDispatcher("/cart.jsp");
rd.forward(request, response);
}
cart.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Shopping Cart</title>
</head>
<body>
"${cart.cartInfo}"
</body>
</html>
cartBean.java
public class CartBean implements Serializable {
private static final long serialVersionUID = 1L;
private List<String> cart;
public CartBean(){
cart = new ArrayList<String>();
}
public void setCartInfo(String cartItem) {
this.cart.add(cartItem);
}
public List<String> getCartInfo() {
return cart;
}
}
When I print "${cart.cartInfo}", my output is coming out like this:
"[381d3af3-c113-46c1-b9d0-2c46cf445e22}, 3913ac54-0c03-4025-8279-5cfad2fcab5f}, 50ed6861-f6e2-479b-865c-cbbbc5c27efd}, eb9b29d6-d93e-4cd8-8d7a-7fe26ff6c05d}]"
Is this the correct way the output should be printed out? I don't know why the additional } is appearing at the end of each item..
Also, should I be defining CartBean cartBean = new CartBean(); in cartServlet.java? If a user were to come back to this shopping cart page and select more items, would the new items be placed in a different bean to the one I was originally using?
Thanks for your help.
Is this the correct way the output should be printed out? I don't know
why the additional } is appearing at the end of each item..
I'm guessing that yes, what's being listed on your JSP is what's supposed to be listed. Now it may differ from what you want, which is another matter. What appears to be currently listed is the ID for a song. In this XML file, I see one of the IDs listed as for "The Sweetest Taboo" by Sade in this homework file: http://www.cse.unsw.edu.au/~cs9321/14s1/assignments/musicDb.xml.
You need to use the useBean tag in your JSP. The syntax is as follows:
<jsp:useBean id = "idName" class = "packageName.SpecificClass" scope = "desiredScope" />
Fill in id, class, and scope with the desired values. The most common value for scope seems to be session.
Then set the property:
<jsp:setProperty name = "idName" property = "*" />
For more information about setProperty (along with useBean), see: jsp:setproperty what does property="*" mean?.
Also, should I be defining CartBean cartBean = new CartBean(); in
cartServlet.java?
It's usually best to use the servlet for the bean, especially if there's some processing that's going on, like filling in lists. Avoid putting a lot of Java code in your JSPs. The JSP should be able to grab a list of products and place them on the page, but it should not be able to instantiate the list, populate it, massage it into the form you need, and then place the products.
If a user were to come back to this shopping cart
page and select more items, would the new items be placed in a
different bean to the one I was originally using?
Read this page: http://www.jguru.com/faq/view.jsp?EID=53309.
You need to put the statement of creating CartBean inside doPost() method as a local variable, otherwise each request will create a new Thread and these threads share the instance variable which means the data in CartBean will be corrupted by different users.