嘉兴模板建站系统,如何进行网站建设的销售,深圳住房和建设局网站公开招标,网站建设衤金手指下拉10基于SpringMVC实现常见功能
防止XSS攻击 XSS攻击全称跨站脚本攻击#xff0c;是为不和层叠样式表(Cascading Style Sheets, CSS)的缩写混淆#xff0c;故将跨站脚本攻击缩写为XSS#xff0c;XSS是一种在web应用中的计算机安全漏洞#xff0c;它允许恶意web用户将代码植入到…基于SpringMVC实现常见功能
防止XSS攻击 XSS攻击全称跨站脚本攻击是为不和层叠样式表(Cascading Style Sheets, CSS)的缩写混淆故将跨站脚本攻击缩写为XSSXSS是一种在web应用中的计算机安全漏洞它允许恶意web用户将代码植入到提供给其它用户使用的页面中。 在后端基于SpringMVC框架过滤XSS攻击还是比较简单只需要使用InitBinder注解即可。
导入Jar包
dependencygroupIdorg.apache.commons/groupIdartifactIdcommons-text/artifactIdversion1.2/version
/dependency过滤XSS攻击
import java.beans.PropertyEditorSupport;import org.apache.commons.text.StringEscapeUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;public abstract class BaseController {InitBinderprotected void initBinder(WebDataBinder binder){// String类型转换将所有传递进来的String进行HTML编码防止XSS攻击binder.registerCustomEditor(String.class, new PropertyEditorSupport() {Overridepublic void setAsText(String text) {setValue(text null ? null : StringEscapeUtils.escapeHtml4(text.trim()));}Overridepublic String getAsText() {Object value getValue();return value null ? : value.toString();}});}
}继承BaseController即可
通过上述的步骤即可过滤XSS攻击。
数据转换
很多时候前端数据传过来后端并不能正常接收比如日期的格式外国人和国人习惯就是不一样的需要转换格式还有比如XSS攻击后端也需要进行数据转换。
上面使用InitBinder添加自定义编辑器转换数据这次主要讲如何使用WebBindingInitializer注册全局自定义编辑器转换数据。
程序
import java.beans.PropertyEditorSupport;import org.apache.commons.text.StringEscapeUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.WebRequest;public class TextBindingInitializer implements WebBindingInitializer {Overridepublic void initBinder(WebDataBinder binder, WebRequest request) {binder.registerCustomEditor(String.class, new PropertyEditorSupport() {Overridepublic void setAsText(String text) {setValue(text null ? null : StringEscapeUtils.escapeHtml4(text.trim()));}Overridepublic String getAsText() {Object value getValue();return value null ? : value.toString();}});}
}配置
bean classorg.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapterproperty namewebBindingInitializerbean classcom.plf.base.TextBindingInitializer //property
/bean注意
已经废弃
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter建议使用
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter当需要使用全局处理的时候可以使用WebBindingInitializer如果只是局部处理那就可以使用InitBinder。
静态资源的配置
SpringMVC配置前端控制器的时候一般建议配置为*.do这种方式,这是不会存在访问不到静态资源的问题但是目前比较流行RESTful风格就需要配置 \ ,这样就需要配置静态资源的访问路径不然就访问不到。
第一种
在springmvc中配置第一步需要 http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd 约束第二步配置 mvc:default-servlet-handler /即可mvc:default-servlet-handler /会将对静态资源的访问请求通过HandlerMapping映射到默认
Servlet请求处理器DefaultServletHttpRequestHandler对象。
而处理器调用了Tomcat的DefaultServlet来处理静态资源的访问请求。其实就是将SpringMVC不能处理的请求交给tomcat。第二种
servlet-mappingservlet-namedefault/servlet-nameurl-pattern*.jpg/url-pattern/servlet-mappingservlet-mappingservlet-namedefault/servlet-nameurl-pattern*.js/url-pattern/servlet-mappingservlet-mappingservlet-namedefault/servlet-nameurl-pattern*.css/url-pattern/servlet-mappingservlet-mappingservlet-namedefault/servlet-nameurl-pattern*.png/url-pattern/servlet-mapping第三种
在springmvc.xml中配置
mvc:resources location/static/ mapping/static/**/在spring3.0.4版本之后Spring中定义了专门用于处理静态资源访问请求的处理器
ResourceHttpRequestHandler并且添加了mvc:resources /标签专门用于解决
静态资源无法访问问题。location 表示静态资源所在目录。目录可以是WEB-INF/目录以及子目录
mapping 表示对该以资源的请求该配置会把静态资源的访问请求经HandlerMapping直接映射到
静态资源处理器对象ResourceHttpRequestHandler集成Shiro的配置
Apache Shiro是一个强大且易用的Java安全框架,执行身份验证、授权、加密和会话管理。所以它用途广泛在大部分系统中都有应用本博客主要讲解基于Spring的配置方法。 Shiro小巧而且简单使用方便很适合高效编码。
学习Shiro的基本使用可以参考http://wiki.jikexueyuan.com/project/shiro/
github上也有相关资料参考https://github.com/zhangkaitao/shiro-example
Shiro核心组件
Subject表示当前的“用户”这个用户不一定是一个具体的人与当前应用交互的任何东西都是Subject比如第三方进程等SecurityManager安全管理器即所有与安全有关的操作都会与SecurityManager交互且其管理着所有Subject。Subject代表了当前用户的安全操作SecurityManager则管理所有用户的安全操作。Realm安全数据源当SecurityManager要验证用户身份可以从Realm中获取用户对比其身份是否合法也可以获取到用户的权限和验证用户操作的合法性。
基于Spring的配置方法
导入Jar包
!-- Shiro的Jar包 --
dependencygroupIdorg.apache.shiro/groupIdartifactIdshiro-core/artifactIdversion1.4.0/version
/dependency
dependencygroupIdorg.apache.shiro/groupIdartifactIdshiro-web/artifactIdversion1.4.0/version
/dependency
dependencygroupIdorg.apache.shiro/groupIdartifactIdshiro-ehcache/artifactIdversion1.4.0/version
/dependency
dependencygroupIdorg.apache.shiro/groupIdartifactIdshiro-spring/artifactIdversion1.4.0/version
/dependency!-- 项目中会使用到ehcache缓存 --
dependencygroupIdnet.sf.ehcache/groupIdartifactIdehcache-core/artifactIdversion2.6.11/version
/dependency配置Filter
在web.xml中配置Shiro的Filter
filterfilter-nameshiroFilter/filter-namefilter-classorg.springframework.web.filter.DelegatingFilterProxy/filter-classinit-paramparam-nametargetFilterLifecycle/param-nameparam-valuetrue/param-value/init-param
/filterfilter-mappingfilter-nameshiroFilter/filter-nameurl-pattern/*/url-pattern
/filter-mapping配置CacheManager缓存管理器
!-- 配置CacheManager 缓存管理器 --
bean idcacheManagerclassorg.apache.shiro.cache.ehcache.EhCacheManager!-- 指定ehcache的配置文件 --property namecacheManagerConfigFile valueclasspath:ehcache-shiro.xml/
/bean其中使用到ehcache的配置ehcache-shiro.xml用默认的配置即可
ehcachediskStore pathjava.io.tmpdir/shiro-spring-sample/defaultCachemaxElementsInMemory10000eternalfalsetimeToIdleSeconds120timeToLiveSeconds120overflowToDiskfalsediskPersistentfalsediskExpiryThreadIntervalSeconds120/cache nameshiro-activeSessionCachemaxElementsInMemory10000eternaltrueoverflowToDisktruediskPersistenttruediskExpiryThreadIntervalSeconds600/cache nameorg.apache.shiro.realm.SimpleAccountRealm.authorizationmaxElementsInMemory100eternalfalsetimeToLiveSeconds600overflowToDiskfalse//ehcache
配置Shiro的SecurityManager
!-- 配置Shiro的SecurityManager --
bean idsecurityManagerclassorg.apache.shiro.web.mgt.DefaultWebSecurityManagerproperty namecacheManager refcacheManager/!-- 配置自定义的Realm --property namerealm refmyRealm/
/bean
配置授权和认证的Realm
bean idmyRealm classcom.plf.shiro.realm.MyRealmproperty namecredentialsMatcher!-- 使用MD5加密 --bean classorg.apache.shiro.authc.credential.HashedCredentialsMatcherproperty namehashAlgorithmName valueMD5/propertyproperty namehashIterations value1024/property/bean/property
/bean需要自定义的Realm
import java.util.HashSet;
import java.util.Set;import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.junit.Test;public class MyRealm extends AuthenticatingRealm{Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationTokentoken) throws AuthenticationException {//hashCode 一样 说明token是传值过来的System.out.println(2token.hashCode());System.out.println(MyRealm ---- AuthenticationInfo:token);//1、把AuthenticationToken强转成UsernamePasswordTokenUsernamePasswordToken upToken (UsernamePasswordToken) token;//2、从UsernamePasswordToken中获取usernameString username upToken.getUsername();//3、调用数据库方法从数据库中查询username对应的用户记录System.out.println(从数据库中获取usernameusername 所对应的用户信息);//4、如果用户不存在则可以抛出UnknownAccountException异常if(unknown.equals(username)){throw new UnknownAccountException(用户不存在);}//5、根据用户信息的情况则可以抛出AuthenticationException异常if(monster.equals(username)){throw new LockedAccountException(用户锁定);}//6、根据用户情况来构建AuthenticationInfo对象并返回//以下信息是从数据库中获取的//1 principal 认证的实体信息 可以是username 也可以是数据表对应的用户的实体类对象Object principal username;//2 credentials 密码Object credentials;//123456 userif(user.equals(username)){credentials098d2c478e9c11555ce2823231e02ec1;}if(admin.equals(username)){//123456 admincredentials 038bdaf98f2037b31f1e75b5b4c9b26e;}//3 realmName 当前realm对象的name 调用父类的getName()方法即可String realmName getName();//4 盐值//这里username为唯一值所以也可以做盐值反正就是需要随机唯一值即可ByteSource credentialsSalt ByteSource.Util.bytes(username);SimpleAuthenticationInfo info new SimpleAuthenticationInfo(principal,credentials,credentialsSalt,realmName);return info;}//主要是为了获取到MD5加密后的密码Testpublic void getMD5(){String hashAlgorithmName MD5;Object credentials 123456;Object salt ByteSource.Util.bytes(user);int hashIterations 1024;Object result new SimpleHash(hashAlgorithmName,credentials,salt,hashIterations);System.out.println(result);}
}配置Bean的后置处理器
!-- 配置Bean后置处理器会自动地调用和Spring整合的各个组件的生命周期方法可以自动的来调用配置在SpringIOC容器中Shiro bean 的生命周期方法--
bean idlifecycleBeanPostProcessorclassorg.apache.shiro.spring.LifecycleBeanPostProcessor/
启用IOC容器中使用Shiro的注解
!-- 启用IOC容器中使用shiro的注解但必须在配置了LifecycleBeanPostProcessor之后才能使用 --
bean classorg.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator depends-onlifecycleBeanPostProcessor/
bean classorg.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisorproperty namesecurityManager refsecurityManager/property
/bean配置Shiro的Filter
!-- 配置 shiroFilter 该bean的id必须与web.xml文件中配置的shiro filter的name一致--
bean idshiroFilter classorg.apache.shiro.spring.web.ShiroFilterFactoryBean!-- 装配securityManager --property namesecurityManager refsecurityManager/!-- 登录页面 --property nameloginUrl value/shiro-login.jsp/!-- 登录成功页面 --property namesuccessUrl value/shiro-success.jsp/!-- 授权失败页面 --property nameunauthorizedUrl value/shiro-fail.jsp/!-- 具体配置需要拦截哪些URL以及访问对应的URL时使用Shiro的什么filter进行拦截 1anon 匿名访问2authc 认证之后登录才能访问的页面3logout 登出4user 用户拦截器 用户已经身份验证/记住我登录即可5 authcBasic Basic HTTP身份验证拦截器6roles 角色授权拦截器7perms 权限授权拦截器 验证用户是否拥有所有权限 /user/**perms[user:create]8port 端口拦截器/testport[80]9rest rest风格拦截器 自动根据请求方法构建权限字符串10ssl SSL拦截器 只有请求协议是https才能通过11noSessionCreation 不创建会话拦截器--property namefilterChainDefinitionsvalue/shiro-logout logout# 不用认证即可访问/shiro-login anon/shiro-login.jsp anon/user.jsp roles[user]/admin.jsp roles[admin]# allow WebStart to pull the jars for the swing app:/*.jar anon# everything else requires authentication:/** authc/value/property
/bean控制器中使用
RequestMapping(shiro-login)
public String login(RequestParam String username,RequestParam String password){Subject currentUser SecurityUtils.getSubject();if(!currentUser.isAuthenticated()){//把用户名和密码封装为UsernamePasswordToken对象UsernamePasswordToken token new UsernamePasswordToken(username,password);token.setRememberMe(true);try{System.out.println(1token.hashCode());currentUser.login(token);}catch(AuthenticationException e){System.out.println(登录失败e.getMessage());return shiro-fail;}}return shiro-success;
}
文章转载自: http://www.morning.tqgmd.cn.gov.cn.tqgmd.cn http://www.morning.zzgkk.cn.gov.cn.zzgkk.cn http://www.morning.lgwpm.cn.gov.cn.lgwpm.cn http://www.morning.nqdkx.cn.gov.cn.nqdkx.cn http://www.morning.jjwt.cn.gov.cn.jjwt.cn http://www.morning.mfzyn.cn.gov.cn.mfzyn.cn http://www.morning.bzjpn.cn.gov.cn.bzjpn.cn http://www.morning.jrslj.cn.gov.cn.jrslj.cn http://www.morning.qrmyd.cn.gov.cn.qrmyd.cn http://www.morning.ctfwl.cn.gov.cn.ctfwl.cn http://www.morning.ntqjh.cn.gov.cn.ntqjh.cn http://www.morning.cwtrl.cn.gov.cn.cwtrl.cn http://www.morning.ndtzy.cn.gov.cn.ndtzy.cn http://www.morning.tpkxs.cn.gov.cn.tpkxs.cn http://www.morning.fjptn.cn.gov.cn.fjptn.cn http://www.morning.nhzzn.cn.gov.cn.nhzzn.cn http://www.morning.yqhdy.cn.gov.cn.yqhdy.cn http://www.morning.hwpcm.cn.gov.cn.hwpcm.cn http://www.morning.ndmh.cn.gov.cn.ndmh.cn http://www.morning.stbfy.cn.gov.cn.stbfy.cn http://www.morning.tpyrn.cn.gov.cn.tpyrn.cn http://www.morning.hgscb.cn.gov.cn.hgscb.cn http://www.morning.plcyq.cn.gov.cn.plcyq.cn http://www.morning.wschl.cn.gov.cn.wschl.cn http://www.morning.lzdbb.cn.gov.cn.lzdbb.cn http://www.morning.tqdlk.cn.gov.cn.tqdlk.cn http://www.morning.ndyrb.com.gov.cn.ndyrb.com http://www.morning.qqzdr.cn.gov.cn.qqzdr.cn http://www.morning.mhnxs.cn.gov.cn.mhnxs.cn http://www.morning.mkrjf.cn.gov.cn.mkrjf.cn http://www.morning.phwmj.cn.gov.cn.phwmj.cn http://www.morning.czzpm.cn.gov.cn.czzpm.cn http://www.morning.ptwqf.cn.gov.cn.ptwqf.cn http://www.morning.cszbj.cn.gov.cn.cszbj.cn http://www.morning.dpnhs.cn.gov.cn.dpnhs.cn http://www.morning.hclplus.com.gov.cn.hclplus.com http://www.morning.nrbqf.cn.gov.cn.nrbqf.cn http://www.morning.bqqzg.cn.gov.cn.bqqzg.cn http://www.morning.fgxws.cn.gov.cn.fgxws.cn http://www.morning.lxhgj.cn.gov.cn.lxhgj.cn http://www.morning.hytr.cn.gov.cn.hytr.cn http://www.morning.lydtr.cn.gov.cn.lydtr.cn http://www.morning.zqcdl.cn.gov.cn.zqcdl.cn http://www.morning.kuaijili.cn.gov.cn.kuaijili.cn http://www.morning.cpnsh.cn.gov.cn.cpnsh.cn http://www.morning.pxwzk.cn.gov.cn.pxwzk.cn http://www.morning.wtyqs.cn.gov.cn.wtyqs.cn http://www.morning.wypyl.cn.gov.cn.wypyl.cn http://www.morning.hnrqn.cn.gov.cn.hnrqn.cn http://www.morning.gjlxn.cn.gov.cn.gjlxn.cn http://www.morning.jltmb.cn.gov.cn.jltmb.cn http://www.morning.ndxss.cn.gov.cn.ndxss.cn http://www.morning.fygbq.cn.gov.cn.fygbq.cn http://www.morning.jljiangyan.com.gov.cn.jljiangyan.com http://www.morning.nyzmm.cn.gov.cn.nyzmm.cn http://www.morning.xjkr.cn.gov.cn.xjkr.cn http://www.morning.rhkgz.cn.gov.cn.rhkgz.cn http://www.morning.nclbk.cn.gov.cn.nclbk.cn http://www.morning.rccpl.cn.gov.cn.rccpl.cn http://www.morning.lstmg.cn.gov.cn.lstmg.cn http://www.morning.xqcbz.cn.gov.cn.xqcbz.cn http://www.morning.cmcjp.cn.gov.cn.cmcjp.cn http://www.morning.hrypl.cn.gov.cn.hrypl.cn http://www.morning.lkwyr.cn.gov.cn.lkwyr.cn http://www.morning.srky.cn.gov.cn.srky.cn http://www.morning.ktmnq.cn.gov.cn.ktmnq.cn http://www.morning.mkzdp.cn.gov.cn.mkzdp.cn http://www.morning.hbdqf.cn.gov.cn.hbdqf.cn http://www.morning.sknbb.cn.gov.cn.sknbb.cn http://www.morning.xdpjf.cn.gov.cn.xdpjf.cn http://www.morning.mnpdy.cn.gov.cn.mnpdy.cn http://www.morning.spqbp.cn.gov.cn.spqbp.cn http://www.morning.tyhfz.cn.gov.cn.tyhfz.cn http://www.morning.myzfz.com.gov.cn.myzfz.com http://www.morning.qstkk.cn.gov.cn.qstkk.cn http://www.morning.fkrzx.cn.gov.cn.fkrzx.cn http://www.morning.qtltg.cn.gov.cn.qtltg.cn http://www.morning.dhbyj.cn.gov.cn.dhbyj.cn http://www.morning.ntyanze.com.gov.cn.ntyanze.com http://www.morning.qydgk.cn.gov.cn.qydgk.cn