Shiro授权-SSM

shiro与SSM整合之授权和注解式开发 文章目录1、shiro授权角色、权限权限表设计图:ShiroUserMapper:ShiroUserMapper.xml:MyRealm:2、Shiro的注解式开发常用注解介绍:ShiroUserController:在springmvc-servlet.xml添加:jsp中添加:测试: 1、shiro授权角色、权限 权限表设计图: ShiroUserMapper: Set<String&... 阅读详情

数据库的表的权限设计图设计
在这里插入图片描述

我们需要根据用户id获取他的角色id(role)和权限(pers),所以需要在ShiroUserMapper写两个查询的方法。

ShiroUserMapper

/**
     * 查询角色id
     * @param userid
     * @return
     */
    Set<String> getRolesByUserId(@Param("userid") Integer userid);

    /**
     * 查询权限id
     * @param userid
     * @return
     */
    Set<String> getPersByUserId(@Param("userid") Integer userid);


ShiroUserMapper.xml

<select id="getRolesByUserId" resultType="java.lang.String" parameterType="java.lang.Integer">
  select r.roleid from t_shiro_user u,t_shiro_user_role ur,t_shiro_role r
    where u.userid = ur.userid and ur.roleid = r.roleid
    and u.userid = #{userid}
</select>
<select id="getPersByUserId" resultType="java.lang.String" parameterType="java.lang.Integer">
  select p.permission from t_shiro_user u,t_shiro_user_role ur,t_shiro_role_permission rp,t_shiro_permission p
  where u.userid = ur.userid and ur.roleid = rp.roleid and rp.perid = p.perid
  and u.userid = #{userid}
</select>

ShiroUserService

package com.pyx.service;

import com.pyx.model.ShiroUser;
import org.apache.ibatis.annotations.Param;

import java.util.Set;

public interface ShiroUserService {
    ShiroUser queryByName( String uname);

    int insert(ShiroUser record);

    Set<String> getRolesByUserId(Integer userid);

    Set<String> getPersByUserId(Integer userid);
}

MyRealm

package com.pyx.shiro;

import com.pyx.model.ShiroUser;
import com.pyx.service.ShiroUserService;
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.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

public class MyRealm extends AuthorizingRealm {
    private ShiroUserService shiroUserService;

    public ShiroUserService getShiroUserService() {
        return shiroUserService;
    }

    public void setShiroUserService(ShiroUserService shiroUserService) {
        this.shiroUserService = shiroUserService;
    }

