Spring Security使用Hibernate实现自定义UserDetails

大多数时候,我们将需要在Web应用程序中配置自己的安全访问角色。 这在Spring Security中很容易实现。 在本文中,我们将看到最简单的方法。

首先,我们将在数据库中需要以下表格:

CREATE TABLE IF NOT EXISTS `mydb`.`security_role` (`id` INT(11) NOT NULL AUTO_INCREMENT ,`name` VARCHAR(50) NULL DEFAULT NULL ,PRIMARY KEY (`id`) )ENGINE = InnoDBAUTO_INCREMENT = 4DEFAULT CHARACTER SET = latin1;CREATE TABLE IF NOT EXISTS `mydb`.`user` (`id` INT(11) NOT NULL AUTO_INCREMENT ,`first_name` VARCHAR(45) NULL DEFAULT NULL ,`family_name` VARCHAR(45) NULL DEFAULT NULL ,`dob` DATE NULL DEFAULT NULL ,`password` VARCHAR(45) NOT NULL ,`username` VARCHAR(45) NOT NULL ,`confirm_password` VARCHAR(45) NOT NULL ,`active` TINYINT(1) NOT NULL ,PRIMARY KEY (`id`) ,UNIQUE INDEX `username` (`username` ASC) )ENGINE = InnoDBAUTO_INCREMENT = 9DEFAULT CHARACTER SET = latin1;CREATE TABLE IF NOT EXISTS `mydb`.`user_security_role` (`user_id` INT(11) NOT NULL ,`security_role_id` INT(11) NOT NULL ,PRIMARY KEY (`user_id`, `security_role_id`) ,INDEX `security_role_id` (`security_role_id` ASC) ,CONSTRAINT `user_security_role_ibfk_1`FOREIGN KEY (`user_id` )REFERENCES `mydb`.`user` (`id` ),CONSTRAINT `user_security_role_ibfk_2`FOREIGN KEY (`security_role_id` )REFERENCES `mydb`.`security_role` (`id` ))ENGINE = InnoDBDEFAULT CHARACTER SET = latin1;

显然,表用户将拥有用户,表security_role将拥有安全角色,而user_security_roles将拥有关联。 为了使实现尽可能简单,security_role表中的条目应始终以“ ROLE_”开头,否则我们将需要封装(本文将不涉及)。

因此,我们执行以下语句:

insert into security_role(name) values ('ROLE_admin');insert into security_role(name) values ('ROLE_Kennel_Owner');insert into security_role(name) values ('ROLE_User');insert into user (first_name,family_name,password,username,confirm_password,active)values ('ioannis','ntantis','123456','giannisapi','123456',1);insert into user_security_role (user_id,security_role_id) values (1,1);

因此,执行这些命令后,我们将得到以下内容:

三种不同的安全角色

一位用户名为“ giannisapi”的用户

我们已将角色“ ROLE_admin”赋予用户“ giannisapi”

现在,一切都已在数据库端完成,我们将移至Java端,看看需要做什么。

首先,我们将创建必要的DTO(有多种工具可以为您自动从数据库生成DTO):

