#WebFilter(filterName = "loginFilter", value = { "/faces/kosz.xhtml" } , dispatcherTypes = { DispatcherType.FORWARD, DispatcherType.ERROR, DispatcherType.REQUEST, DispatcherType.INCLUDE } )
public class loginFilter implements Filter {
public loginFilter(){
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException{
HttpServletRequest req = ( HttpServletRequest ) request;
userSession auth = ( userSession ) req.getSession().getAttribute("user");
if ( auth != null && auth.isLogged() ) {
chain.doFilter(request, response);
HttpServletResponse res = ( HttpServletResponse ) response;
res.sendRedirect(req.getContextPath() + "/login.xhtml");
}
else {
HttpServletResponse res = ( HttpServletResponse ) response;
res.sendRedirect(req.getContextPath() + "/login.xhtml");
}
}
#Override
public void init(FilterConfig filterConfig) throws ServletException
{
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public void destroy()
{
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* Return the filter configuration object for this filter.
}
The problem is that the filter doesn't execute. THe URL is localhost:8080/PP2/faces/kosz.xhtml . What would be the proper way to do this?
I have no entry in my web.xml, it's all based on Annotations.
You throw exceptions in init() and destroy() methods of filter. If you don't want to do anything in init() or destroy(), just leave body of method empty. In this case your filter is not successfully initialized at all.
Related
I have a ThreadLocale in which i am setting some value which i want to read while creating the mongo document..
#Service
public class DocumentContext {
private ThreadLocal<String> currentValue = new ThreadLocal<>();
public void setName(String documentName) {
currentValue.set(documentName);
}
public String getName() {
return currentValue.get();
}
}
I am using this to set the value in my filter:
#Autowired
private DocumentContext docContext;
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
final HttpServletRequest httpRequest = (HttpServletRequest) request;
final String col= "value1";
docContext.setCurrentValue(col);
chain.doFilter(request, response);
docContext.setCurrentValue(null);
}
Now i have my POJO class in which i am using like this:
#Data
#Document(collection="doc.#{docContext.getName()}.tableName")
class Entity{
}
But, in the mongo i am getting the collection name as :
doc..tablename
I was expecting :
doc.value1.tablename
Please suggest am i missing something.
Is there a way to log the requests coming for static files (like index.html or js files) in JHipster.
Add a filter:
public class RequestLoggingFilter implements Filter {
private static final Logger log = Logger.getLogger(AuditFilter.class);
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String requestUrl = httpRequest.getRequestURI();
String requestMethod = httpRequest.getMethod();
log.info("Received " + requestMethod + " request + " for " + requestUrl);
chain.doFilter(request, response);
}
#Override
public void destroy() {
}
}
while logout i did removed session object and invalidated session also as like below
public String logout() throws IOException {
logger.info("logout() : satarted----- ");
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
ec.getSessionMap().remove("visitorComponent");
System.out.println("*************_->"+ec.getSessionMap().remove("visitorComponent"));
ec.invalidateSession();
ec.redirect(ec.getRequestContextPath() + "/logout.xhtml");
return null;
// return "logout?faces-redirect=true";
}
But still in filter class its giving values, filter class code like below
public class AuthorizationFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession();
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader("Cache-Control", "no-cache,no-store,must-revalidate"); // HTTP 1.1
httpResponse.setHeader("Pragma", "no-cache"); // HTTP 1.0
httpResponse.setDateHeader("Expires", 0);
if (session.getAttribute("visitorComponent") != null) {
System.out.println("-sdf>"+((VisitorComponent) session.getAttribute("visitorComponent")).getAdmin());
}
System.out.println("->"+session.getAttribute("visitorComponent"));
System.out.println("=url>"+req.getRequestURI());
System.out.println("=>"+req.getRequestURI().endsWith("login.xhtml"));
if (session.getAttribute("visitorComponent") != null || req.getRequestURI().endsWith("index.xhtml")) {
chain.doFilter(request, httpResponse);
} else {
System.out.println("---in else--");
// HttpServletResponse res = (HttpServletResponse) response;
httpResponse.sendRedirect("index.xhtml");
return;
}
}
Could you please help any one, what I need to do?
Finally I found solution but side effects are there.
My solution is, previously I was not kept login object manually because my login class in session scope. If i do in this way its not clear the object after invalidate also because while starting application login class instantiated.
#ManagedBean(name = "visitorComponent")
#SessionScoped
public class VisitorComponent {
Admin admin = new Admin();
public String login() {
// some code to verify login details
this.admin = adminService.getAdminObject(adminId);
}
Now i did manually by get session object map and put my login object in session map.
#ManagedBean(name = "visitorComponent")
#SessionScoped
public class VisitorComponent {
Admin admin = new Admin();
public String login() {
// some code to verify login details
this.admin = adminService.getAdminObject(adminId);
// Session object creating to get the session values
ExternalContext externalContext = FacesContext.getCurrentInstance()
.getExternalContext();
Map<String, Object> sessionMap = externalContext.getSessionMap();
sessionMap.put("abcadminBean", this.admin);
}
Now its working fine by invalidate but problem is in my login page
i have
I have doubt in my filterclass, that is like below
public class AuthorizationFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession();
if (session.getAttribute("abcadminBean") != null || req.getRequestURI().endsWith("index.xhtml")) {
chain.doFilter(request, response);
} else {
FacesContext fc = FacesContext.getCurrentInstance();
if (fc == null) {
// Create new Lifecycle.
LifecycleFactory lifecycleFactory = (LifecycleFactory)
FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
Lifecycle lifecycle = lifecycleFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
// Create new FacesContext.
FacesContextFactory contextFactory = (FacesContextFactory)
FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
fc = contextFactory.getFacesContext(
((HttpServletRequest) request).getSession().getServletContext(), request, response, lifecycle);
}
System.out.println("fc->"+fc);
ExternalContext ec = fc.getExternalContext();
ec.redirect(ec.getRequestContextPath() + "/index.xhtml");
// HttpServletResponse res = (HttpServletResponse) response;
// ((HttpServletResponse) response).sendRedirect("index.xhtml");
return;
}
}
Here I am redirecting my page, I thought it is the problem
Could you please any one help me, What i need to do for my UI changes ?
Finally I caught solution.
Why because it is not loading all primefaces UI effects is,
For every request our filter is checking so in Filter class we have to write condition to allow our CSS and JS file as like below
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession();
if (session.getAttribute("loginDetails") != null
|| session.getAttribute("empLoginDetails") != null
|| req.getRequestURI().endsWith("index.xhtml")
|| req.getRequestURI().endsWith("forgetpass.xhtml")
|| req.getRequestURI().endsWith("empLogin.xhtml")
|| req.getRequestURI().endsWith("logout.xhtml")
|| req.getRequestURI().endsWith("ajax-loader.gif.xhtml")
|| req.getRequestURI().contains(".js")
|| req.getRequestURI().contains(".css")) {
chain.doFilter(request, response);
} else {
FacesContext fc = FacesContext.getCurrentInstance();
if (fc == null) {
// Create new Lifecycle.
LifecycleFactory lifecycleFactory = (LifecycleFactory) FactoryFinder
.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
Lifecycle lifecycle = lifecycleFactory
.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
// Create new FacesContext.
FacesContextFactory contextFactory = (FacesContextFactory) FactoryFinder
.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
fc = contextFactory.getFacesContext(
((HttpServletRequest) request).getSession()
.getServletContext(), request, response,
lifecycle);
}
RequestDispatcher dispatcher = request
.getRequestDispatcher("/index.xhtml");
dispatcher.forward(request, response);
return;
}
Now my application is working fine with filter class
I've tried to make autorisation form by using jsf 1.2 but I had some exceptions with redirect.
Bean code
public class UserAutorisationBean implements Serializable {
private Boolean isLogin = false;
private String login = "";
private String password = "";
public void autoriseLoginAndPass() throws IOException {
if (this.login == "user" && this.password == "password") {
this.isLogin = true;
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response =
(HttpServletResponse) context.getExternalContext().getResponse();
response.sendRedirect("web/HelloWorld.jsp");
} else {
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response =
(HttpServletResponse) context.getExternalContext().getResponse();
response.sendRedirect("web/Error.jsp");
}
}
Filter code
public class Filter implements javax.servlet.Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
HttpSession session = null;
session = httpRequest.getSession(false);
if (session != null) {
UserAutorisationBean userAutorisationBean = null;
userAutorisationBean =
(UserAutorisationBean) session.getAttribute("userautorisationbean");
if (userAutorisationBean != null) {
if (!userAutorisationBean.isLoginIn()) {
httpResponse.sendRedirect(httpRequest.getContextPath() + "/Error.jsp");
}
}
chain.doFilter(request, response);
}
if (session == null) {
httpResponse.sendRedirect(httpRequest.getContextPath() + "/Error.jsp");
}
}
public void destroy() {
}
}
Stack:
message Cannot forward after response has been committed
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Cannot forward after response has been committed
javax.faces.webapp.FacesServlet.service(FacesServlet.java:256)
root cause
java.lang.IllegalStateException: Cannot forward after response has been committed
com.sun.faces.context.ExternalContextImpl.dispatch(ExternalContextImpl.java:414)
com.sun.faces.application.ViewHandlerImpl.executePageToBuildView(ViewHandlerImpl.java:455)
com.sun.faces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:139)
com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:108)
com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:266)
com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:159)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:245)
I've tried to find some advices by using search but it didn't help me to solve the problem.
As I have an Apache Webserver which does ProxyPass to the Glassfish server, the latter does not know that the customers are talking "https".
Thus when using things like
return "shop.xhtml?faces-redirect=true";
the generated HTTP Location: header contains a "http://" URL.
I've read JSF redirects from HTTPS to HTTP but found this solution not very elegant. Is there a way to tell Glassfish that this or all incoming requests are https so that I don't have to fiddle with the generated Navigation rules?
You may try to add some request header which can be interpreted on java side, for example 'X-redirect-to-https'. Then create filter that will wrap HttpServletResponse, and in that wrapper override sendRedirect method to replace http with https in redirect URL when 'X-redirect-to-https' header is present.
Code (a little messy, but illustrates a solution) adapted from:
http://javahunter.wordpress.com/2011/06/01/why-does-https-become-http-on-a-sendredirect/
#WebFilter("/*")
public class HttpsSendRedirectFilter implements Filter {
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void destroy() {
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
chain.doFilter(request, new HttpsRedirectResponseWrapper((HttpServletRequest) request,
(HttpServletResponse) response));
}
}
public class HttpsRedirectResponseWrapper extends HttpServletResponseWrapper {
private HttpServletRequest req;
private String prefix = null;
public HttpsRedirectResponseWrapper(HttpServletRequest req, HttpServletResponse res) {
super(res);
this.req = req;
prefix = getPrefix(req);
}
#Override
public void sendRedirect(String location) throws IOException {
String finalurl = null;
if (isUrlAbsolute(location)) {
finalurl = location;
} else {
finalurl = fixForScheme(prefix + location);
}
super.sendRedirect(finalurl);
}
public boolean isUrlAbsolute(String url) {
String lowercaseurl = url.toLowerCase();
if (lowercaseurl.startsWith("http") == true) {
return true;
} else {
return false;
}
}
public String fixForScheme(String url) {
if (this.req.getHeader("X-redirect-to-https") != null) {
return url.replaceFirst("http", "https");
} else {
return url;
}
}
public String getPrefix(HttpServletRequest request) {
StringBuffer str = request.getRequestURL();
String url = str.toString();
String uri = request.getRequestURI();
int offset = url.indexOf(uri);
String prefix_t = url.substring(0, offset);
return prefix_t;
}
}