使用java servlet实现基于角色的登录

时间:2018-06-19 05:17:45

标签: java servlets

如何实现基于此的登录角色。我已经在其中实现了一些代码,但无济于事。在实施我从互联网上引用的代码之后,代码就会被破坏,或者当我从我的数据库输入凭据时,有时它的jsut会让我重定向到错误页面。

这是我的servlet

public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

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

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

        try
        {

            GetSet gsup = new GetSet();                     

            gsup.setUname(request.getParameter("uname")); 
            gsup.setPword(request.getParameter("pword"));  



            gsup = myDAO.login(gsup);                       
            if (gsup.isValid())
            {

                post.print("Welcome" + gsup);
                HttpSession mysession = request.getSession(true);
                mysession.setAttribute("thiscurrentuser", gsup);
                mysession.setMaxInactiveInterval(10);                                       
                response.sendRedirect("loggedin.jsp");                                      


            }

            else
            {

                response.sendRedirect("thisinvaliduser.jsp");                                       

            }

        }

        catch (Throwable e){

            System.out.println(e);

        doGet(request, response);
    }

}
}

这是我的DAO

public class myDAO {

    public static GetSet login (GetSet bean) {

        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs =null;

        String uname = bean.getUname();
        String pword = bean.getPword();

        String searchQuery = "select *from csusers where username=? AND password=?"; 



        System.out.println("Your username is: " + uname);               
        System.out.println("Your password is: " + pword);               


    try {

        con = konekMoko.getCon();                               
        ps = con.prepareStatement(searchQuery);                 


        ps.setString(1, uname);                             
        ps.setString(2, pword);                                 

        rs = ps.executeQuery();                                 


        boolean tochek =rs.next();

        if (!tochek)                                                
        {

            System.out.println("Username does not exists!");
            bean.setisValid(false);

        }

        else if (tochek)                                            
        {

            System.out.println("Welcome " + uname);
            bean.setUname(uname);
            bean.setPword(pword);
            bean.setisValid(true);

        }
        rs.close();
        ps.close();
        con.close();

    }

    catch (Exception e) {


    }
    return bean;

    }


}

这是我的getter和setter

package thisPackage;

public class GetSet {



    private String uname;
    private String pword;
    public boolean ifvalid;



    public String getUname () {

        return uname;

    }

    public void setUname (String myuname) {


        this.uname=myuname;
    }

    public String getPword () {

        return pword;

    }


    public void setPword (String mypword) {


    this.pword=mypword;
    }


    public boolean isValid() {


        return ifvalid;
    }

    public void setisValid (boolean validity)
    {

        this.ifvalid=validity;

    }

}

2 个答案:

答案 0 :(得分:0)

请阅读此参考文献:
Google
Tomcat Realm
太容易在应用程序服务器上实现JDBC领域并使用:

httpServletRequest.login(username,password) ;

或者:

httpServletRequest.logout() ;

答案 1 :(得分:0)

在我看来,你可以使用tomcat的内置DataSourceRealm。从我在你的问题中看到的,你没有任何表来存储角色,但是你可以使用一个视图:

CREATE VIEW user_roles(username,role) AS SELECT username, 'user' FROM csusers;

您可以在文件<tomcat-home>/conf/server.xml中声明数据源:

...
<GlobalNamingResources>
    ...
    <Resource auth="Container"
            type="javax.sql.DataSource"
            name="mydatasource"
            driverClassName="com.mysql.jdbc.Driver"
            url="jdbc:mysql://localhost/mydb"
            maxActive="10"
            maxIdle="5"
            validationQuery="SELECT 1"
            testOnBorrow="true"
            testWhileIdle="true"
            timeBetweenEvictionRunsMillis="10000"
            minEvictableIdleTimeMillis="60000"
            username="the-user"
            password="the-password"/>
</GlobalNamingResources>
...

然后在您的webapp的context.xml中声明数据源链接和领域:

<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/myapp">
    <ResourceLink global="mydatasource" name="mydatasource"
            type="javax.sql.DataSource"/>
    <Realm className="org.apache.catalina.realm.DataSourceRealm"
            dataSourceName="mydatasource"
            debug="99"
            localDataSource="true"
            userTable="csusers"
            userNameCol="username"
            userCredCol="password"
            userRoleTable="user_roles"
            roleNameCol="role"/>
</Context>