How to get the session id in FTL - freemarker

I want the current session id in the ftl page.
I tried many things with the Session (HttpSessionHashModel) available but not able to get the id?
Getting a request header also do my job.
Is there any way to get any of these item in my FTL?

you can put the parameter in your FTL file with java servlet.
I think your project work like this:
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
try
{
Map dataModel = new HashMap();
dataModel.put("session_id", req.getSession().getId());
Configuration cfg = new Configuration();
Template tmpl = cfg.getTemplate("test.ftl");
tmpl.process(dataModel, resp.getWriter());
}
catch (TemplateException ex) {
throw new IOException(ex);
}
}
file test.ftl as
<html>
<head></head>
<body>
<p> ${session_id!""} </p>
</body>
</html>

FreeMarker doesn't expose anything by default. It doesn't even know what servlets are. So it depends on the web application framework your are using. (Unless, you are using freemarker.ext.servlet.FreeMarkerServlet.) Or, you can put these into the data-model directly.

Related

Including a JSP into a sling servlet

I'm currently working on a small project, trying to help someone figure out how to wire up a component.
Ideally we'd like to do 2 things:
have a jsp that renders the template
have all our business login in a SlingAllMethodServlet
Gist of servlet definition:
package definition...
import statements...
#SuppressWarnings("serial")
#SlingServlet(
resourceTypes="path/to/my/component",
methods="GET",
extentions="HTML")
#Properties({
#Property(name="service.pid", value="<my service class>", propertyPrivate=false),
#Property(name="service.description",value="<description>", propertyPrivate=false),
#Property(name="service.vendor",value="<company>", propertyPrivate=false)
})
public class MyComponentServlet extends SlingAllMethodsServlet {
#Override
protected void doGet (SlingHttpServletRequest pRequest, SlingHttpServletResponse pResponse) throws ServletException, IOException {
...
}
#Override
protected void doPost(SlingHttpServletRequest pRequest, SlingHttpServletResponse pResponse) throws ServletException, IOException {
...
}
}
This actually works great, when I include the component on a page this runs. The problem (as you might expect) is that I'm consuming the HTML extension here. So "component.jsp" isn't getting picked up for render.
I'm curious if someone knows how to do one of the following:
Include the JSP for render in this servlet (i.e. i saw some interesting stuff on 6dimensions regarding pageContext#include and pageContext#pushBody: http://labs.sixdimensions.com/blog/2013-08-13/cq-resource-inclusion-servlet/)
Set up this servlet, so that this servlet runs at that path before the JSP is rendered.
Any insight would be great.
thank you,
brodie
Including scripts
Use following construction to include script /apps/test.jsp inside the servlet and pass some values (bindings) to it:
#Reference
private ServletResolver servletResolver;
public void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
Servlet servlet = servletResolver.resolveServlet(request.getResource(), "/apps/test.jsp");
request.setAttribute("sampleBinding", "bindingValue");
servlet.service(request, response);
}
The script itself may look like this:
<%#page session="false" contentType="text/html; charset=utf-8"
%><%#include file="/libs/foundation/global.jsp"%>
Binding value: ${sampleBinding}
Using models
You may also consider a second approach - don't create servlet for each component, but stick to JSP and at the beginning of each script create a model object. Sample script:
<%#page session="false" contentType="text/html; charset=utf-8"
%><%#include file="/libs/foundation/global.jsp"%><%
pageContext.setAttribute("model", new MyModel(slingRequest, slingResponse));
%>
Value from model: ${model.value}
And sample model:
public class MyModel {
private final SlingHttpServletRequest request;
private final SlingHttpServletResponse response;
public MyModel(SlingHttpServletRequest request, SlingHttpServletResponse response) {
this.request = request;
this.response = response;
}
public String getValue() {
// you may use request & response objects here
return "sample value";
}
}
If you like this approach, you may use a framework that makes writing such models easier. Two interesting solutions are:
Sling models
Slice
Also have a look at the BindingsValueProvider.
https://sling.apache.org/apidocs/sling6/org/apache/sling/scripting/api/BindingsValuesProvider.html

Receiving files form PLUpload in WICKET