    /**
     * 授权的方法
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String uname=principalCollection.getPrimaryPrincipal().toString();
        ShiroUser shiroUser = this.shiroUserService.queryByName(uname);
        Set<String> persByUserId = this.shiroUserService.getPersByUserId(shiroUser.getUserid());
        Set<String> rolesByUserId = this.shiroUserService.getRolesByUserId(shiroUser.getUserid());
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.setRoles(rolesByUserId);
        info.setStringPermissions(persByUserId);
        return info;
    }

    /**
     * 身份认证的方法
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String uname=authenticationToken.getPrincipal().toString();
        String pwd=authenticationToken.getCredentials().toString();
        ShiroUser shiroUser=shiroUserService.queryByName(uname);

        AuthenticationInfo info=new SimpleAuthenticationInfo(
            shiroUser.getUsername(),
                shiroUser.getPassword(),
                ByteSource.Util.bytes(shiroUser.getSalt()),
                this.getName()
        );
        return info;
    }
}


常用注解

@RequiresAuthenthentication:表示当前Subject已经通过login进行身份验证;即
Subject.isAuthenticated()返回 true
@RequiresUser:表示当前Subject已经身份验证或者通过记住我登录的
@RequiresGuest:表示当前Subject没有身份验证或者通过记住我登录过,即是游客身份
@RequiresRoles(value = {“admin”,“user”},logical =
Logical.AND):表示当前Subject需要角色admin和user @RequiresPermissions(value =
{“user:delete”,“user:b”},logical =
Logical.OR):表示当前Subject需要权限user:delete或者user:b

Springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 通过context:component-scan元素扫描指定包下的控制器-->
    <!--1) 扫描com.javaxl.zf及子子孙孙包下的控制器(扫描范围过大,耗时)-->
    <aop:aspectj-autoproxy/>
    <context:component-scan base-package="com.pyx"/>

    <!--2) 此标签默认注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter -->
    <!--两个bean,这两个bean是spring MVC为@Controllers分发请求所必须的。并提供了数据绑定支持,-->
    <!--@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson)-->
    <mvc:annotation-driven></mvc:annotation-driven>

    <!--3) ViewResolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- viewClass需要在pom中引入两个包:standard.jar and jstl.jar -->
        <property name="viewClass"
                  value="org.springframework.web.servlet.view.JstlView"></property>
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 -->
        <property name="defaultEncoding" value="UTF-8"></property>
        <!-- 文件最大大小(字节) 1024*1024*50=50M-->
        <property name="maxUploadSize" value="52428800"></property>
        <!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常-->
        <property name="resolveLazily" value="true"/>
    </bean>

    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
          depends-on="lifecycleBeanPostProcessor">
        <property name="proxyTargetClass" value="true"></property>
    </bean>
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"/>
    </bean>

    <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="org.apache.shiro.authz.UnauthorizedException">
                    unauthorized
                </prop>
            </props>
        </property>
        <property name="defaultErrorView" value="unauthorized"/>
    </bean>

    <!--4) 单独处理图片、样式、js等资源 -->
    <!--<mvc:resources location="/css/" mapping="/css/**"/>-->
    <!--<mvc:resources location="/images/" mapping="/images/**"/>-->
    <!--<mvc:resources location="/js/" mapping="/js/**"/>-->
    <mvc:resources location="/static/" mapping="/static/**"/>
</beans>

ShiroUserController

package com.pyx.controller;

import com.pyx.model.ShiroUser;
import com.pyx.service.ShiroUserService;
import com.pyx.util.PasswordHelper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class ShiroUserController {
    @Autowired
    private ShiroUserService shiroUserService;

    @RequestMapping("login")
    public String login(HttpServletRequest req){
        Subject subject = SecurityUtils.getSubject();
        String uname = req.getParameter("username");
        String pwd = req.getParameter("password");
        UsernamePasswordToken token = new UsernamePasswordToken(uname,pwd);

        try {
//            这里会跳转到MyRealm中的认证方法
            subject.login(token);
            req.getSession().setAttribute("username",uname);
            return "main";
        }catch (Exception e){
            req.setAttribute("message","用户名密码错误");
            return "login";
        }
    }

    @RequestMapping("logout")
    public String logout(HttpServletRequest req){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login.jsp";
    }


    @RequestMapping("/register")
    public String register(HttpServletRequest req, HttpServletResponse resp){
        String uname = req.getParameter("username");
        String pwd = req.getParameter("password");
        String salt = PasswordHelper.createSalt();
        String credentials = PasswordHelper.createCredentials(pwd, salt);

        ShiroUser shiroUser=new ShiroUser();
        shiroUser.setUsername(uname);
        shiroUser.setPassword(credentials);
        shiroUser.setSalt(salt);
        int insert = shiroUserService.insert(shiroUser);
        if(insert>0){
            req.setAttribute("message","注册成功");
            return "login";
        }
        else{
            req.setAttribute("message","注册失败");
            return "register";
        }
    }

    @RequiresUser
    @ResponseBody
    @RequestMapping("passUser")
    public String passUser(){
        return "用户认证访问成功!!!";
    }
    @RequiresRoles(value = {"2"} ,logical = Logical.AND)
    @ResponseBody
    @RequestMapping("passRole")
    public String passRole(){
        return "角色访问成功!!!";
    }
    @RequiresPermissions(value = {"user:update","user:load"},logical = Logical.AND)
    @ResponseBody
    @RequestMapping("passPer")
    public String passPer(){
        return "权限访问成功!!!";
    }


}

Shiro教程7(整合SSM项目-授权) 授权原理分析 首先授权必须是在认证通过之后才会执行的操作 之前我们在Shiro教程4(授权操作)该教程中讲过,获取权限我们是通过如下方法实现的 那么在自定义Realm中授权是怎么实现的呢? 我们跟踪代码来看 首先从 hasRole()方法来看。 到此我们发现要对用户授权的话,我们只需要在定义Realm的doGetAuthorizationInfo方法中来授权。 授权具体实现 授权 /**... 阅读详情

相关推荐

基于osgEarth的二维态势中时变对象的绘制方法

在态势系统中,卫星、飞机的轨迹、覆盖等的几何数据随时间改变,称之为时变对象。在以OSGEarth实现的二维态势中,如果利用OSGEarth的预定义线、面类型处理这种几何数据的动态改变,则导致效率极具降低。介绍了此问题并给出解决技巧。

eyepeak的博客 2090

Shiro授权

1、shiro授权角色、权限 2、Shiro的注解式开发 授权 <select id="getRolesByUserId" resultType="java.lang.String" parameterType="java.lang.Integer"> select r.roleid from t_shiro_user u,t_shiro_user_role ur,t_shir...

qq_44982547的博客 226

DDR4技术原理详解

DDR4是DDR4-SDRAM的简写,即第4代DDR-SDRAM,DDR-SDRAM全称Double Date Rate Synchronous Dynamic Random Access Memory。本文重点解析DDR4技术规范及其背后的电子电路原理,以及编程使用DDR4过程中需要注意的性能事项。

ctbinzi的专栏 1万+

shiro 不完全学习笔记-----------1

一.shiro 简介                   shiro是apache的一个开源的安全框架,大体功能:认证,授权,企业会话管理,安全加密,缓存管理                   shiro和springScurity的比较                            简单                                               复杂 ...

小张同学的博客 305

基于Vivado2025的UltraScale+时序收敛优化实战案例

深入解析在Vivado2025环境中针对UltraScale+架构的时序收敛挑战,结合实际设计案例,分享关键优化策略与操作技巧,显著提升设计性能与收敛效率。vivado2025的更新特性为时序优化带来新机遇。

weixin_33660045的博客 343

西威SIEI变频器与电梯主板及驱动板原理图解析与详解(共二十九页原厂PDF图纸)

通过本文的分析,可以了解到西威变频器的技术特点、维修需求以及相关的图纸获取途径。在今后的工作中,维修人员需要充分了解设备的电路图和原理图,掌握正确的维修技术和方法,确保设备的正常运行和延长使用寿命。对于维修人员来说,获取准确的变频器图纸是进行维修工作的基础。这些图纸包含了变频器的电路图、原理图以及相关的元件布局等信息,是维修人员了解设备工作原理、确定维修步骤的重要依据。西威变频器是一种高效、可靠的电机控制设备,广泛应用于电梯、空调、风机等领域的电机控制中。目前,西威提供的维修图纸主要以PDF格式为主。

lXSqtACEzg的博客 1112

SpringMVC+Shiro权限管理

博文目录 权限的简单描述实例表结构及内容及POJOShiro-pom.xmlShiro-web.xmlShiro-MyShiro-权限认证,登录认证层Shiro-applicationContext-shiro.xmlHomeController三个JSP文件  什么是权限呢?举个简单的例子: 我有一个论坛,注册的用户分为normal用户,manager用户。 对论坛的帖子的操

LzwGlory的专栏 2613

eLabRadio软件无线电虚实结合仿真开发平台简介

在使用仿真平台时,不要关闭设备或断开设备与PC机之间的网络连接,否则,仿真平台将无法正常工作。注:采用eNodeX设备认证方式,当出现“设备不存在”的报错时,请检查计算机IP是否和硬件设备IP处于同一网段,或者是否是先连接好网线,再开启硬件设备的。①此登录方式下,需要先建立软件与硬件的通信:在登录窗口点击【网络配置】,参照下图输入设备IP,服务器地址无需设置,设置完成后点击确认,此时登录界面无需设置账号密码;,拷贝到电脑上,使用管理员权限运行setup.exe,下一步直到安装完成,桌面会生成快捷方式。

weixin_55349105的博客 6319

实战-Shiro安全框架(二)权限控制

  上一篇讲解了shiro的认证流程以及实现。这一篇,笔者要详细讲解shiro的另一重要部分就是权限控制,简称授权。   授权流程跟认证流程很相似,大致过程为当前用户subject调用isPermitted*/hasRole* 接口时,将会委派给security manager,security manager委派给Authorizer(授权器)。比如调用的是isPermitted("user:...

啊杰的博客 824

高性能优化的本质

在很早之前,处理器性能的提升一般是通过减小元器件的尺寸,增加元器件的数量,提高主频来实现,这也是摩尔定律所说的,但是由于功耗的影响,主频不能一直增加。后来,由于英伟达的GPU的并行计算的出现,逐渐打破摩尔定律,人们利用多核,SIMD,SIMT来处理大量相同计算的数据,这极大的提高了效率。计算机的算力得到了巨大的提升,但是并行是困难的,对于有数据依赖的程序来说,处理并行是一件及其困难的事,但对于一些简单的数学库的计算,并行的实现相对简单。

发狂的小花的博客 273

【模型之美】3、文本聚类与智能摘要,让AI帮你做个总结

在信息过载时代,文本聚类与摘要技术成为关键工具。本文提出了一种结合OpenAI Embedding与传统机器学习的方法,实现从文本预处理到智能分析的完整流程。技术方案分为三阶段:1)通过Embedding将文本转化为语义向量;2)采用K-Means等算法进行无监督聚类;3)利用大模型生成可解释的标签和摘要。实验证明,该方法能有效提升信息处理效率,如在新闻聚合系统中自动分类10,000篇文章,准确率较传统方法提高15%。方案包含实用代码示例,涵盖文本清洗、向量化、聚类优化等关键技术细节,可应用于对话记忆、舆情

