Attribute set in portlet session is not available in servlet session - java

Post on Liferay Forums: https://www.liferay.com/community/forums/-/message_boards/message/47412302
I have a simple application setup within a JSR-286 portlet to retrieve the value from a Portlet session.attribute
doView() method:
public void doView(RenderRequest renderRequest, RenderResponse renderResponse)
throws PortletException, IOException
{
renderResponse.setContentType("text/html");
getFormBean(renderRequest.getPortletSession());
PortletURL renderUrl = renderResponse.createRenderURL();
renderUrl.setWindowState(WindowState.MAXIMIZED);
PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher(this.viewUrl);
dispatcher.include(renderRequest, renderResponse);
}
I set my attribute here in
TestPortlet.java:
private void getFormBean(PortletSession session)
{
String testVar = (String)session.getAttribute("testAttr", 1);
if (null == testVar) {
System.out.println("Setting Attribute inside Portlet");
session.setAttribute("testAttr", "TESTING SESSION", 1);
}
}
And retrieve the attribute here in TestServlet.java (same package):
private void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String testVal = (String) request.getSession(true).getAttribute("testAttr");
System.out.println("Test Attribute from Servlet:"+testVal);
}
The output of the application returns null
Setting Attribute in Portlet
Test Attribute from Servlet:null
Output should be:
Test Attribute from Servlet:TESTING SESSION
This application does work on my local setup, however not on a remote server with almost the same configurations.
I've included the javax-servlet-api-3.1.0 in my tomcat/lib to retrieve the HttpServletRequest Class, haven't found what else could be missing. I also haven't seen any Exceptions/ClassNotFound Errors.
Could there be any kind of server configuration that could interfere with the Session? (Authentication, network config, security)
Local setup
Tomcat 7.0.33
jdk-1.7 (compiled with 1.6 and 1.7)
Remote setup
Tomcat 7.0.33
Apache Web Server
jdk-1.6.0u35
more jar files in /lib (jdbc drivers, etc)

If you want to share session data between portlet and servlet in the same application (war), you have to place the attribute in the application scope, like this:
portletSession.setAttribute("testAttr", "TESTING SESSION", PortletSession.APPLICATION_SCOPE);
and then also retrieve it in portlet using scope:
portletSession.getAttribute("testAttr", PortletSession.APPLICATION_SCOPE);

Related

WebSphere is not displaying webpage element when url contains string "?error "

I am working on a Spring security project where if User inserts wrong userId - password, webpage will update with "Invalid Login Attempt" message.
I am sending redirect on AuthenticationFailureHandler.onAuthenticationFailure
code snippet for onAuthenticationFailure() implementation.
#Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
//some logic
response.sendRedirect(String.format("%s?error", getUrl());
}
}
Resource Html page has div tag with thymeleaf dependency to identify error object and display message
<div th:if="${error}" id="loginFailedMessage" class="alert alert-danger">
Invalid login attempt.
</div>
So far this implementation works on Jboss application server and WebLogic application server - however when not for websphere. Is there a reason why WebSphere is blocking such url invocation - any configuration am I missing. I have tired different version of WebSphere 8.5.5.9 up to 8.5.5.13
ps. there are no errors in any logs ffdc or application logs.
Solution will be to use error=true in url. for some reason websphere does not allow url parameter without assigning values.
#Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
//some logic
response.sendRedirect(String.format("%s?error=true", getUrl());
}
}

How do I enforce Https Connection in Ibm Bluemix using Tomcat Server with Default java Build Pack?