Im trying to integrate PLUpload into my wicket application. First steps are looking clear. Im able to choose files and when i click the "upload"-button i receive an request on server-side in my PLUploadBehavior based on AbstractDefaultAjaxBehavior. But it does not seems to be a MultiPart request.
public abstract class PLUploadBehavior extends AbstractDefaultAjaxBehavior {
public PLUploadBehavior() {
}
#Override
public void renderHead(final Component component, IHeaderResponse response) {
super.renderHead(component, response);
response.render(JavaScriptHeaderItem.forReference(new JavaScriptResourceReference(PLUploadBehavior.class, "plupload.full.min.js"));
StringBuffer script = new StringBuffer();
//build the init-script...
response.render(OnLoadHeaderItem.forScript(script.toString()));
}
#Override
protected void respond(AjaxRequestTarget target) {
Request request = getComponent().getRequest();
//received request here, but don't know hot to access files
if (request instanceof IMultipartWebRequest) {
System.out.println("Multipart!!!");
}
}
}
I followed the tutorial for plupload and have no form in my html template. There is none in the tutorial, so i think i don't need it. Anyone an idea to access the files on server-side?
After some more coffee i found the solution to my problem. The example on wicket in action can get adapted to the use with an Behavior. Thanks to Martin Grigorov and the great Wicket Team!

Redirect to a JSP page after login using AJAX

I have a login.jsp page where users type in username and password. Username and password are sent to the server using ajax ($.post). When the authentication is complete, I want to redirect user to an index.jsp page.
js:
function Login()
{
var traderName = document.getElementById('username').value;
var traderPass = document.getElementById('password').value;
//SetLoginLoading();
data = {action:'login',username:traderName,password:traderPass};
$.post('TraderServlet',$.param(data),function(response){
});
return false;
}
Servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
....
login(request, response);
....
}
private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
String name = request.getParameter(PARAMETER_NAME);
String pass = request.getParameter(PARAMETER_PASS);
traderBean.login(name, pass);
response.sendRedirect("index.jsp");
}
I tried to use response.sendRedirect() but it does not work. Should I use jQuery to redirect user using ajaxCallback ?
Thank you.
In general, if you are just going to redirect anyway, there is really no point in using AJAX as you can accomplish this by just having the servlet handle directly from the form.
To your question, first check the url pattern of your servlet. Make sure it is actually being called. If so, then if it has a url pattern like
/TraderServlet
Then it expects index.jsp to be also in the root folder under Web. It could be that you are simply not redirecting to where you are expecting to go.
One way to check is (if you're in Chrome) use the debugger tools (F12 on Windows/Nix, Ctrl-Shift-I on Macs), and see what error it is giving.

Flash attributes in Spring MVC 3.1 not visible to redirected JSP

I am using Spring 3.1's new Flash Attribute support to set flash attributes on a RedirectAttributes object in a Controller and then invoking a redirect. That redirect request is in turn caught by a filter which then sends it on its merry way to the JSP that it's intended for. The problem: I can't see the flash attributes either from within the filter's doFilter() method or from the JSP. Non-flash (URL) attributes make it just fine.
Controller that does the redirect:
#RequestMapping("/pages/login")
public String login (HttpServletRequest request, Map<String, Object> model, RedirectAttributes redirectAttributes) {
model.put("userId", "batman");
String redirectUrl = request.getParameter("redirectUrl");
if (redirectUrl != null) {
redirectAttributes.addAttribute("attr1","ababab");
redirectAttributes.addFlashAttribute("flashAttr1", "flashflash");
for (Iterator<String> iterator = model.keySet().iterator(); iterator.hasNext();) {
String key = iterator.next();
redirectAttributes.addFlashAttribute(key, model.get(key));
}
return "redirect:"+redirectUrl;
} else {
return "pages/login";
}
}
The filter which picks up the redirect doesn't do anything interesting in this case:
public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
//if (httpRequest.getSession().getAttribute("userId") == null) {
//...do some stuff here which invokes controller above as well as the redirect
//} else {
chain.doFilter(request, response);
//}
}
The page that gets redirected to following the filter:
...
<title>Test Web App 1</title>
</head>
<body>
<p>Flash attribute: <c:out value="${flashAttr1}"/></p>
<p>Welcome <c:out value="${userId}"/>!</p>
</body>
</html>
Neither flashAttr1 nor userId end up being populated in the page. The attr1 non-flash attribute the controller set does appear in the URL params of the page, so that seems to work.
Here is some output from log4j after I set springfamework.web to DEBUG:
19:15:44,406 DEBUG http-8080-1 view.ContentNegotiatingViewResolver:494 - Returni
ng redirect view [org.springframework.web.servlet.view.RedirectView: name 'redir
ect:http://my_hostname:8080/test-webapp-1/protected/protected_page.jsp';
URL [http://my_hostname:8080/test-webapp-1/protected/protected_page.jsp]]
19:15:44,406 DEBUG http-8080-1 servlet.DispatcherServlet:1155 -
Rendering view [org.springframework.web.servlet.view.RedirectView: name
'redirect:http://my_hostname:8080/test-webapp-1/protected/protected_page.jsp';
URL [http://my_hostname:8080/test-webapp-1/protected/protected_page.jsp]] in
DispatcherServlet with name 'dispatcher'
19:15:44,421 DEBUG http-8080-1 support.DefaultFlashMapManager:199 - Saving Flash
Map=[Attributes={userId=batman, flashAttr1=flashflash}, targetRequestPath=/test-
webapp-1/protected/protected_page.jsp, targetRequestParams={attr1=[ababab]}]
19:15:44,421 DEBUG http-8080-1 servlet.DispatcherServlet:913 - Successfully comp
leted request
Following a brief stop at the filter I've shown above, I am taken to the page with URL
http://my_hostname:8080/test-webapp-1/protected/protected_page.jsp?attr1=ababab
But neither of the attributes I expect that JSP to find are displayed. I have also debugged through the doFilter() method shown above and failed to find the flash attributes in the request's session.
I'm not sure exactly what's wrong at this point. Everything works as expected except for those flash attributes. If there is anything else I should provide to make the situation more clear, I will be happy to.
Ran into this issue a few months ago with AJAX-related redirects. If you use a read-only HTTP POST pattern, you can specify a #ResponseStatus to simulate a POST. Also be sure to have your method return a View or ModelAndView (as opposed to String) so that Spring knows to look up the Flash scope for the given #RequestMapping.
Pseudocode:
#RequestMapping(...)
#ResponseStatus(OK)
public ModelAndView login (...) {
...
}

Struts2 and servlet integration

i am getting data from action class to servlet by adding data to session.whenever i am clicking the item in select list onchange event is fired that function is invoked the our servlet up to now OK,whenever we send second time request that servlet is not called why? and also comparsion is failed it will maintain previous values only.here i am sending request from ajax.pls can any one provide solution ?
AjaX code
function verify_details()
{
var resourceId=document.getElementById("res").value
var url="/EIS10/ResourceTest?resourceId="+resourceId;
ajax(url);
}
Action class Code:
listResource=taskService.getUserList(taskId);
System.out.println("The list Of Resources are::"+listResource);
HttpSession session=request.getSession();
session.setAttribute("listResource", listResource);
ServletCode
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
System.out.println("Servlet is Called...........");
String resourceId=request.getParameter("resourceId");
boolean t=false;
System.out.println("Your Clicked Id::"+resourceId);
HttpSession session=request.getSession();
List l=(List)session.getAttribute("listResource");
System.out.println("Resource List in Servlet:"+l);
if(l!=null)
{
System.out.println("The Size of List::"+l.size());
Iterator itr=l.iterator();
while(itr.hasNext())
{
String s=itr.next().toString();
System.out.println("Elements in List:"+s);
if(s.equals(resourceId))
t=true;
}
response.setContentType("text/html");
if (t) {
response.getWriter().write("Y");
} else {
response.getWriter().write("N");
}
}
}
}
It's probably because the browser returns the contents from its cache at the second request. See http://spacebug.com/solving_browser_caching_problem_of_ajax-html/ for a solution, or use an AJAX library (jQuery for example) which can handle this for you.
Besides, if you're using Struts, why do you use a bare servlet to handle your AJAX call? Why don't you use a Struts action?

Resources