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

Asked

Viewed 533 times

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 enter a filter into Servlet, I get the message:

java.lang.Classcastexception: java.lang.String cannot be cast to UTIL.Usuario

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

Follows 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

Login Servlet

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>
  • 1

    How are you setting the attribute name in the session? Probably the value is not an instance of Usuario, rather a string.

  • It’s coming as String from Loginservlet

  • Can include the LoginServlet who said?

  • I just inserted

  • Really, you’re setting like string and trying to recover as Usuario, I already include an answer for you

  • Thank you!!!! the/

Show 1 more comment

1 answer

2

As spoken in the comments, you are adding to the session an attribute called name with the guy String and then trying to get it back and doing cast for the guy Usuario.

One ClassCastException is launched 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 the type String. Now notice how you’re doing in FiltroSeguranca:

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

Opz, we have a problem. We said earlier that name was an instance of String And now we’re converting to a non-equivalent type. I don’t know how the rest of your application is, but a simple way to fix it is to change the above section 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 ....
  • Thanks for the help!!! I will test here and put the result!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.