I am creating a portlet for WebSphere portal 8 and would like to retrieve the page name where my portlet is rendered. This is important because depending on the page, the portlet will server content differently
I've tried to use the NavigationSelectionModel API but do not think I'm using it correctly. I want this code to happen before the view is rendered and I put the code in the doView method. The problem is that I cannot cast a ServletRequest/Response because I only have the RenderRequest and RenderResponse available in the doView method.
public void doView(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
// Declarations
List<ForeignAuthority> faList = new ArrayList<ForeignAuthority>();
String resp;
// Set the MIME type for the render response
response.setContentType(request.getResponseContentType());
// Check if portlet session exists
ForeignAuthoritiesPortletSessionBean sessionBean = getSessionBean(request);
if (sessionBean == null) {
response.getWriter().println("<b>NO PORTLET SESSION YET</b>");
return;
}
try{
Context ctx = new InitialContext();
NavigationSelectionModelHome home = (NavigationSelectionModelHome)
ctx.lookup("portal:service/model/NavigationSelectionModel");
if (home != null) {
NavigationSelectionModelProvider provider =
home.getNavigationSelectionModelProvider();
NavigationSelectionModel model =
provider.getNavigationSelectionModel((ServletRequest)request, (ServletResponse)response);
for (java.util.Iterator i = model.iterator(); i.hasNext(); )
{
NavigationNode node = (NavigationNode) i.next();
if (i.hasNext()) {
System.out.println(node.getObjectID().getUniqueName());
}
}
}
}catch(Exception e){
e.printStackTrace();
}
PortletRequestDispatcher rd = getPortletContext()
.getRequestDispatcher(getJspFilePath(request, VIEW_JSP));
rd.include(request, response);
}
The expected result would be to retrieve the page name or unique name of the current page that the portlet is rendered on.
You can try whether the below code snippet helps. You can get the URI value and extract the page name from it.
HttpServletRequest httpServletRequest = PortletUtils.getHttpServletRequest(renderRequest);
httpServletRequest.getRequestURI();
Related
I have a requirement where I need to get the page name from the request in the doView method and redirect it to page_name_SUFIX but I can't find a way to decode the WebSphere URL
When I request the view for 'pageName' I have to do something like this:
public void doView(RenderRequest req, RenderResponse res) {
String decodedURL = decodeURL(req); // This is the method that I need, decodedURL should be 'pageName'
(...)
}
I am working on WebSphere 8.0 and I've tried the following without results.
http://wpcertification.blogspot.com.ar/2010/05/getting-name-of-page-where-your-portlet.html (Here i've got the page title, but i don't know how to get the name)
WebSphere Portal decode url (I've decoded the URL but I can't find the page name in the XML)
There's some way to achieve this?
Thank you in advance!
So the question is of scope, from above it is unclear if you mean pageName as in the uniqueName of the page? If so once you have the objectid in a string or the actual object you can get the uniqueName from that object.
here is code to get the objectId of the current page
public ObjectID getCurrentPage(PortletRequest request,
PortletResponse response) throws StateException, NamingException,
IOException {
ObjectID oId = null;
try {
NavigationSelectionModelProvider provider = getNavigationSelectionModelProvider();
NavigationSelectionModel model = provider
.getNavigationSelectionModel(request, response);
NavigationNode node = (NavigationNode) model.getSelectedNode();
oId = node.getObjectID();
} catch (ModelException e) {
System.err.println("The current page could not be located = " + e);
}
return oId;
}
Now if your question is about a portlet parameter called pageName then it should be in the decoded url. is it the uniqueName you are looking for? that will not be in the xml but you can get that from the objectid object
you should be able to get the page id/uniqueName by using a doView method similar to this:
public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
// Set the MIME type for the render response
response.setContentType(request.getResponseContentType());
PortletServiceHome nsh = null;
javax.naming.Context ctx;
boolean serviceAvailable = false;
try {
ctx = new javax.naming.InitialContext();
nsh = (PortletServiceHome)ctx.lookup("portletservice/com.ibm.portal.portlet.service.model.NavigationSelectionModelProvider");
serviceAvailable = true;
} catch(NameNotFoundException nnfe) {
nnfe.printStackTrace();
} catch(NamingException ne) {
ne.printStackTrace();
}
// Check if portlet session exists
ShowPageLayoutPortletSessionBean sessionBean = getSessionBean(request);
if( sessionBean==null ) {
response.getWriter().println("<b>NO PORTLET SESSION YET</b>");
return;
} else if(!serviceAvailable) {
response.getWriter().println("<b>NO SERVICE AVAILABLE</b>");
return;
}
try {
NavigationSelectionModelProvider nsProvider = (NavigationSelectionModelProvider) nsh.getPortletService(NavigationSelectionModelProvider.class);
NavigationSelectionModel navmodel = nsProvider.getNavigationSelectionModel(request, response);
NavigationNode navNode = (NavigationNode)navmodel.getSelectedNode();
ContentPage contentPage = (ContentPage)navNode.getContentNode();
ObjectID pageId = contentPage.getObjectID();
// Invoke the JSP to render
PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher(getJspFilePath(request, VIEW_JSP));
rd.include(request,response);
} catch(Exception ex) {
ex.printStackTrace();
}
}
i'm new in liferay, and now i'm learning Liferay with liferaycookbook. I have a problem with send object from porlet to jsp page
here's my porlet,.In LibraryPortlet.java i have a function:
public void searchBooks(ActionRequest actionRequest,
ActionResponse actionResponse) throws IOException, PortletException {
String searchTerm = ParamUtil.getString(actionRequest, "searchTerm");
if (Validator.isNotNull(searchTerm)) {
try {
List<LMSBook> lmsBooks = LMSBookLocalServiceUtil
.searchBooks(searchTerm);
actionRequest.setAttribute("SEARCH_RESULT", lmsBooks);
actionRequest.setAttribute("test", "sentence to test");
actionResponse.setRenderParameter("jspPage",
LibraryConstants.PAGE_LIST);
} catch (SystemException e) {
e.printStackTrace();
}
}
}
in file list.jsp, i have
List<LMSBook> booksTemp = (List<LMSBook>) request
.getAttribute("SEARCH_RESULT");
List<LMSBook> books = Validator.isNotNull(booksTemp) ? ListUtil
.copy(booksTemp) : LMSBookLocalServiceUtil.getLMSBooks(0,
LMSBookLocalServiceUtil.getLMSBooksCount());
System.out.println("test: "+ request.getAttribute("test"));
in list.jsp, booksTemp is null because liferay can't send my object from LibraryPortlet.java to jsp, i try to send the string "sentence to test", but in console, it shows test: null
Anybody have had same problem, can you help me, please!
You must first use the correct request to set your attribute. The problem is that in the LibraryPortlet, you are using a type of PortletRequest and the object in the JSP is a HttpServletRequest.
For your case, in LibraryPortlet.java, do the following:
HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest);
request.setAttribute("SEARCH_RESULT", lmsBooks);
This also goes for any other attribute you are setting.
I have developed a custom tag library in Java which I use in my web application.
I am not sure why but my doTag() is not setting up cookie at all. I have cleared my cache and restarted my computer as well. Here is the code:
public class UserVersionOfSite extends EvenSimplerTagSupport {
private static final Log logger = LogFactory.getLog(UserVersionOfSite.class);
private StringWriter sw = new StringWriter();
#Override
public void doTag() throws IOException, JspException {
getJspBody().invoke(sw); //get the tag body and put it in StringWriter object
//get request object to get cookie value
PageContext ctx = (PageContext)getJspContext();
HttpServletRequest httpServletRequest = (HttpServletRequest) ctx.getRequest();
HttpServletResponse httpServletResponse = (HttpServletResponse) ctx.getResponse();
if(httpServletRequest.getParameterMap().containsKey("show_full_site")) {
logger.debug("show_full_site ");
if(!checkIfCookieExists(httpServletRequest)){
Cookie cookie = new Cookie("SHOW_FULL_SITE",httpServletRequest.getParameter("show_full_site"));
cookie.setMaxAge(86400);
httpServletResponse.addCookie(cookie);
//write the tag output
if(!httpServletRequest.getParameter("show_full_site").equalsIgnoreCase("true")){
//write the response
getJspContext().getOut().println(sw.toString());
}
}else{
String cookieValueString = getCookieValue(httpServletRequest.getCookies(),"SHOW_FULL_SITE","false");
if(!cookieValueString.equalsIgnoreCase("true")){
//write the response
getJspContext().getOut().println(sw.toString());
}
}
}
}
#Override
public String getResult() throws IOException {
return "User version of site";
}
public String getCookieValue(Cookie[] cookies,
String cookieName,
String defaultValue) {
for(int i=0; i<cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName()))
return(cookie.getValue());
}
return(defaultValue);
}
public boolean checkIfCookieExists(HttpServletRequest httpServletRequest){
logger.debug("inside checkIfCookieExists()");
boolean cookiePresent = Arrays.asList(httpServletRequest.getCookies()).contains( "SHOW_FULL_SITE" );
return cookiePresent;
}
}
Even I tried adding the code without using if else statements but still no success. Is there any thing critical I am missing?
Any ideas guys??!!! I have checked the browser's setting as well, but there is nothing there which is blocking a creation of cookie!
I realise the horse has probably bolted by the time I'm posting this but, for the benefit of others stumbling across it, I think the problem may be related to the feature of RequestDispatcher highlighted in this question: unable to add a cookie included in JSP via jsp:include
your following line inside checkIfCookieExists() method is wrong:
Arrays.asList(httpServletRequest.getCookies()).contains( "SHOW_FULL_SITE" );
HttpServletRequest.getCookies() returns Cookie[]. You are wrapping it inside a List and checking for a string "SHOW_FULL_SITE" inside this.
Coming back to your question- how do you know cookie is not being set in the HTTP headers? Try using browser plugins like firebug to see the HTTP response headers coming from server. Also set the path of cookie before adding it to response e.g.
Cookie cookie = new Cookie("SHOW_FULL_SITE",httpServletRequest.getParameter("show_full_site"));
cookie.setMaxAge(86400);
cookie.setPath("/");
I'm using jsp of out-of-box portlet like feed.jspf in Liferay 6:
String articleId =null;
HttpServletRequest httpReq = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(renderRequest));
articleId = httpReq.getParameter("articleId");
It is giving a null value whether in custom portlet or in .jsp files, but it should have a value.
Sure, you can always use the standard HttpServletRequest to retrieve your parameters from. You can get this request by using the PortalUtil class, like in the following example:
HttpServletRequest request = PortalUtil.getHttpServletRequest(portletRequest);
String articleId = request.getParameter("articleId");
In my Liferay- JSP I use this:
<!-- ... some imports... -->
<!-- ... some more imports... -->
<%# page import="com.liferay.portal.util.PortalUtil" %>
<portlet:defineObjects /> <!-- Liferay-specific, defines renderRequest etc.-->
<%
HttpServletRequest r = PortalUtil.getHttpServletRequest(renderRequest);
String wellHole = PortalUtil.getOriginalServletRequest(r).getParameter("well_hole");
%>
(this combines fragments of wisdom from other answers, notably Miguel Gil MartÃnez's answer from 2012 Jul 23 at 17:35
When working with portlets, each HttpServletRequest paramenter has a prefix which informs the "type" of the parameter and a suffix expressing which instance of the portlet should process it. So, the name of the parameters is not just "articleId". I do not know what portlet are you working but if it was a portlet called, let's say, "example" deployed through a war the parameter would be called example_WAR_exampleportletwar_articleId_w2Xd.
However, you do not have to deal with such complexity. If you are working within a JSP of some already created portlet, there should be an object called renderRequest which contains all parameters and abstracts all this name mangling. So, instead of retrieving the original servlet requestion you an use it:
String articleId = renderRequest.getParamenter("articleId");
If this object is not defined, you just need to insert the <portlet:defineObjects/> tag somewhere and after this the object will be available.
HTH. Let us know if it worked!
It worked for me:
public void doView(RenderRequest request, RenderResponse response) throws
PortletException, IOException {
HttpServletRequest requestInsideThePortlet = PortalUtil.getHttpServletRequest(request);
String myURLParam =
PortalUtil.getOriginalServletRequest(requestInsideThePortlet).getParameter("myURLParam");
....
....
....
}
For JSF I use this:
#ManagedBean
#RequestScoped
public class OriginalRequest {
private HttpServletRequest getOriginalRequest() {
return PortalUtil.getOriginalServletRequest(
PortalUtil.getHttpServletRequest(
(PortletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest() ) );
}
public String getParam( String name ) {
return getOriginalRequest().getParameter( name );
}
public List<String> getParamNames() {
return Collections.list( getOriginalRequest().getParameterNames() );
}
}
Then in your facelet:
#{originalRequest.getParam('my_param')}
I tried ur solutions but render request it gives me an exception,
so this is another solution:
public String obtainFromUrl(String keyFromWeb) {
Object outcome = null;
Map<String, Object> map = FacesContext.getCurrentInstance().getExternalContext().getRequestMap();
if (map != null) {
for (String key : map.keySet()) {
if (map.get(key) instanceof HttpServletRequestWrapper) {
HttpServletRequest request = (HttpServletRequest) ((HttpServletRequestWrapper) map.get(key))
.getRequest();
outcome = request.getParameter(keyFromWeb);
break;
}
}
}
return (String) outcome;
}
I'm trying to implement proper logout for my Java EE / JSF2 application.
It requires two things:
I need to logout from JAAS and invalidate the session
I then have to navigate to an external URL to fire Siteminder logout
The Siteminder logout URL (configured on the Policy server -> I cannot change it) is outside my applications context. Eg. if my webapp URL is https://localhost:8080/sm/MyWebApp then the logout URL is https://localhost:8080/anotherwebapp/logout.html.
This is the current local logout code:
public void logout() {
System.out.println("Logging out...");
HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
try {
request.logout();
} catch (ServletException e) {
e.printStackTrace();
}
HttpSession session = (HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(false);
if (session != null) {
session.invalidate();
}
}
And here is the property that produces the logout URL:
public String getLogoutUrl() {
HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
String requestServer = request.getServerName();
String requestScheme = request.getScheme();
int serverPort = request.getServerPort();
String logoutUrl = requestScheme + "://" + requestServer + ":" + Integer.toString(serverPort) + "/anotherwebapp/logout.html";
return logoutUrl;
}
However, I cannot find a JSF2 / Primefaces component that can call logout() then open the external URL. For example, if I have:
<h:outputLink value="#{authBean.logoutUrl}" onclick="#{authBean.logout()}">[Logout]</h:outputLink>
then onclick does not seem to be called.
Another way I tried was putting the external URL to the end of the logout function to have it returned as a navigation string but it is not recognized (also tried with "?faces-redirect=true"...).
Any help would be appreciated.
You can also just use ExternalContext#redirect().
public void logout() throws ServletException, IOException {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
((HttpServletRequest) ec.getRequest()).logout();
ec.invalidateSession();
ec.redirect("http://example.com/anothercontext/logout");
}
No need for an intermediating page with a meta refresh.
You can create a page logout.xhtml, so the code will look like this:
public String getLogoutUrl() {
return "/logout.jsf";
}
and in the page add:
<META HTTP-EQUIV="Refresh" CONTENT="0;URL=https://localhost:8080/anotherwebapp/logout.html">