"java.lang.String can not be cast to ..." using access control in Servlet

4

I have a system made for my company and together I have the new website. I can log into the system normally with the accounts registered in the database, but when I insert a filter in the servlet, I get the message:

  

java.lang.ClassCastException: java.lang.String can not be cast to UTIL.Username

If you delete the filter, the system works normally. The filter I am using is to prevent system pages from being accessed via url, so it is always redirected to login.jsp .

Follow the code.

FiltroSeguranca.java

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;

public class FiltroSeguranca implements Filter {

    public void init(FilterConfig config) throws ServletException {

    }

    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {

        HttpSession session = ((HttpServletRequest) req).getSession();

        Usuario usuario = (Usuario) session.getAttribute("name");

        if (usuario == null) {

            session.setAttribute("msg", "Você não está logado no sistema!");

            ((HttpServletResponse) res).sendRedirect("login.jsp");

        } else {

            chain.doFilter(req, res);

        }

    }

    public void destroy() {

    }

}

web.xml :

<servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>UTIL.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>  
    <welcome-file>index.jsp</welcome-file>  
</welcome-file-list>
<filter>
    <filter-name>Filtro Seguranca</filter-name>
    <filter-class>UTIL.FiltroSeguranca</filter-class>
</filter>

<filter-mapping>
    <filter-name>Filtro Seguranca</filter-name>
    <url-pattern>/GrantedAccess.jsp</url-pattern>
    <url-pattern>/Cadastro.jsp</url-pattern>
</filter-mapping>

UPDATED

Servlet login

public class LoginServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        String n = request.getParameter("username");
        String p = request.getParameter("userpass");

        HttpSession session = request.getSession(false);
        if (session != null) {
            session.setAttribute("name", n);
        }

        if (LoginDao.validate(n, p)) {
            RequestDispatcher rd = request.getRequestDispatcher("GrantedAccess.jsp");
            rd.forward(request, response);
        } else {
            out.print("<p style=\"color:red\">Sorry username or password error</p>");
            RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
            rd.include(request, response);
        }

        out.close();
    }

}

LOGIN FORM

<div id="conteudo" class="animated fadeIn">
    <div id="raside">
        <div class="animated flash">
            <h1>

                <form action="LoginServlet" method="post">
                    LOGIN  <input autofocus type="text" name="username" required>
                    SENHA  <input type="password" name="userpass" required>
                    <input type="submit" value="AUTENTICAR">
                </form>

            </h1>
        </div>
    </div>
</div>
    
asked by anonymous 11.10.2015 / 00:32

1 answer

2

As mentioned in the comments, you are adding an attribute named name to the session with type String and then trying to retrieve it and cast cast to type Usuario .

A ClassCastException is thrown whenever you try to convert an object to another type of which it is not an instance.

See this excerpt from LoginServlet :

// recupera como String
String n = request.getParameter("username");
String p = request.getParameter("userpass");

HttpSession session = request.getSession(false);
if (session != null) {
    // configura "name" na sessão como String
    session.setAttribute("name", n);
}

As in the comments, you are always working with type String . Now notice how you are doing in FiltroSeguranca :

Usuario usuario = (Usuario) session.getAttribute("name");

Opz, we have a problem. We previously said that name was an instance of String and now we are converting to an equivalent type. I do not know how the rest of your application is, but a simple way to fix it is to change the excerpt above by this:

String userName = (String) session.getAttribute("name");

// assumindo que tenha um construtor que receba uma string =D
Usuario usuario = new Usuario(userName);

// continua seu código ....
    
11.10.2015 / 01:50