I have a Spring Mvc Application using hibernate hosted on ibm bluemix with domain registered in go daddy using tomcat server using the java_buildpack provided by blue mix for tomcat.Currently I have bought a ssl certificate in go daddy registered in blue mix.My application now works both on http and https.But now i have a requirement to enforce only https connection to my application .I implemented Spring Security .I have used Security config to enforce https and used below code for https redirection .
requiresChannel().anyRequest().requiresSecure()
but it gives me the following error in browser
Too many redirects occurred trying to open “https://website-name”. This might occur if you open a page that is redirected to open another page which then is redirected to open the original page.
Now I have followed few links over network inorder to enforce https where they told me to add few parameters I added these parameters in blue mix runtime environmental variables of my application.
server.tomcat.internal-proxies:.*
I also tried adding
server.tomcat.remote_ip_header:x-forwarded-for
server.tomcat.protocol_header:x-forwarded-proto
the flow of application is first go daddy lookup then it goes to the blue mix application how can i have only https enabled
But Still I get The Same error.
Guys can you help me solve this problem.
I added the custom filter
#Component
public class CustomFilter implements Filter {
private static final Logger logger = Logger.getLogger(CartController.class);
#Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
#Override
public void doFilter(ServletRequest request1, ServletResponse response1, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) request1;
HttpServletResponse response = (HttpServletResponse) response1;
if (!request.isSecure()) {
logger.info("Not secure");
// generate full URL to https
StringBuilder newUrl = new StringBuilder("https://");
newUrl.append(request.getServerName());
if (request.getRequestURI() != null) {
newUrl.append(request.getRequestURI());
}
if (request.getQueryString() != null) {
newUrl.append("?").append(request.getQueryString());
}
response.sendRedirect(newUrl.toString());
} else {
// already a secure connection, no redirect to https required.
logger.info("Else");
if (chain != null) {
logger.info("Chain Null");
chain.doFilter(request, response);
}
}
}
}
I would advise two options:
1. In the past I have manually implemented a filter that if a non-http request is received to redirect to https. I have not used spring security in the manner you're attempting.
2. Post a question to Rob Winch, spring security lead, on the spring forms and cross link to this question so that people on the Bluemix platform can see his response.
My initial thought is that the manual filter is the way to go but would really like to know if Rob and team have encountered this on the CF platform.

Save to session when the application starts

How can I save to the session a variable at the very start of the application?
The below code isn't executed when I fist run the application..
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
session.setAttribute("flag", true);
//etc...
}
That code wont be executed at server startup, because there is no request and therefore no session at this time. This method belongs to a servlet, which is invoked once some client hits the url mapped to it.
If you need to do something at application startup use a ServletContextListener. If you have to store some variable for "global" use in your webapp use the ServletContext. If you really have to store it to the session use an HttpSessionListener.

List servlets in a java webapp (running in tomcat)

I am trying to re-package a relatively big java webapp which I did not code and for which the project configuration was lost.
I setup a first packaging, and deployed it in tomcat. Now to understand it, I'd like to get a list of the servlets that started successfully or failed, with corresponding access url.
Is there a way to get that list (from some startup log maybe)?
Some details: the webapp uses gwt (which I don't master), I use tomcat7 on ubuntu. I am not against a solution using another servlet container, if practical.
I would write a simple JSP or ServletContextListener to read all the ServletRegistratioins from the servlet context and display them.
So your JSP/ServletContextListener would read the data from
servletContext.getServletRegistrations();
and just display it.
Edit
#WebServlet(urlPatterns = "/mappings")
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = -7256602549310759826L;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
PrintWriter writer = resp.getWriter();
Map<String, ? extends ServletRegistration> registrations = req
.getServletContext().getServletRegistrations();
for (String key : registrations.keySet()) {
ServletRegistration registration = registrations.get(key);
writer.write("Name: " + registration.getName());
writer.write("<br>Mappings:");
for (String mapping : registration.getMappings()) {
writer.write(mapping);
}
}
// of course you can write that to log or console also depending on your
// requirement.
}
}
You can see started modules and paths in Tomcat by double click at Tomcat and see Modules tab.

Change Tomcat Webapp directory from code

I have a Webapp running on Tomcat. This app has an entry Servlet which receives a certain parameter. It looks like this:
https://localhost:8443/myapp/entryservlet?param=app1
This parameter param indicates which webapp should be loaded.
In my Webapp directory I have a structure like this:
-WebApp
-- App1
-- App2
-- App3
...
Depending on the parameter, I have to tell Tomcat which webapp should be loaded
Obviously, you're not passing in the entire URL as a parameter, but here's a sample redirecting to another url. You can also look at forwarding.
public class EntryServlet extends HttpServlet {
public final void doGet(HttpServletRequest request, HttpServletResponse response
) throws ServletException, IOException {
String forwardURL = request.getParameter("param");
response.sendRedirect( forwardURL );
}
}

Categories