2025博客之星Top81。专注AI工程化与架构实战。从分布式思维到模型部署,用工程化视角为你厘清AI落地的真实路径。 1439

权限管理:shiro

图一: shiro整体架构功能 图二: shiro架构API实现方式 @DependsOn(value="springUtils") @Configuration public class ShiroCoreConfig { @Autowired private RedisProperties redisParam; public static final String...

weixin_38289303的博客 258

励磁电感 Lm 选对了,LLC 才真“高效”:半桥 LLC 效率优化

你有没有遇到过这种 LLC:参数一套下来,ZVS 也有了,波形看着也“挺谐振”,但一上功率——,效率就是死活上不去。我说句直白的:LLC 的“高效”,很大一部分其实是在背后控场。Lm 选小了,励磁电流蹭蹭涨,谐振电流 RMS 变大,导通损耗、开关损耗、整流损耗一起上天;Lm 选太大,又可能把 ZVS 的门槛抬高,轻载掉 ZVS,EMI 也开始作妖。

weixin_43199439的博客 434

Shiro授权之SSM

1.添加角色和权限的授权方法 //根据username查询该用户的所有角色,用于角色验证 Set<String> findRoles(String username); //根据username查询他所拥有的权限信息,用于权限判断 Set<String> findPermissions(String username); 编写方法 1.根据username获取用户对应的角色 2.根据username获取用户对应的角色权限 实现方法 ...

m0_67596612的博客 658

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

shiro授权SSM

shiro授权SSM 授权 1.添加角色和权限的授权方法 //根据username查询该用户的所有角色,用于角色验证 Set findRoles(String username); //根据username查询他所拥有的权限信息,用于权限判断 Set findPermissions(String username); 在ShiroUserMapper.xml中新增内容: <select id...

hao_dream_xi的博客 321

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

shiro授权-SSM

1.添加角色和权限的授权方法 //根据username查询该用户的所有角色,用于角色验证 Set<String> findRoles(String username); //根据username查询他所拥有的权限信息,用于权限判断 Set<String> findPermissions(String username); 2.自定义Realm配置Shiro授权认证 1) 获取验证身份(用户名) 2) 根据身份(用户名)获取角色和权限信息 3) ...

m0_67476502的博客 160

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

SSM整合Shiro-授权案例

SSM整合Shiro-授权案例 接着上一篇登录案例,今天写一篇授权案例,博客结尾有shiro和ssm整合的一整个小案例,完成了登录、授权、缓存和session管理以及RememberMe功能。有需要的小伙伴下载,谢谢。 下面上代码,代码接着上一篇中的修改,我这里主要是授权改动的代码,shiro进行授权是两种方式注解和拦截器,我这里方便起见,使用的是注解。 修改自定义Realm //授权 ...

java小白的博客 468

Shiro之 SSM 授权

一、简介 SSM 项目整合Shiro 访问需要相关角色、许可的操作可以使用Filter 配置,但是使用Filter 非常的不灵活,请繁琐;Shiro 也提供了使用注解配置相关角色、许可的访问控制。 该授权操作将基于笔者 ssm 整合Shiro实现用户认证 项目, 二、项目修改 1.pom.xml 添加如下依赖: <dependency> <groupId>org.a...

Zllvincent的博客 8401

Shiro+SSM整合,认证授权

   环境 :     Shiro+SSM整合基于你已经拥有一个可运行的ssm环境,jar包管理这里使用的Maven。   主体 :    1. 导入shiro相关jar包    2. web.xml配置shiro的代理过滤器,shiro的入口,相当于建立起servlet与shiro的联系    3. 配置shiro的xml文件    步骤 :    1. pom.xml导入相关jar包     ...

hans的博客 1万+

shiro+ssm授权方式之xml文件授权

shiro+ssm给请求地址授权的方式有两种: 一是通过xml文件授权 二是通过注解方式授权

灵魂和肉体总要有一个在路上 364

SSM集成Shiro并完成认证和授权

一、准备工作 在进行ssm集成Shiro之前,需要准备相关的数据库表结构。如:用户表,角色表,权限表,用户与角色关系表,角色与权限关系表。 并且准备好相关的实体类,以及Mapper和Mapper的映射xml文件,还有进行认证的自定义Realm。 二、application-Shrio.xml文件的相关配置 在此,将shiro的配置内容与Spring的配置内容分开进行配置。 <beans xm...

qq_44193036的博客 361

Shiro与SSM集成实现用户认证和授权

Shiro实现用户认证 在 shiro 中,用户需要提供principals (身份)和credentials(凭证)给shiro,从而应用能验证用户身份。身份即帐号/凭证即密码

weixin_64987028的博客 376

shiro-----Shiro与SSM集成实现用户认证和授权

Shiro实现用户认证 在 shiro 中,用户需要提供principals (身份)和credentials(凭证)给shiro,从而应用能验证用户身份。身份即帐号/凭证即密码 认证流程 Shrio实现登录(盐加密)认证 导入Shrio与Spring及springMVC相关依赖 <!-- shiro核心包 --> <dependency> <groupId>org.apache.shiro</groupId...

鑫709的博客 1030

SSM+Shiro+用户登录授权

SSM与整合Shiro进行整合实现用户登录验证及权限分配 在前面的学习过程中,已经学习了 Shiro的一些基本组件以及如何利用Shiro进行权限控制。下面学习用目前比较主流的SSM框架来整合Shiro框架,将我们前面学习的一些基本知识运用到实际项目之中。由于本人初学,内容可能比较粗浅,后期进行深入理解后会细化,SSM项目的搭建过程这里不再叙述,可查阅其他人教程学习,可能有时间也会进行回顾记录。 为方便对下述内容进行理解,先画了一个流程图进行辅助 第一步项目配置文件(项目常规操作) 1.spring-con

qq_46416934的博客 375
上一篇: shiro入门
下一篇: git
P_YUX
博客等级 码龄7年 3粉丝 66原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值