web項目整合Shiro架構

來源:互聯網
上載者:User

標籤:返回   filter   管理器   inf   mapping   實現   manage   img   ***   

1、修改pom.xml檔案

  <dependency>      <groupId>org.apache.shiro</groupId>      <artifactId>shiro-core</artifactId>      <version>1.3.2</version>    </dependency>    <dependency>      <groupId>org.apache.shiro</groupId>      <artifactId>shiro-web</artifactId>      <version>1.3.2</version>    </dependency>

2、在web中使用shiro時必須配置監聽器,web.xml

  參考地址:http://shiro.apache.org/webapp-tutorial.html

  <listener>        <listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>    </listener>

3、在整個web開發中,使用者的登入檢測一定要有過濾器

  <filter>        <filter-name>ShiroFilter</filter-name>        <filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>        <!-- 指定設定檔的路徑 -->        <init-param>            <param-name>configpath</param-name>            <param-value>classpath:shiro.ini</param-value>        </init-param>    </filter>    <filter-mapping>        <filter-name>ShiroFilter</filter-name>        <url-pattern>/*</url-pattern>        <dispatcher>REQUEST</dispatcher>        <dispatcher>FORWARD</dispatcher>        <dispatcher>INCLUDE</dispatcher>        <dispatcher>ERROR</dispatcher>    </filter-mapping>

  此時web程式就與shiro整合好了

4、建立shiro.ini檔案

[main]
#定義本次要基於JDBC實現的Realm的認證的配置類jdbcRealm=com.wyl.realm.MyRealm#配置安全管理器所使用的RealmsecurityManager.realms=$jdbcRealm

5、建立MyRealm類,完成使用者驗證

package com.wyl.realm;import org.apache.shiro.authc.AuthenticationException;import org.apache.shiro.authc.AuthenticationInfo;import org.apache.shiro.authc.AuthenticationToken;import org.apache.shiro.authc.SimpleAuthenticationInfo;import org.apache.shiro.authc.UnknownAccountException;import org.apache.shiro.authz.AuthorizationInfo;import org.apache.shiro.authz.SimpleAuthorizationInfo;import org.apache.shiro.realm.AuthorizingRealm;import org.apache.shiro.subject.PrincipalCollection;import com.wyl.entity.Member;import com.wyl.service.MemberLoginService;/** * 自訂使用者認證 * @author wyl */public class MyRealm extends AuthorizingRealm{    @Override    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {                System.out.println("1、**************使用者登入驗證:doGetAuthenticationInfo***************");        // 1、登入認證的方法需要先執行,用來判斷登入的使用者資訊是否合法        String username = (String) token.getPrincipal();//取得使用者名稱        MemberLoginService service = new MemberLoginService();        //通過使用者名稱獲得使用者的完整資訊        Member vo = service.get(username);//取得使用者資訊        service.close();        if(vo == null){            throw new UnknownAccountException("該使用者名稱不存在!!!");        }else{ //進行密碼驗證處理            String password = new String((char[]) token.getCredentials());//取得登入密碼            //將資料庫密碼與登入密碼比較            if(!password.equals(vo.getPassword())){                throw new AuthenticationException("密碼錯誤!!!");            }else{                AuthenticationInfo auth = new SimpleAuthenticationInfo(username, password, "memberRealm");                 return auth;            }        }    }    @Override    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {        // TODO Auto-generated method stub        System.out.println("2、**************使用者角色與許可權:doGetAuthorizationInfo***************");        // 1、登入認證的方法需要先執行,用來判斷登入的使用者資訊是否合法        String username = (String) principals.getPrimaryPrincipal();//取得使用者名稱        SimpleAuthorizationInfo auth = new SimpleAuthorizationInfo();//定義授權資訊的返回資料        MemberLoginService service = new MemberLoginService();        auth.setRoles(service.listRolesByMember(username)); //設定角色資訊        auth.setStringPermissions(service.listJurisdictionsByMember(username)); //設定許可權資訊        service.close();        return auth;    }}

6、建立LoginServlet類

package com.wyl.servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.shiro.SecurityUtils;import org.apache.shiro.authc.UsernamePasswordToken;import org.apache.shiro.subject.Subject;@WebServlet("/shiroLogin")public class LoginServlet extends HttpServlet {    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        // TODO Auto-generated method stub        String mid = req.getParameter("mid");        String password = req.getParameter("password");        //擷取進行使用者名稱和密碼驗證的介面對象        Subject subject = SecurityUtils.getSubject();        //實現身份認證資訊儲存        UsernamePasswordToken token = new UsernamePasswordToken(mid,password);         subject.login(token);        req.setAttribute("mid", mid);        req.getRequestDispatcher("/pages/welcom.jsp").forward(req, resp);;    }        @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        // TODO Auto-generated method stub        this.doPost(req, resp);    }}

7、在根目錄下建立login.jsp檔案

<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><%    String path = request.getContextPath();    String basePath = request.getScheme()+"://"            +request.getServerName()+":"            +request.getServerPort()+path+"/";%><html><head><base href="<%=basePath%>"><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>shiro登入</title></head><body>    <form action="shiroLogin" method="post">    使用者名稱:<input type="text" name="mid" id="mid">    密碼:<input type="password" name="password" id="password">    <input type="submit" value="登入">    <input type="reset" value="重設">    </form></body></html>

8、建立/pages/welcom.jsp檔案

<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Insert title here</title></head><body>    <h1>welcom</h1></body></html>

9、結果顯示

 

 

web項目整合Shiro架構

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.