I am doing a university work, i need to do a simple login system that reject direct URL access to some pages if there is no login, i tried to use a filter, but when i load any page, the filter is called at least 20 times, and then is called more times, if i let it be, in 30 seconds is called 80 times because it wants, i need help please, here is my code.
The filter
package edu.eci.pdsw.misc;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import edu.eci.pdsw.view.LoginBean;
public class LoginFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
// Get the loginBean from session attribute
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(String.valueOf(LoginBean.mas()));
boolean loggedIn = (session != null) && (session.getAttribute("user") != null);
if (!loggedIn) {
String contextPath = ((HttpServletRequest)request).getContextPath();
((HttpServletResponse)response).sendRedirect(contextPath + "/Inicio.xhtml");
}
chain.doFilter(request,response);
}
public void init(FilterConfig config) throws ServletException {}
public void destroy() {}
}
the web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>omega</param-value>
</context-param>
<!-- Login filter -->
<filter>
<filter-name>LoginFilter</filter-name>
<filter-class>edu.eci.pdsw.misc.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>*.xhtml</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/Inicio.xhtml</welcome-file>
</welcome-file-list>
<listener>
<listener-class>edu.eci.pdsw.guice.GuiceContextListener</listener-class>
</listener>
</web-app>
if anything else is needed please tell i will put it here, thank you for the help
Related
I am trying to get the parameters names in a Servlet Context object from context param elements in an order given in the web.xml file. But on running code on the server, displayed parameter order is not the same as to mention in the web.xml file.
DemoServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DemoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
ServletContext context=getServletContext();
//we are getting all the initialization parameter from the web.xml file
Enumeration<String> e=context.getInitParameterNames();
while(e.hasMoreElements()) {
String s=e.nextElement();
pw.println("<br>"+context.getInitParameter(s));
}
pw.close();
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>Servlet6ServletContextInterface2</display-name>
<servlet>
<servlet-name>demo</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<context-param>
<param-name>DriverName</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</context-param>
<context-param>
<param-name>Username</param-name>
<param-value>Pranay Singh</param-value>
</context-param>
<context-param>
<param-name>Password</param-name>
<param-value>abc123</param-value>
</context-param>
<servlet-mapping>
<servlet-name>demo</servlet-name>
<url-pattern>/context</url-pattern>
</servlet-mapping>
</web-app>
Expected Results:
com.mysql.jdbc.Driver Pranay Singh abc123
Actual Results:
Pranay Singh com.mysql.jdbc.Driver abc123
The params are intended to be accessed by their name, so the orders are not guaranteed.
If you really need them in a specific order, you can hard-code the param names (in your own order) into a collection:
List<String> paramNames = Arrays.asList("DriverName", "Username", "Password");
for(String paramName: paramNames) {
pw.println("<br>" + context.getInitParameter(paramName));
}
Or if you want to keep the params dynamic without hard-coding anything, you can at least sort them.
Enumeration<String> e = context.getInitParameterNames();
List<String> paramNames = Collections.list(e);
Collections.sort(paramNames);
for(String paramName: paramNames) {
pw.println("<br>" + context.getInitParameter(paramName));
}
I am getting an error in web.xml file while adding context parameters to it.
Here is web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<context-param>
<pram-name>ADMIN_PATH</param-name>
<param-value>AdminChatServlet</param-value>
</context-param>
<context-param>
<param-name>ROOMLIST_PATH</param-name>
<param-value>/RoomListServlet</param-value>
</context-param>
<context-param>
<param-name>CHROOM_PATH</param-name>
<param-value>/ChRoomServlet</param-value>
</context-param>
<servlet>
<servlet-name>MainChatServlet</servlet-name>
<servlet-class>MainChatServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>AdminChatServlet</servlet-name>
<servlet-class>AdminChatServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>RoomListServlet</servlet-name>
<servlet-class>RoomListServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>ChRoomServlet</servlet-name>
<servlet-class>ChRoomServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MainChatServlet</servlet-name>
<url-pattern>/MainChatServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>AdminChatServlet</servlet-name>
<url-pattern>/AdminChatServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>RoomListServlet</servlet-name>
<url-pattern>/RoomListServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ChRoomServlet</servlet-name>
<url-pattern>/ChRoomServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
and here is the servlet(MainChatServlet) using those context-parameters:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.*;
import com.amir.*;
public class MainChatServlet extends HttpServlet {
String chRoomPath;//="ChRoomServlet.java";
String roomListPath;//="RoomListServlet.java";
String adminChatPath;//="AdminChatServlet.java";
public void init()
{
ServletContext context = getServletConfig().getServletContext();
context.setAttribute("chRoomPath",context.getInitParameter("CHROOM_PATH"));
context.setAttribute("roomListPath",context.getInitParameter("ROOMLIST_PATH"));
context.setAttribute("adminChatPath",context.getInitParameter("ADMINCHAT_PATH"));
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session = request.getSession();
chRoomPath = (String)getServletContext().getAttribute("chRoomPath");
roomListPath = (String)getServletContext().getAttribute("roomListpath");
adminChatPath = (String)getServletContext().getAttribute("adminChatPath");
session.setAttribute("chRoomPath",chRoomPath);
session.setAttribute("roomListPath", roomListPath);
session.setAttribute("adminChatPath",adminChatPath);
HashMap hashmap = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/chat","root","mysql");
synchronized(getServletContext())
{
hashmap = (HashMap)getServletContext().getAttribute("chatList");
if(hashmap == null)
{
hashmap =new HashMap();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from chatrooms");
while(rs.next())
{
hashmap.put(rs.getString(1),new ChatRoom(rs.getString(1),rs.getString(2),4));
}
rs.close();
getServletContext().setAttribute("roomList", hashmap);
}
}
conn.close();
}
catch(ClassNotFoundException e)
{
System.out.print("Error(Class)");
e.printStackTrace();
}
catch(SQLException e)
{
System.out.print("Error(SQL)");
e.printStackTrace();
}
RequestDispatcher view = request.getRequestDispatcher("chat.jsp");
view.forward(request, response);
}
}
and here is the default-package in which all the .java files(servlets are kept)
Screenshot#1
Why am I getting the error in the web.xml file?
Screenshot#2
EDIT: OR Suggest me any alternate idea if possible.
I have a Simple Web Service returning JSON data.
The User Class (com.bargadss.SpringService.Domain) is The POJO class containing
user_ID, firstName, lastName, eMail
The UserService class (com.bargadss.SpringService.DAO) two major operation
getAllUser() -> Queries the DB to Select all Users from User Table and returns List{User}
getUserById(int user_ID) -> Queries the DB to Select a specific user based on ID
The SpringServiceController (com.bargadss.SpringService.Controller) is as follows :
package com.bargadss.SpringService.Controller;
import java.util.List;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.bargadss.SpringService.DAO.UserService;
import com.bargadss.SpringService.Domain.User;
#RestController
#RequestMapping("/service/user/")
public class SpringServiceController {
UserService userService=new UserService();
#RequestMapping(value = "/{id}", method = RequestMethod.GET,headers="Accept=application/json")
public User getUser(#PathVariable int id) {
User user=userService.getUserById(id);
return user;
}
#RequestMapping(method = RequestMethod.GET,headers="Accept=application/json")
public List<User> getAllUsers() {
List<User> users=userService.getAllUsers();
return users;
}
}
The ListUserController (com.bargadss.SpringService.Controller) is as follows :
package com.bargadss.SpringService.Controller;
import java.util.LinkedHashMap;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;
import com.bargadss.SpringService.Domain.User;
#Controller
public class ListUserController {
#RequestMapping("/listUsers")
public ModelAndView listUsers() {
RestTemplate restTemplate = new RestTemplate();
String url="http://localhost:8080/SpringServiceWithRESTAndJSONExample/service/user/";
List<LinkedHashMap> users=restTemplate.getForObject(url, List.class);
return new ModelAndView("listUsers", "users", users);
}
#RequestMapping("/dispUser/{userid}")
public ModelAndView dispUser(#PathVariable("userid") int userid) {
RestTemplate restTemplate = new RestTemplate();
String url="http://localhost:8080/SpringServiceWithRESTAndJSONExample/service/user/{userid}";
User user=restTemplate.getForObject(url, User.class,userid);
return new ModelAndView("dispUser", "user", user);
}
}
The CorsFilter (com.bargadss.CORS) is as follows :
package com.bargadss.CORS;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;
public class CorsFilter extends OncePerRequestFilter{
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
// CORS "pre-flight" request
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
response.addHeader("Access-Control-Allow-Headers", "Content-Type");
response.addHeader("Access-Control-Max-Age", "1800");//30 min
}
filterChain.doFilter(request, response);
}
}
The web.xml is as follows :
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>SpringServiceWithRESTAndJSONExample</display-name>
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>jsp</servlet-name>
<servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>jsp</servlet-name>
<url-pattern>/WEB-INF/jsp/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>cors</filter-name>
<filter-class>com.bargadss.CORS.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
The Web Service when being invoked by AngularJS from another Web Server returns Error referring to Cross Origin Resource Sharing problem !!!
What Changes must be performed in the Controller side to eliminate the error ?
Is there any changes necessary to be done at the AngularJS side to avoid this situation ?
Check the cors-filter
Download cors-filter-2.1.2.jar and java-property-utils-1.9.1.jar.
mvn dependency
<dependency>
<groupId>com.thetransactioncompany</groupId>
<artifactId>cors-filter</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>com.thetransactioncompany</groupId>
<artifactId>java-property-utils</artifactId>
<version>1.9.1</version>
</dependency>
and in web.xml
<filter>
<filter-name>CORS</filter-name>
<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
This is my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<filter>
<display-name>MyFilter</display-name>
<filter-name>MyFilter</filter-name>
<filter-class>AB_DB.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/MyFilter</url-pattern>
</filter-mapping>
<servlet>
<description></description>
<display-name>Profile</display-name>
<servlet-name>Profile</servlet-name>
<servlet-class>AB_DB.Profile</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Profile</servlet-name>
<url-pattern>/Profile</url-pattern>
</servlet-mapping>
</web-app>
This is the filter servlet I've tried
package AB_DB;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class MyFilter implements Filter {
public MyFilter() {
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
String requri = ((HttpServletRequest) request).getRequestURI().substring(((HttpServletRequest) request).getContextPath().length() + 1);
System.out.println(requri);
//if request uri starts with user/ then system will forward the request to Profile servlet
if (requri.startsWith("user/")) {
//get userid from request uri
String id = requri.substring(5);
System.out.println(id);
//set attribute "user" with userid value
request.setAttribute("user", id);
//forward the request to Profile servlet
request.getRequestDispatcher("/Profile")
.forward(request, response);
} else {
chain.doFilter(request, response);
}
}
public void init(FilterConfig fConfig) throws ServletException {
}
}
However in the GlassFish 4 server log, there is no errors at all when running the project. The URI isnt even being printed out with 'System.out.println(id);' so I assume that the filter isnt even being injected.
Can anyone see any issues with my code? The sevlet Profile isn't being ran
You have mapped oyur filter to /MyFilter
<url-pattern>/MyFilter</url-pattern>
and that doesn't match with URL you are requesting
/user/Surname1993
so your filter won't get invoked
I have three primefaces (version 4.0) webpages. One of them is a login.xhtml which I want to use to authenticate a user before they are allowed to access either of the other two webpages. I am using Tomcat server (v7.0)
My problem is that I can access the login.xhtml from my base url: http://localhost:8080/controlservice-server/ --> which does the correct user authentication and then passes through onto the correct webpage.
However, I am able to access the other two webpages directly from their urls without having to go through the login page and therefore anyone can access them.
My web.xml:
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<welcome-file-list>
<welcome-file>Login.xhtml</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
My Authentication Web Filter:
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
#WebFilter(filterName = "PrimefacesAuthFilter", urlPatterns={"*.Login.xhtml"})
public class PrimesfacesAuthFilter implements Filter {
public PrimesfacesAuthFilter() {
}
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
HttpSession ses = req.getSession(false);
String reqURI = req.getRequestURI();
if (reqURI.indexOf("/*.xhtml") >= 0 || (ses != null && ses.getAttribute("username") != null)
|| reqURI.indexOf("/public/") >= 0 || reqURI.contains("javax.faces.resource")) {
chain.doFilter(request, response);
}
else
res.sendRedirect(req.getContextPath() + "/login.xhtml");
} catch (Throwable t) {
System.out.println(t.getMessage());
}
}
#Override
public void destroy() {
}
}
You should change urlPatterns attribute in your #WebFilter annotation as below:
#WebFilter(filterName = "PrimefacesAuthFilter", urlPatterns={"*.xhtml"})