package org.intan.pedigree.form;import java.io.Serializable;import java.util.Collection;import java.util.Date;import java.util.Set;import javax.persistence.Basic;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.JoinColumn;import javax.persistence.JoinTable;import javax.persistence.ManyToMany;import javax.persistence.NamedQueries;import javax.persistence.NamedQuery;import javax.persistence.Table;import javax.persistence.Temporal;import javax.persistence.TemporalType;/**** @author intan*/@Entity@Table(name = 'user', catalog = 'mydb', schema = '')@NamedQueries({@NamedQuery(name = 'UserEntity.findAll', query = 'SELECT u FROM UserEntity u'),@NamedQuery(name = 'UserEntity.findById', query = 'SELECT u FROM UserEntity u WHERE u.id = :id'),@NamedQuery(name = 'UserEntity.findByFirstName', query = 'SELECT u FROM UserEntity u WHERE u.firstName = :firstName'),@NamedQuery(name = 'UserEntity.findByFamilyName', query = 'SELECT u FROM UserEntity u WHERE u.familyName = :familyName'),@NamedQuery(name = 'UserEntity.findByDob', query = 'SELECT u FROM UserEntity u WHERE u.dob = :dob'),@NamedQuery(name = 'UserEntity.findByPassword', query = 'SELECT u FROM UserEntity u WHERE u.password = :password'),@NamedQuery(name = 'UserEntity.findByUsername', query = 'SELECT u FROM UserEntity u WHERE u.username = :username'),@NamedQuery(name = 'UserEntity.findByConfirmPassword', query = 'SELECT u FROM UserEntity u WHERE u.confirmPassword = :confirmPassword'),@NamedQuery(name = 'UserEntity.findByActive', query = 'SELECT u FROM UserEntity u WHERE u.active = :active')})public class UserEntity implements Serializable {private static final long serialVersionUID = 1L;@Id@GeneratedValue(strategy = GenerationType.IDENTITY)@Basic(optional = false)@Column(name = 'id')private Integer id;@Column(name = 'first_name')private String firstName;@Column(name = 'family_name')private String familyName;@Column(name = 'dob')@Temporal(TemporalType.DATE)private Date dob;@Basic(optional = false)@Column(name = 'password')private String password;@Basic(optional = false)@Column(name = 'username')private String username;@Basic(optional = false)@Column(name = 'confirm_password')private String confirmPassword;@Basic(optional = false)@Column(name = 'active')private boolean active;@JoinTable(name = 'user_security_role', joinColumns = {@JoinColumn(name = 'user_id', referencedColumnName = 'id')}, inverseJoinColumns = {@JoinColumn(name = 'security_role_id', referencedColumnName = 'id')})@ManyToManyprivate Set securityRoleCollection;public UserEntity() {}public UserEntity(Integer id) {this.id = id;}public UserEntity(Integer id, String password, String username, String confirmPassword, boolean active) {this.id = id;this.password = password;this.username = username;this.confirmPassword = confirmPassword;this.active = active;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getFirstName() {return firstName;}public void setFirstName(String firstName) {this.firstName = firstName;}public String getFamilyName() {return familyName;}public void setFamilyName(String familyName) {this.familyName = familyName;}public Date getDob() {return dob;}public void setDob(Date dob) {this.dob = dob;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getConfirmPassword() {return confirmPassword;}public void setConfirmPassword(String confirmPassword) {this.confirmPassword = confirmPassword;}public boolean getActive() {return active;}public void setActive(boolean active) {this.active = active;}public Set getSecurityRoleCollection() {return securityRoleCollection;}public void setSecurityRoleCollection(Set securityRoleCollection) {this.securityRoleCollection = securityRoleCollection;}@Overridepublic int hashCode() {int hash = 0;hash += (id != null ? id.hashCode() : 0);return hash;}@Overridepublic boolean equals(Object object) {// TODO: Warning - this method won't work in the case the id fields are not setif (!(object instanceof UserEntity)) {return false;}UserEntity other = (UserEntity) object;if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {return false;}return true;}@Overridepublic String toString() {return 'org.intan.pedigree.form.User[id=' + id + ']';}}
package org.intan.pedigree.form;import java.io.Serializable;import java.util.Collection;import javax.persistence.Basic;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.ManyToMany;import javax.persistence.NamedQueries;import javax.persistence.NamedQuery;import javax.persistence.Table;/**** @author intan*/@Entity@Table(name = 'security_role', catalog = 'mydb', schema = '')@NamedQueries({@NamedQuery(name = 'SecurityRoleEntity.findAll', query = 'SELECT s FROM SecurityRoleEntity s'),@NamedQuery(name = 'SecurityRoleEntity.findById', query = 'SELECT s FROM SecurityRoleEntity s WHERE s.id = :id'),@NamedQuery(name = 'SecurityRoleEntity.findByName', query = 'SELECT s FROM SecurityRoleEntity s WHERE s.name = :name')})public class SecurityRoleEntity implements Serializable {private static final long serialVersionUID = 1L;@Id@GeneratedValue(strategy = GenerationType.IDENTITY)@Basic(optional = false)@Column(name = 'id')private Integer id;@Column(name = 'name')private String name;@ManyToMany(mappedBy = 'securityRoleCollection')private Collection userCollection;public SecurityRoleEntity() {}public SecurityRoleEntity(Integer id) {this.id = id;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Collection getUserCollection() {return userCollection;}public void setUserCollection(Collection userCollection) {this.userCollection = userCollection;}@Overridepublic int hashCode() {int hash = 0;hash += (id != null ? id.hashCode() : 0);return hash;}@Overridepublic boolean equals(Object object) {// TODO: Warning - this method won't work in the case the id fields are not setif (!(object instanceof SecurityRoleEntity)) {return false;}SecurityRoleEntity other = (SecurityRoleEntity) object;if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {return false;}return true;}@Overridepublic String toString() {return 'org.intan.pedigree.form.SecurityRole[id=' + id + ']';}}

现在我们已经有了DTO,让我们创建必要的DAO类:

package org.intan.pedigree.dao;import java.util.List;import java.util.Set;import org.hibernate.SessionFactory;import org.intan.pedigree.form.SecurityRoleEntity;import org.intan.pedigree.form.UserEntity;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Repository;@Repositorypublic class UserEntityDAOImpl implements UserEntityDAO{@Autowiredprivate SessionFactory sessionFactory;public void addUser(UserEntity user) {try {sessionFactory.getCurrentSession().save(user);} catch (Exception e) {System.out.println(e);}}public UserEntity findByName(String username) {UserEntity user = (UserEntity) sessionFactory.getCurrentSession().createQuery('select u from UserEntity u where u.username = '' + username + ''').uniqueResult();return user;}public UserEntity getUserByID(Integer id) {UserEntity user = (UserEntity) sessionFactory.getCurrentSession().createQuery('select u from UserEntity u where id = '' + id + ''').uniqueResult();return user;}public String activateUser(Integer id) {String hql = 'update UserEntityset active = :active where id = :id';org.hibernate.Query query = sessionFactory.getCurrentSession().createQuery(hql);query.setString('active','Y');query.setInteger('id',id);int rowCount = query.executeUpdate();System.out.println('Rows affected: ' + rowCount);return '';}public String disableUser(Integer id) {String hql = 'update UserEntity set active = :active where id = :id';org.hibernate.Query query = sessionFactory.getCurrentSession().createQuery(hql);query.setInteger('active',0);query.setInteger('id',id);int rowCount = query.executeUpdate();System.out.println('Rows affected: ' + rowCount);return '';}public void updateUser(UserEntity user) {try {sessionFactory.getCurrentSession().update(user);} catch (Exception e) {System.out.println(e);}}public List listUser() {return sessionFactory.getCurrentSession().createQuery('from UserEntity').list();}public void removeUser(Integer id) {UserEntity user = (UserEntity) sessionFactory.getCurrentSession().load(UserEntity.class, id);if (null != user) {sessionFactory.getCurrentSession().delete(user);}}public Set getSecurityRolesForUsername(String username) {UserEntity user = (UserEntity) sessionFactory.getCurrentSession().createQuery('select u from UserEntity u where u.username = '' + username + ''').uniqueResult();if (user!= null) {Set roles = (Set) user.getSecurityRoleCollection();if (roles != null && roles.size() > 0) {return roles;}}return null;}}
package org.intan.pedigree.dao;import java.util.List;import org.hibernate.Criteria;import org.hibernate.SessionFactory;import org.hibernate.criterion.Restrictions;import org.intan.pedigree.form.Country;import org.intan.pedigree.form.Kennel;import org.intan.pedigree.form.SecurityRoleEntity;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Repository;@Repositorypublic class SecurityRoleEntityDAOImpl implements SecurityRoleEntityDAO{@Autowiredprivate SessionFactory sessionFactory;public void addSecurityRoleEntity(SecurityRoleEntity securityRoleEntity) {try {sessionFactory.getCurrentSession().save(securityRoleEntity);} catch (Exception e) {System.out.println(e);}}public List listSecurityRoleEntity() {Criteria criteria = sessionFactory.getCurrentSession().createCriteria(SecurityRoleEntity.class);criteria.add(Restrictions.ne('name','ROLE_ADMIN' ));return criteria.list();}public SecurityRoleEntity getSecurityRoleEntityById(Integer id) {Criteria criteria = sessionFactory.getCurrentSession().createCriteria(SecurityRoleEntity.class);criteria.add(Restrictions.eq('id',id));return (SecurityRoleEntity) criteria.uniqueResult();}public void removeSecurityRoleEntity(Integer id) {SecurityRoleEntity securityRoleEntity = (SecurityRoleEntity) sessionFactory.getCurrentSession().load(SecurityRoleEntity.class, id);if (null != securityRoleEntity) {sessionFactory.getCurrentSession().delete(securityRoleEntity);}}}

现在,我们将为上述DAO创建服务层。

package org.intan.pedigree.service;import java.util.List;import org.intan.pedigree.dao.SecurityRoleEntityDAO;import org.intan.pedigree.form.SecurityRoleEntity;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;@Servicepublic class SecurityRoleEntityServiceImpl implements SecurityRoleEntityService{@Autowiredprivate SecurityRoleEntityDAO securityRoleEntityDAO;@Transactionalpublic void addSecurityRoleEntity(SecurityRoleEntity securityRoleEntity) {securityRoleEntityDAO.addSecurityRoleEntity(securityRoleEntity);}@Transactionalpublic List listSecurityRoleEntity() {return securityRoleEntityDAO.listSecurityRoleEntity();}@Transactionalpublic void removeSecurityRoleEntity(Integer id) {securityRoleEntityDAO.removeSecurityRoleEntity(id);}@Transactionalpublic SecurityRoleEntity getSecurityRoleEntityById(Integer id) {return securityRoleEntityDAO.getSecurityRoleEntityById( id);}}

在下面的UserDetails的服务层中,请注意它是从org.springframework.security.core.userdetails.UserDetailsS​​ervice实现UserDetailsS​​ervice的。

package org.intan.pedigree.service;import org.intan.pedigree.dao.UserEntityDAO;import org.intan.pedigree.dao.UserEntityDAO;import org.intan.pedigree.form.UserEntity;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.dao.DataAccessException;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import org.springframework.security.core.userdetails.User;import org.springframework.security.core.userdetails.UserDetails;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.core.userdetails.UsernameNotFoundException;@Service('userDetailsService')public class UserDetailsServiceImpl implements UserDetailsService {@Autowiredprivate UserEntityDAO dao;@Autowiredprivate Assembler assembler;@Transactional(readOnly = true)public UserDetails loadUserByUsername(String username)throws UsernameNotFoundException, DataAccessException {UserDetails userDetails = null;UserEntity userEntity = dao.findByName(username);if (userEntity == null)throw new UsernameNotFoundException('user not found');return assembler.buildUserFromUserEntity(userEntity);}}

您还在上面看到,loadUserByUsername方法返回assembler.buildUserFromUserEntity的结果。 简而言之,汇编程序的这种方法是从给定的UserEntity DTO构造一个org.springframework.security.core.userdetails.User对象。 下面给出了Assembler类的代码:

package org.intan.pedigree.service;import java.util.ArrayList;import java.util.Collection;import org.intan.pedigree.form.SecurityRoleEntity;import org.intan.pedigree.form.UserEntity;import org.springframework.security.core.GrantedAuthority;import org.springframework.security.core.authority.GrantedAuthorityImpl;import org.springframework.security.core.userdetails.User;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;@Service('assembler')public class Assembler {@Transactional(readOnly = true)User buildUserFromUserEntity(UserEntity userEntity) {String username = userEntity.getUsername();String password = userEntity.getPassword();boolean enabled = userEntity.getActive();boolean accountNonExpired = userEntity.getActive();boolean credentialsNonExpired = userEntity.getActive();boolean accountNonLocked = userEntity.getActive();Collection authorities = new ArrayList();for (SecurityRoleEntity role : userEntity.getSecurityRoleCollection()) {authorities.add(new GrantedAuthorityImpl(role.getName()));}User user = new User(username, password, enabled,accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);return user;}}

现在剩下要做的唯一事情就是定义applicationContext-Security.xml中必需的内容。 为此,创建一个具有以下内容的名为“ applicationContext-Security.xml”的新xml文件:

<?xml version='1.0' encoding='UTF-8'?>
<beans:beans xmlns='http://www.springframework.org/schema/security'xmlns:beans='http://www.springframework.org/schema/beans' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'xmlns:context='http://www.springframework.org/schema/context'xsi:schemaLocation='http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd'><beans:bean id='userDetailsService' class='org.intan.pedigree.service.UserDetailsServiceImpl'></beans:bean><context:component-scan base-package='org.intan.pedigree' /><http auto-config='true'><intercept-url pattern='/admin/**' access='ROLE_ADMIN' /><intercept-url pattern='/user/**' access='ROLE_REGISTERED_USER' /><intercept-url pattern='/kennel/**' access='ROLE_KENNEL_OWNER' /><!-- <security:intercept-url pattern='/login.jsp' access='IS_AUTHENTICATED_ANONYMOUSLY' />  --></http><beans:bean id='daoAuthenticationProvider'class='org.springframework.security.authentication.dao.DaoAuthenticationProvider'><beans:property name='userDetailsService' ref='userDetailsService' /></beans:bean><beans:bean id='authenticationManager'class='org.springframework.security.authentication.ProviderManager'><beans:property name='providers'><beans:list><beans:ref local='daoAuthenticationProvider' /></beans:list></beans:property></beans:bean><authentication-manager><authentication-provider user-service-ref='userDetailsService'><password-encoder hash='plaintext' /></authentication-provider></authentication-manager></beans:beans>

在您的web.xml中放入以下代码,以加载applicationContext-security.xml文件。

<context-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/applicationContext-hibernate.xml/WEB-INF/applicationContext-security.xml</param-value></context-param>

最后,请原谅任何输入错误等,因为此代码只是从我完成的个人工作中复制和粘贴的内容,如果某些操作不起作用,请提出问题,我们将非常乐意为您提供帮助。

参考: Spring 3,Spring Security在Giannisapi博客上与我们的JCG合作伙伴 Ioannis Dadis 一起使用Hibernate实现自定义用户 详细信息 。


翻译自: https://www.javacodegeeks.com/2012/08/spring-security-implementing-custom.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/371958.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

python之路-面向对象

编程范式 编程是 程序 员 用特定的语法数据结构算法组成的代码来告诉计算机如何执行任务的过程 &#xff0c; 一个程序是程序员为了得到一个任务结果而编写的一组指令的集合&#xff0c;正所谓条条大路通罗马&#xff0c;实现一个任务的方式有很多种不同的方式&#xff0c; 对这…

西安邮电大学计算机科学与技术有专硕吗,2020年西安邮电大学计算机学院考研拟录取名单及排名!...

20考研复试调剂群&#xff1a;4197552812020年西安邮电大学计算机学院硕士研究生招生复试成绩及综合排名各位考生&#xff1a;现将我院2020年硕士研究生招生复试成绩及综合排名公布(最终录取名单及新生学籍注册均以“全国硕士研究生招生信息公开平台”备案信息为准)&#xff0c…

用Java排序的五种有用方法

Java排序快速概述&#xff1a; 正常的列表&#xff1a; private static List VEGETABLES Arrays.asList("apple", "cocumbers", "blackberry");Collections.sort(VEGETABLES);output: apple, blackberry, cocumbers反向排序&#xff1a; pri…

[python]-数据科学库Numpy学习

一、Numpy简介&#xff1a; Python中用列表(list)保存一组值&#xff0c;可以用来当作数组使用&#xff0c;不过由于列表的元素可以是任何对象&#xff0c;因此列表中所保存的是对象的指针。这样为了保存一个简单的[1,2,3]&#xff0c;需要有3个指针和三个整数对象。对于数值运…

检测一个点, 是否在一个半圆之内的方法

demo: http://jsbin.com/lihiwigaso 需求: 一个圆分成分部分, 鼠标滑上不同的区域显示不同的颜色 思路: 先判断这个点是否在圆之内, 再判断是否在所在的三角形之内就可以了 所需要的全部源码: <!DOCTYPE html> <html> <head><meta charset"utf-8&quo…

计算机网络设备接地规范,网络机房防雷接地的四种方式及静电要求

编辑----河南新时代防雷由于计算机网络系统的核心设备都放置在网络机房内&#xff0c;因而网络机房防雷接地有了较高的环境要求&#xff0c;良好的接地系统是保证机房计算机及网络设备安全运行&#xff0c;以及工作人员人身安全的重要措施。直流地的接法通常采用网格地&#xf…

抓住尾部的StackOverFlowError

使用Java程序时可能要处理的一种更烦人的情况是StackOverFlowError&#xff0c;如果您有一个很好的可生产的测试用例&#xff0c;那么关于使用堆栈大小或设置条件断点/某种痕迹 。 但是&#xff0c;如果您有一个测试案例可能一次失败100次&#xff0c;或者像我的案例一样在AWTM…

Gunicorn配置部分的翻译

写在前面&#xff0c;虽然翻译得很烂&#xff0c;但也是我的劳动成果&#xff0c;转载请注明出处&#xff0c;谢谢。 Gunicorn版本号19.7.1 Gunicorn配置 概述 三种配置方式 优先级如下&#xff0c;越后的优先级越大 1.框架的设置&#xff08;现在只有paster在用这个&#xff0…

台式计算机风扇声音大怎么处理,如何解决电脑电源风扇声音大的问题?

现在的台式机一般用3到5年后&#xff0c;一些问题自然也就慢慢表现出来了。很多网友在使用电脑过程中都有电脑风扇声音大怎么办的问题&#xff0c;电脑风扇声音大就会让人觉得使用电脑很不舒服&#xff0c;怎么办好呢&#xff1f;出现重要的问题要如何解决好呢&#xff1f;现在…

jsp分页功能

http://blog.csdn.net/xiazdong/article/details/6857515转载于:https://www.cnblogs.com/Baronboy/p/6112403.html

Spring Security第1部分–具有数据库的简单登录应用程序

什么是Spring Security&#xff1f; Spring Security是一个提供安全解决方案的框架&#xff0c;可在Web请求级别和方法级别上处理身份验证和授权。 Spring安全性通过两种方式处理安全性。 一种是安全的Web请求&#xff0c;另一种是在URL级别限制访问。 Spring Security使用Serv…

计算机应用 winxp,2017年职称计算机考试模块WindowsXP试题

2017年职称计算机考试模块WindowsXP试题全国专业技术人员计算机应用能力考试是专业技术人员资格考试的一种。接下来应届毕业生小编为大家搜索整理了2017年职称计算机考试模块WindowsXP试题&#xff0c;希望大家有所帮助。1. Windows XP中删除某个文件的快捷方式【 A 】。A. 对原…

Python基础(8)_迭代器、生成器、列表解析

一、迭代器 1、什么是迭代 1 重复   2 下次重复一定是基于上一次的结果而来 1 l[1,2,3,4] 2 count0 3 while count < len(l): 4 print(l[count]) 5 count1 迭代举例2、可迭代对象 可进行.__iter__()操作的为可迭代对象 #print(isinstance(str1,Iterable)),判断str…

Angularjs2-EXCEPTION: Response with status: 200 Ok for URL:

利用jsonp跨域请求数居&#xff0c;报错 core.umd.js:3070 EXCEPTION: Response with status: 200 Ok for URL: 参考&#xff1a;stackoverflow 未解决。。。脑仁疼。。。有小伙伴也碰到过这个问题么&#xff1f; 16/11/30 问题解决 1.服务器端API允许跨域访问(返回的数据添加允…

图片无法删除要计算机管理员,存在桌面的图片删不掉,怎么处理?提示是需要管理员权限。...

将下面代码复制到记事本里&#xff0c;重命名为1.bat&#xff0c;然后打开&#xff0c;这时你右键图片会出现管理员取得所有权&#xff0c;然后取得所有权后再删除试试Windows Registry Editor Version 5.00[HKEY_CLASSES_ROOT\*\shell\runas]管理员取得所有权NoWorkingDirecto…

Java对象序列化的本机C / C ++类似性能

您是否曾经希望过像使用C 这样的本地语言将Java对象转换成字节流一样快的速度&#xff1f; 如果您使用标准的Java序列化&#xff0c;您可能会对性能感到失望。 Java序列化的目的是与尽可能快而紧凑地序列化对象的目的截然不同。 为什么我们需要快速紧凑的序列化&#xff1f; 我…

WebStrom Sass 编译配置 windows

第一步&#xff1a; 先安装Ruby下载 一路next 安装完成后打开开始菜单 打开后输入 gem install sass sass -v 出现版本号说明成功 第二部配置webstorm 在webstorm中settings中搜索file watchers工具&#xff0c;在此工具中添加一个scss的watcher 确定&#xff0c;打开一个scss…

非本地跳转之setjmp与longjmp

非本地跳转(unlocal jump)是与本地跳转相对应的一个概念。 本地跳转主要指的是类似于goto语句的一系列应用&#xff0c;当设置了标志之后&#xff0c;可以跳到所在函数内部的标号上。然而&#xff0c;本地跳转不能将控制权转移到所在程序的任意地点&#xff0c;不能跨越函数&am…

清华计算机自主招生试题,2017年清华大学自主招生笔试题

2017年清华大学自主招生笔试题2017高考结束后&#xff0c;全国各大高校自主招生面试开始了&#xff0c;以下是百分网小编搜索整理的关于2017年清华大学自主招生笔试题&#xff0c;供各位参考&#xff0c;希望对大家有所帮助!想了解更多相关信息请持续关注我们应届毕业生考试网!…

扩展剂:模式还是反模式?

扩展器模式在最近几年变得很流行&#xff0c;甚至已经在OSGi标准&#xff08;例如&#xff0c;蓝图服务和Web应用程序规范&#xff09;中使用。 在处女座&#xff0c;我们从一开始就与扩展程序一起工作&#xff0c;但是尽管它们具有优势&#xff0c;但它们仍有一些明显的缺点。…