在a.js文件里面调用b.html 里面的<>c方法</>,如何调用啊?

在a.js文件里面调用b.html 里面的<>c方法</>,如何调用啊,图片说明图片说明

如图,我要在list.js文件里面调用fullcalendar.html里的<>function test()</>

4个回答

调用不了,除非它俩都位于 fullcalendar.html 页面上。
在 html 中定义的 js 方法是不能复用的,只有在独立 js 文件中定义的方法,通过引入该 js 文件后才能复用。

Lzwiscoming
Lzwiscoming fullcalendar.html是通过iframe嵌套在list.html的子页面,在list.js中发现用window.frames["childPage"].test()可以调用full.....html里面的test方法(childPage是iframe的ID名和name = 'childPage').一开始没说清楚,不好意思哈
5 个月之前 回复

HTML把test()结果发级服务器 JS可以通过AJAX与服务端通信获取结果

为什么不把他写到一个js里面呢

zea_liu
zea_liu 回复Lzwiscoming: 如果是这样子你可以写window.parent.method()去调用父的方法
5 个月之前 回复
Lzwiscoming
Lzwiscoming fullcalendar.html是通过iframe嵌套在list.html的子页面,在list.js中发现用window.frames["childPage"].test()可以调用full.....html里面的test方法(childPage是iframe的ID名和name = 'childPage').一开始没说清楚,不好意思哈
5 个月之前 回复

你可以试下,b页面里面做个全局变量,然后引用a,c ,用试试看能不能在b页面里面实现

Lzwiscoming
Lzwiscoming fullcalendar.html是通过iframe嵌套在list.html的子页面,在list.js中发现用window.frames["childPage"].test()可以调用full.....html里面的test方法(childPage是iframe的ID名和name = 'childPage').一开始没说清楚,不好意思哈
5 个月之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
怎样用uglifyjs3压缩一组代码,将几个文件的函数名同步混淆?可以用uglifyjs混淆.html文件吗?
比如我在A.js中创建了: ``` function Add(str1, str2) { var strSum = str1 + str2; return strSum; } ``` 在B.js调用了A的函数: ``` var sum = Add(1,2); ``` 在C.html调用了A的函数: ``` var sum = Add(2,2); ``` 可以用uglify把他们的函数名同步混淆吗,如果A中的‘Add’变成m,B和C中的‘Add’也变成m。 现在我通过把lifyjs.js文件中option配置成: ``` var options = { mangle: { toplevel: true, }, nameCache: {} }; ``` 可以把A.js中的Add变为n,但是其他文件调用的函数Add不能同步混淆。
JavaScript调用Flex方法
1.Flex里面使用ExternalInterface.call(“Js函数名称”,参数)进行调用javascript方法,其返回的值就是Js函数所返回的值。 2.在初始化方法中使用ExternalInterface.addCallback(“注册的方法名”,As中的函数名)进行注册,“注册的方法名”可以再javascript中直接调用 3.在js中,就可以用document.getElementById(“Flash在Html中的ID”).注册的方法名(参数)进行调用,当然,默认”Flash在Html中的ID”就是Flex文件的名称,例如,我们这里就是SampleApp,因为我们的Flex文件就是SampleApp.mxml //Flex代码 <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" creationComplete="application1_creationCompleteHandler(event)" minWidth="955" minHeight="600"> <fx:Script> <![CDATA[ import flash.external.*; import mx.controls.Alert; import mx.events.FlexEvent; protected function text_clickHandler(event:MouseEvent):void { myFunc(); } public function myFunc():void { Alert.show("Invoke Ok"); } public function getValue():Number { return 84; } protected function application1_creationCompleteHandler(event:FlexEvent):void { ExternalInterface.addCallback( "myFlexFunction" ,myFunc); ExternalInterface.addCallback( "getValue" ,getValue); } ]]> </fx:Script> <fx:Declarations> <!-- 将非可视元素(例如服务、值对象)放在此处 --> </fx:Declarations> <mx:Button id="Test" label="Hello" click="text_clickHandler(event)"> </mx:Button> </s:Application> //HTML代码,Flex自动生成的代码中小改动。 <body> <!-- SWFObject's dynamic embed method replaces this alternative HTML content with Flash content when enough JavaScript and Flash plug-in support is available. The div is initially hidden so that it doesn't show when JavaScript is disabled. --> <div id="flashContent"> <p> To view this page ensure that Adobe Flash Player version 11.1.0 or greater is installed. </p> </div> <noscript> <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100px" height="100px" id="SampleApp"> <param name="movie" value="SampleApp.swf" /> <param name="quality" value="high" /> <param name="bgcolor" value="#ffffff" /> <param name="allowScriptAccess" value="sameDomain" /> <param name="allowFullScreen" value="true" /> <!--[if !IE]>--> <object type="application/x-shockwave-flash" data="SampleApp.swf" width="100px" height="100px"> <param name="quality" value="high" /> <param name="bgcolor" value="#ffffff" /> <param name="allowScriptAccess" value="sameDomain" /> <!--<![endif]--> <!--[if gte IE 6]>--> <p> Either scripts and active content are not permitted to run or Adobe Flash Player version 11.1.0 or greater is not installed. </p> <!--<![endif]--> <a href="http://www.adobe.com/go/getflashplayer"> <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash Player" /> </a> <!--[if !IE]>--> </object> <!--<![endif]--> </object> </noscript> <input type="button" value="test" onclick="TestFlex()"/> </body> <script type="text/javascript"> function TestFlex() { var obj=document.getElementById('SampleApp'); //obj.myFlexFunction(); var vals=obj.getValue(); alert(vals); } </script>
c#调用html文件中js函数
要做一个程序从读卡器读出数据,给的测试的网页中可以用读卡器读出数据,怎么才能用c#调用html中的js函数 html> ``` <head> <title>TEST</title> <script language="javascript"> function GetCardinfo() { var cport; var cseat; var str1; cport=parseInt(document.form1.T1.value); cseat=parseInt(document.form1.T2.value); str1=document.getElementById("CIccardCtrl").GetCardinfo(cport,cseat); document.form1.cardinfo.value=str1; } </script> </head> <body> <OBJECT classid=clsid:8A5B3626-40FC-4563-AF78-C9C4AC2ECFD6 width=0 height=0 align="center" id="CIccardCtrl" HSPACE=0 VSPACE=0> </OBJECT> <form name="form1"> <p>串口号<input type="text" name="T1" size="20" value="1"> <p>卡座号(1:下卡座 2:上卡座)<input type="text" name="T2" size="20" value="1"> <p><input type="text" name="cardinfo" size="60"> <input type="button" onclick="javascript:GetCardinfo()" value="读卡信息" > </form> </body> </html> ```
在html中调用js文件(无路径错误和书写错误),但js中的函数无法执行
我在html中调用js文件 <script type="text/javascript" src="Question_Manage.js"></script> 这个文件中有5个函数,其中有一个函数已经可以用了,但是这个文件中的另外两个函数在调用 的时候却没有反映,具体代码如下 **html代码** <!-- `<div id="dx" style="display:none"><!--单选题--> <form name="form_dx" action="#" method="post" onSubmit="return SubQuestion('dx');" > <input type="hidden" value="<%=Task_ID %>" name="Task_ID" /> <input type="hidden" value="" name="Q_body" /> <input type="hidden" value="" name="RightAnswer" /> <p>问题:</p> <textarea rows="1" name="Q_head" cols="40" onpropertychange="this.style.posHeight=this.scrollHeight"></textarea> <br/><br/> <p>选项:</p> <ul id="ulAnswer_dx"> <li><input type="radio" name="radio" value="A"/>A<input type="text" name="Answer" /></li> <li><input type="radio" name="radio" value="B"/>B<input type="text" name="Answer" /></li> <li><input type="radio" name="radio" value="C"/>C<input type="text" name="Answer" /></li> <li><input type="radio" name="radio" value="D"/>D<input type="text" name="Answer" /></li> </ul> <input type="button" name="MoreAnswer" value="增加选项" onClick="MoreAnswer('dx');" /> <input type="button" name="LessAnswer" value="减少选项" onClick="LessAnswer('dx');" /> <input type="submit" value="添加题目" /> </form> </div>`` --> **html代码解释** SubQuestion('dx')这个函数也在Question_Manage.js中,就是它能用 但是MoreAnswer('dx')和LessAnswer('dx')这两个函数不能用 **js代码** function MoreAnswer(type){ alert("this is alert");//用来测试该函数有没有调用的临时警告 switch(type){ case "dx": var ul = document.getElementById("ulAnswer_dx"); var lis = ul.getElementsByTagName("li"); var sign = document.createElement("p"); sign.style.display = "inline"; sign.innerHTML = String.fromCharCode(i.length+65); var inputTitle=document.createElement("input"); inputTitle.setAttribute("type", "radio"); inputTitle.setAttribute("name", "radio"); inputTitle.setAttribute("value",'String.fromCharCode(lis.length+65)'); var input=document.createElement("input"); input.setAttribute("name","Answer"); input.setAttribute("type","text"); var li=document.createElement("li"); li.appendChild(inputTitle); li.appendChild(sign); li.appendChild(input); ul.appendChild(li); break; case "marked": var ul=document.getElementById("ulAnswer_marked"); var li=document.createElement("li"); var textArea=document.createElement("textarea"); textArea.setAttribute("rows", "1"); textArea.setAttribute("name", "Answer"); textArea.setAttribute("cols","100"); li.appendChild(textArea); ul.appendChild(li); break; default: break; } } function LessAnswer(type){ switch(type){ case "dx": var ul = document.getElementById("ulAnswer_dx") if(ul.firstChild.nextSibling == ul.lastChild){ alert("已减至最后一项"); }else{ ul.removeChild(ul.lastChild); } break; case "marked": var ul = document.getElementById("ulAnswer_marked") if(ul.firstChild.nextSibling == ul.lastChild){ alert("已减至最后一项"); }else{ ul.removeChild(ul.lastChild); } break; } } **js代码解释** MoreAnswer(type)和 LessAnswer(type)是用来增加和删除html中的元素,但现在这两个函数却在点击按钮的时候无法调用
jquery ajax方法调用在session超时以后如何跳转到登录页面?
jquery ajax方法调用在session超时以后如何跳转到登录页面? session超时以后虽然被过滤器过滤到了,但是并不会跳转到登录页面请求具体的解决方法。 我参考了这篇文章,但是我调用ajaxStart不起作用。 http://www.blogjava.net/vickzhu/archive/2009/06/05/280223.html ext jquery 用户访问超时(ext session过期) 解决两种情况下的用户访问超时。 a)普通http请求的session超时。 b)异步http请求的session超时,使用ext后大部分的界面刷新都是异步的ajax请求。 不管是那种类型的http请求总是可以由一个过滤器来捕捉。 分类:普通http请求的header参数中没有x-requested-with:XMLHttpRequest头信息,而异步的有。 其实对于常见的ajax框架,header中还有标示自己身份的header信息。 对于普通的http请求,发现session超时后直接重定向到一个超时页面,显示访问超时。 对于异步http请求,发现session超时后则向请求的response中写入特定的超时头信息,客户端ajax对象检测 头信息,发现有超时状态标志后调用显示超时信息的javascript方法,提示用户访问超时。 服务器端session超时后在过滤器中为response添加新的头信息,标记该请求超时: if(r.getHeader("x-requested-with")!=null && r.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){ response.setHeader("sessionstatus","timeout"); } 使用Ext.Ajaxt对象完成异步请求的交互,Ext.Ajax是单实例对象(非常重要,全局单一Ext.Ajax实例!)。 注册Ext.Ajax的requestcomplete事件,每个ajax请求成功后首先响应该事件。在该事件的回调函数里面判断 访问请求是否超时。使用Ext.Ajax对象的好处是,只需要引入一个包含了几行超时处理代码的js文件,就可以 为当前应用增加超时处理功能,原有代码不需要做任何修改。 使用Ext.Ajaxt对象完成异步请求交互,假如checkUserSessionStatus是你的回调方法,每个页面引用: Ext.Ajax.on('requestcomplete',checkUserSessionStatus, this); function checkUserSessionStatus(conn,response,options){ //Ext重新封装了response对象 if(typeof response.getResponseHeader.sessionstatus != 'undefined'){ //发现请求超时,退出处理代码... } } 可以利用的几个特性:a)所有的ajax请求均带有x-requested-with:XMLHttpRequest头信息b)Ext.Ajax是单实例对象(非常重要,全局单一Ext.Ajax实例!)c)注册Ext.Ajax的requestcomplete事件,每个ajax请求成功后首先响应该事件(概念类似spring的aop拦截)。 jquery提供了几个全局事件可以用来处理session过期请求,如当ajax请求开始时会触发ajaxStart()方法的回调函数;当ajax请求结束时,会触发ajaxStop()方法的回调函数。这些方法都是全局的方法,因此无论创建它们的代码位于何处,只要有ajax请求发生时,都会触发它们。类似的事件还有:ajaxComplete(),ajaxError(),ajaxSend(),ajaxSuccess()等。 如果使某个ajax请求不受全局方法的影响,那么可以在使用$.ajax()方法时,将参数中的global设置为false,jquery代码如下:$.ajax({ url:"test.html", global:false//不触发全局ajax事件}) 对于其他的ajax框架,解决用户访问请求超时这个问题的思路是类似的。
基于springmvc+mybatis的登录表单提交后404
前端填写正确的用户名和密码后,提交登录,浏览器显示404,前端提交的地址是/userlogin,后端对接的/user/userlogin也是对的,浏览器f12里显示请求的确成功传给了后端,但是不知道为什么404。用的是tomcat8.5,java版本1.8,phpstudy最新版,mysql5.7.26。 ## 这是所用到的包: ![图片说明](https://img-ask.csdn.net/upload/202002/01/1580567617_880785.jpg) ## 这是目录结构: ![图片说明](https://img-ask.csdn.net/upload/202002/01/1580567511_223692.jpg) ## 这是web.xml: ```xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>springmvc_test</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 配置spring监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 加载spring配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/context-config.xml</param-value> </context-param> <!-- 配置前端控制器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <!-- DispatcherServlet在初始化方法里面会读取该初始化参数的值来获得 spring配置文件的位置 ,然后启动spring容器。 --> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/springmvc-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 配置字符编码 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> ``` ## 这是context-config.xml: ```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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 扫描service包下的注解 --> <context:component-scan base-package="com.test.service"></context:component-scan> <!-- 配置数据库 --> <!-- 加载配置文件 --> <!-- <context:property-placeholder location="classpath:jdbc.properties"/> --> <bean id="dateSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driver" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/Eday_Test"></property> <property name="username" value="root"></property> <property name="password" value="123456"></property> </bean> <!-- 配置Sqlsessionfactory并将数据源注入 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 引入数据源 --> <property name="dateSource" ref="dateSource"></property> <!-- 载入mybatis配置文件 --> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <!-- 载入配置mapper映射的xml --> <property name="mapperLocations" value="classpath:com/test/mapper/*.xml"></property> </bean> <!-- 配置扫描mapper接口 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackge" value="com.test.mapper"></property> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dateSource" ref="dateSource"></property> </bean> <tx:annotation-driven transaction-manager="transactionManager"/> </beans> ``` ## 这是mybatis-config.xml: ```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <typeAliases> <!-- 配置别名 --> <typeAlias alias="User" type="com.test.pojo.User"/> </typeAliases> </configuration> ``` ## 这是springmvc-config.xml: ```xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" 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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 扫描controller包下的注解 --> <context:component-scan base-package="com.test.controller"></context:component-scan> <!-- 开启注解 --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 静态资源访问 --> <mvc:default-servlet-handler/> <!-- 视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 配置试图解析的默认路径,即配置页面的根路径 --> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans> ``` ## 这是UserController.java: ```java package com.test.controller; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.test.pojo.User; import com.test.service.UserService; //声明控制器 @Controller //设置bean的scope属性为多例(prototype) @Scope("prototype") //设置请求映射,当客户端请求/user时,转到该控制器处理 @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @RequestMapping(value="/userlogin") public ModelAndView login(String user_Name,String user_pwd,ModelAndView mv,HttpSession session){ //调用userService中的login方法处理user实体类对象 User user = userService.login(user_Name,user_pwd); //登录的逻辑判断,判断条件是返回结果不为空 if(user!=null){ //登陆成功,将user对象设置到HttpSession作用范围域中,相当于服务端的cookie,有效时间默认30分钟 //在程序运行期间,在任意页面都可以提取它的值。 session.setAttribute("user",user); //转发到main请求 //登录成功,跳转页面 mv.setViewName("login/login-success"); }else{ //登录失败,向前端传递失败信息 mv.addObject("message","用户名或密码错误,请重新输入!"); //登录失败,跳转到登录页面 mv.setViewName("login"); } return mv; } //跳转到用户注册界面 @RequestMapping(value="/userregister"/*,method=RequestMethod.POST*/) public String register(User user){ String user_Name = user.getUser_Name(); //如果数据库中没有该用户,可以注册,否则跳转页面 if(userService.findByUserName(user_Name)==null){ //添加用户 userService.register(user); //注册成功,跳转到主页面 return "index"; }else{ //注册失败,跳转到错误页面 return "error"; } } } ``` ## 这是UserMapper.java: ```java package com.test.mapper; import org.apache.ibatis.annotations.Param; import com.test.pojo.User; public interface UserMapper { //根据用户名和密码查找,mybatis中有多个参数时,需要使用@Param注解 User findByUserNameAndPassword(@Param("user_Name")String user_Name,@Param("user_Pwd")String user_Pwd); //增加用户 void addUser(User user); //根据用户名查询 User findByUserName(String user_Name); } ``` ## 这是UserMapper.xml: ```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.tes.mapper.UserMapper"> <!-- 根据用户名和密码查询 --> <select id="findByUserNameAndPasssword" resultType="User"> select * from user where user_Name=#{user_Name} and user_Pwd=#{user_Pwd} </select> <!-- 增加用户 --> <insert id="addUser" parameterType="User"> insert into user (user_Name,user_Pwd,user_Email,user_NickName,user_Birth,user_Phone,user_InvitationCode) values(#{user_Name},#{user_Pwd},#{user_Email},#{user_NickName},#{user_Birth},#{user_Phone},#{user_InvitationCode}) </insert> <!-- 根据用户名查询 --> <select id="findByUserName" resultType="User"> select * from user where user_Name=#{user_Name} </select> </mapper> ``` ## 这是User.java: ```java package com.test.pojo; import java.sql.Timestamp; public class User { private int user_Id; private String user_Name; private int user_Pwd; private String user_Email; private String user_NickName; private Timestamp user_Time; private String user_Birth; private int user_Fans; private int user_Follow; private int user_Score; private String user_HeadImgAddr; private int user_Phone; private String user_InvitationCode; public int getUser_Id() { return user_Id; } public void setUser_Id(int user_Id) { this.user_Id = user_Id; } public String getUser_Name() { return user_Name; } public void setUser_Name(String user_Name) { this.user_Name = user_Name; } public int getUser_Pwd() { return user_Pwd; } public void setUser_Pwd(int user_Pwd) { this.user_Pwd = user_Pwd; } public String getUser_Email() { return user_Email; } public void setUser_Email(String user_Email) { this.user_Email = user_Email; } public String getUser_NickName() { return user_NickName; } public void setUser_NickName(String user_NickName) { this.user_NickName = user_NickName; } public Timestamp getUser_Time() { return user_Time; } public void setUser_Time(Timestamp user_Time) { this.user_Time = user_Time; } public String getUser_Birth() { return user_Birth; } public void setUser_Birth(String user_Birth) { this.user_Birth = user_Birth; } public int getUser_Fans() { return user_Fans; } public void setUser_Fans(int user_Fans) { this.user_Fans = user_Fans; } public int getUser_Follow() { return user_Follow; } public void setUser_Follow(int user_Follow) { this.user_Follow = user_Follow; } public int getUser_Score() { return user_Score; } public void setUser_Score(int user_Score) { this.user_Score = user_Score; } public String getUser_HeadImgAddr() { return user_HeadImgAddr; } public void setUser_HeadImgAddr(String user_HeadImgAddr) { this.user_HeadImgAddr = user_HeadImgAddr; } public int getUser_Phone() { return user_Phone; } public void setUser_Phone(int user_Phone) { this.user_Phone = user_Phone; } public String getUser_InvitationCode() { return user_InvitationCode; } public void setUser_InvitationCode(String user_InvitationCode) { this.user_InvitationCode = user_InvitationCode; } @Override public String toString() { return "User [user_Id=" + user_Id + ", user_Name=" + user_Name + ", user_Pwd=" + user_Pwd + ", user_Email=" + user_Email + ", user_NickName=" + user_NickName + ", user_Time=" + user_Time + ", user_Birth=" + user_Birth + ", user_Fans=" + user_Fans + ", user_Follow=" + user_Follow + ", user_Score=" + user_Score + ", user_HeadImgAddr=" + user_HeadImgAddr + ", user_Phone=" + user_Phone + ", user_InvitationCode=" + user_InvitationCode + "]"; } } ``` ## 这是UserService.java: ```java package com.test.service; import com.test.pojo.User; public interface UserService { //通过用户名及密码核查用户登录 User login(String user_Name,String user_Pwd); //增加用户 void register(User user); //根据用户名查询 User findByUserName(String user); } ``` ## 这是UserServiceImpl.java: ```java package com.test.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.test.mapper.UserMapper; import com.test.pojo.User; import com.test.service.UserService; @Service @Transactional public class UserServiceImpl implements UserService { //注入UserMapper接口 @Autowired private UserMapper userMapper; //登录,根据用户名和密码进行查询 @Override public User login(String user_Name,String user_Pwd){ return userMapper.findByUserNameAndPassword(user_Name,user_Pwd); } //注册,增加用户 @Override public void register(User user){ userMapper.addUser(user); } //根据用户名查询 @Override public User findByUserName(String user_Name){ return userMapper.findByUserName(user_Name); } } ``` ##这是login.jsp ```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"> <link rel="stylesheet" type="text/css" href="../css/login.css" /> <title>登录</title> </head> <body> <!--导航栏--> <nav class="nav"> <ul> <li class="logo"><a href="#">Eday</a></li> <li class="shouye"><a href="../index.jsp" class="neirong">首页</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">文章列表</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">留言板</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">更新日志</a></li> </ul> </nav> <!--登录板块--> <header class="header"> <p class="logintitle"> <b>登录</b> </p> <form action="${pageContext.request.contextPath }/user/userlogin" method="post" class=login-form> <p class= login-username-p> <label for="username" class="login-username-text">用户名:</label> <input type=text name="user_Name" class="login-username-input"> <br><a href="register.jsp" class=login-register>注册</a> </p> <p class="login-psw-p"> <label for="psw" class="login-psw-text">密码:</label> <input type=password name="user_Pwd" class="login-psw-input"> <br><a href="#" class=login-forget>忘记密码</a> </p> <div class=login-button-div> <label for=button></label> <button type=sublim class=login-button>登录</button> </div> </form> </header> </body> </html> ``` ## 这是login-success.jsp: ```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>登录成功,请等待跳转...</title> <script type="text/javascript"> onload=function(){ setInterval(go, 1000); }; var x=3; //利用了全局变量来执行 function go(){ x--; if(x>0){ document.getElementById("sp").innerHTML=x; //每次设置的x的值都不一样了。 }else{ location.href='../index.jsp'; } } </script> </head> <body> <!--导航栏--> <nav class="nav"> <ul> <li class="logo"><a href="#">Eday</a></li> <li class="shouye"><a href="../index.jsp" class="neirong">首页</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">文章列表</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">留言板</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">更新日志</a></li> </ul> </nav> <header> <div> <p>登录成功!页面将在3秒后自动跳转,请稍等...</p> </div> </header> </body> </html> ``` ## 这是数据库: ![图片说明](https://img-ask.csdn.net/upload/202002/01/1580568589_694404.jpg)
jQuery上传插件Uploadify 3.2在.NET下的详细例子
项目中要使用Uploadify 3.2来实现图片上传并生成缩略通的功能,特此记下来,以供各位参考! Uploadify下载地址:http://www.uploadify.com/download/ 下载下来解压后估计里面很多文件,其实有用的也就jquery.uploadify.min.js、uploadify.css、uploadify.swf和uploadify-cancel.png这四个文件。你还得下载jQuery库,我这里用的是jquery-1.7.2.min.js,另外和大多数JQ插件一样,同时也需要swfobject.js这个插件,我的是2.2的版本,东西都准备好了,那下面就开始。 前端界面: [html] view plain copy <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="jqUploadify._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>无标题页</title> <link href="scripts/uploadify.css" rel="stylesheet" type="text/css" /> <link href="scripts/default.css" rel="stylesheet" type="text/css" /> <script src="scripts/jquery-1.7.2.min.js" type="text/javascript"></script> <script src="scripts/swfobject.js" type="text/javascript"></script> <script src="scripts/jquery.uploadify.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function(){ $("#file_upload").uploadify({ //开启调试 'debug' : false, //是否自动上传 'auto':false, 'buttonText':'选择照片', //flash 'swf': "scripts/uploadify.swf", //文件选择后的容器ID 'queueID':'uploadfileQueue', 'uploader':'scripts/upload.ashx', 'width':'75', 'height':'24', 'multi':false, 'fileTypeDesc':'支持的格式:', 'fileTypeExts':'*.jpg;*.jpge;*.gif;*.png', 'fileSizeLimit':'1MB', 'removeTimeout':1, //返回一个错误,选择文件的时候触发 'onSelectError':function(file, errorCode, errorMsg){ switch(errorCode) { case -100: alert("上传的文件数量已经超出系统限制的"+$('#file_upload').uploadify('settings','queueSizeLimit')+"个文件!"); break; case -110: alert("文件 ["+file.name+"] 大小超出系统限制的"+$('#file_upload').uploadify('settings','fileSizeLimit')+"大小!"); break; case -120: alert("文件 ["+file.name+"] 大小异常!"); break; case -130: alert("文件 ["+file.name+"] 类型不正确!"); break; } }, //检测FLASH失败调用 'onFallback':function(){ alert("您未安装FLASH控件,无法上传图片!请安装FLASH控件后再试。"); }, //上传到服务器,服务器返回相应信息到data里 'onUploadSuccess':function(file, data, response){ //alert(data); } }); }); function doUplaod(){ $('#file_upload').uploadify('upload','*'); } function closeLoad(){ $('#file_upload').uploadify('cancel','*'); } </script> </head> <body> <table width="704" border="0" align="center" cellpadding="0" cellspacing="0" id="__01"> <tr> <td align="center" valign="middle"> <div id="uploadfileQueue" style="padding: 3px;"> </div> <div id="file_upload"> </div> </td> </tr> <tr> <td height="50" align="center" valign="middle"> <img alt="" src="images/BeginUpload.gif" width="77" height="23" onclick="doUplaod()" style="cursor: hand" /> <img alt="" src="images/CancelUpload.gif" width="77" height="23" onclick="closeLoad()" style="cursor: hand" /> </td> </tr> </table> </body> </html> 后端的Handler: [csharp] view plain copy using System; using System.Collections; using System.Data; using System.Linq; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.Xml.Linq; using System.Web.SessionState; using System.IO; namespace jqUploadify.scripts { /// <summary> /// $codebehindclassname$ 的摘要说明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class upload : IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Charset = "utf-8"; HttpPostedFile file = context.Request.Files["Filedata"]; string uploadPath = context.Server.MapPath("..\\uploads\\"); if (file != null) { if (!Directory.Exists(uploadPath)) { Directory.CreateDirectory(uploadPath); } file.SaveAs(uploadPath + file.FileName); //生成缩略图 MakeThumbnail(uploadPath + file.FileName, uploadPath + "\\s\\" + file.FileName, 80, 80); } } private void MakeThumbnail(string sourcePath, string newPath, int width, int height) { System.Drawing.Image ig = System.Drawing.Image.FromFile(sourcePath); int towidth = width; int toheight = height; int x = 0; int y = 0; int ow = ig.Width; int oh = ig.Height; if ((double)ig.Width / (double)ig.Height > (double)towidth / (double)toheight) { oh = ig.Height; ow = ig.Height * towidth / toheight; y = 0; x = (ig.Width - ow) / 2; } else { ow = ig.Width; oh = ig.Width * height / towidth; x = 0; y = (ig.Height - oh) / 2; } System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.Clear(System.Drawing.Color.Transparent); g.DrawImage(ig, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel); try { bitmap.Save(newPath, System.Drawing.Imaging.ImageFormat.Jpeg); } catch (Exception ex) { throw ex; } finally { ig.Dispose(); bitmap.Dispose(); g.Dispose(); } } public bool IsReusable { get { return false; } } } } 这样我们就是实现图片上传至uploads,生成的缩略图(这里设为80*80)存放在uploads下面的s文件夹中,是不是很简单呢!当然实际使用过程你还可能碰到一下的问题: 1、在火狐下session出现丢失的情况,可以参考这里:http://www.cnblogs.com/akingyao/archive/2012/09/04/2670794.html 2、IE9出现了按钮不能点击的问题,可以参考这里:http://www.uploadify.com/forum/#/discussion/9155/uploadify-version-3-2-does-not-work-in-ie9/p1 最后贴一个Uploadify参数说明: Uploadify Version 3.2 Options选项设置 auto 选择文件后自动上传 buttonClass 给“浏览按钮”加css的class样式 buttonCursor 鼠标移上去形状:arrow箭头、hand手型(默认) buttonImage 鼠标移上去变换图片 buttonText 按钮文字 checkExisting 在目录中检查文件是否已上传成功(1 ture,0 false) debug 是否显示调试框(默认不显示false) fileObjName 设置一个名字,在服务器处理程序中根据该名字来取上传文件的数据。默认为Filedata,$tempFile = $_FILES['Filedata']['tmp_name'] fileSizeLimit 设置允许上传文件最大值B, KB, MB, GB 比如:'fileSizeLimit' : '20MB' fileTypeDesc 选择的文件的描述。这个字符串出现在浏览文件对话框中文件类型下拉框处。默认:All Files fileTypeExts 允许上传的文件类型。格式:'fileTypeExts' : '*.gif; *.jpg; *.png' formData 附带值,需要通过get or post传递的额外数据,需要结合onUploadStart事件一起使用 height “浏览按钮”高度px itemTemplate <itemTemplate>节点表示显示的内容。这些内容中也可以包含绑定到控件DataSource属性中元素集合的数据。 method 上传方式。默认:post multi 选择文件时是否可以【选择多个】。默认:可以true overrideEvents 不执行默认的onSelect事件 preventCaching 随机缓存值 默认true ,可选true和false.如果选true,那么在上传时会加入一个随机数来使每次的URL都不同,以防止缓存.但是可能与正常URL产生冲突 progressData 进度条上显示的进度:有百分比percentage和速度speed。默认百分比 queueID 给“进度条”加背景css的ID样式。文件选择后的容器ID queueSizeLimit 允许多文件上传的数量。默认:999 removeCompleted 上传完成后队列是否自动消失。默认:true removeTimeout 上传完成后队列多长时间后消失。默认 3秒 需要:'removeCompleted' : true,时使用 requeueErrors 队列上传出错,是否继续回滚队列,即反复尝试上传。默认:false successTimeout 上传超时时间。文件上传完成后,等待服务器返回信息的时间(秒).超过时间没有返回的话,插件认为返回了成功。 默认:30秒 swf swf文件的路径,本文件是插件自带的,不可用其它的代替.本参数不可省略 uploader 上传处理程序URL,本参数不可省略 uploadLimit 限制总上传文件数,默认是999。指同一时间,如果关闭浏览器后重新打开又可上传。 width “浏览按钮”宽度px Events 事件 onCancel 当取消一个上传队列中的文件时触发,删除时触发 onClearQueue 清除队列。当'cancel'方法带着*参数时,也就是说一次全部取消的时候触发.queueItemCount是被取消的文件个数(另外的按钮) onDestroy 取消所有的上传队列(另外的按钮) onDialogClose 当选择文件对话框关闭时触发,不论是点的'确定'还是'取消'都会触发.如果本事件被添加进了'overrideEvents'参数中,那么如果在选择文件时产生了错误,不会有错误提示框弹出 onDialogOpen 当选择文件框被打开时触发,没有传过来的参数 onDisable 关闭上传 onEnable 开启上传 onFallback 检测FLASH失败调用 onInit 每次初始化一个队列时触发 onQueueComplete 当队列中的所有文件上传完成时触发 onSelect 当文件从浏览框被添加到队列中时触发 onSelectError 选择文件出错时触发 onSWFReady flash准备好时触发 onUploadComplete当一个文件上传完成时触发 onUploadError 当文件上传完成但是返回错误时触发 onUploadProgress上传汇总 onUploadStart 一个文件上传之间触发 onUploadSuccess 每个上传完成并成功的文件都会触发本事件 Methods 方法 cancel 取消一个上传队列 destroy 取消所有上传队列 disable 禁止点击“浏览按钮” settings 返回或修改一个 uploadify实例的settings值 stop 停止当前的上传并重新添加到队列中去 upload 上传指定的文件或者所有队列中的文件 最后是DEMO的下载地址:http://download.csdn.net/detail/wangqiuyun/566551
spring mvc+shiro+cas 实现cas client功能 跳转回来404
http://securitycenter.com:8080/gtsys/cas?ticket=ST-14-HEDhc1GVQt0UYdiZpi7R-cas 返回这个地址 404 ![图片说明](https://img-ask.csdn.net/upload/201510/09/1444404164_27274.png) ``` <?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:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd" > <!-- 定时器开关 开始 --> <task:annotation-driven /> <!-- 标注类型 的事务配置 如果使用注解事务。就放开 <tx:annotation-driven />--> <!-- 统一异常处理方式 --> <bean id="exceptionHandler" class="com.lanyuan.exception.MyExceptionHandler"/> <!-- 初始化数据 --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" > <property name ="locations"> <list> <value>classpath:jdbc.properties</value> </list> </property> <property name="ignoreUnresolvablePlaceholders" value="true" /> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="driverClassName" value="${jdbc.driverClass}" /> </bean> <bean id="pagePlugin" class="com.lanyuan.plugin.PagePlugin"> <property name="properties"> <props> <prop key="dialect">mysql</prop> <prop key="pageSqlId">.*query.*</prop> </props> </property> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动匹配Mapper映射文件 --> <property name="mapperLocations" value="classpath:mappings/*-mapper.xml"/> <property name="typeAliasesPackage" value="com.lanyuan.entity"/> <property name="plugins"> <array> <ref bean="pagePlugin" /> </array> </property> </bean> <!-- 通过扫描的模式,扫描目录在com.lanyuan.mapper目录下,所有的mapper都继承SqlMapper接口的接口, 这样一个bean就可以了 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.lanyuan.mapper" /> </bean> <!-- 事务配置 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- <aop:config> <aop:pointcut expression="execution(public * com.lanyuan.controller.*(..))" id="pointcut" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" /> </aop:config> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="query*" propagation="REQUIRED" read-only="true" /> <tx:method name="find*" propagation="REQUIRED" read-only="true" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="modify*" propagation="REQUIRED" /> <tx:method name="logicDelById" propagation="REQUIRED" /> </tx:attributes> </tx:advice> --> <!-- <aop:aspectj-autoproxy proxy-target-class="true"/> <bean id="log4jHandlerAOP" class="com.lanyuan.logAop.LogAopAction"></bean> <aop:config proxy-target-class="true"> <aop:aspect id="logAspect" ref="log4jHandlerAOP"> <aop:pointcut id="logPointCut" expression="execution(* org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(..))" /> <aop:around method="logAll" pointcut-ref="logPointCut" /> </aop:aspect> </aop:config> --> <!-- 使用Spring组件扫描的方式来实现自动注入bean --> <context:component-scan base-package="com.lanyuan.task" /> <!-- 隐式地向 Spring 容器注册 --> <context:annotation-config /> </beans> spring-application.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:tx="http://www.springframework.org/schema/tx" 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.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.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-4.1.xsd" > <tx:annotation-driven /> <context:component-scan base-package="com.lanyuan.controller" /> <context:component-scan base-package="com.lanyuan.logAop" /> <!-- 启动对@AspectJ注解的支持 --> <!--通知spring使用cglib而不是jdk的来生成代理方法 AOP可以拦截到Controller--> <aop:aspectj-autoproxy proxy-target-class="true"/> <!-- 注解支持 --> <context:annotation-config/> <!--避免IE执行AJAX时,返回JSON出现下载文件 --> <bean id="mappingJackson2HttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>text/json;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> </bean> <!-- 采用SpringMVC自带的JSON转换工具,支持@ResponseBody注解 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJackson2HttpMessageConverter" /> <!-- JSON转换器 --> </list> </property> </bean> <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean> <mvc:annotation-driven> <!-- 处理responseBody 里面日期类型 --> <mvc:message-converters> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper"> <bean class="com.fasterxml.jackson.databind.ObjectMapper"> <property name="dateFormat"> <bean class="java.text.SimpleDateFormat"> <constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" /> </bean> </property> </bean> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 默认编码 --> <property name="defaultEncoding" value="utf-8" /> <!-- 文件大小最大值 --> <property name="maxUploadSize" value="10485760000" /> <!-- 内存中的最大值 --> <property name="maxInMemorySize" value="40960" /> </bean> <import resource="spring-mvc-shiro.xml"/> </beans> spring-mvc.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:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd" > <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" > <property name ="locations"> <list> <value>classpath:jdbc.properties</value> </list> </property> <property name="ignoreUnresolvablePlaceholders" value="true" /> </bean> <bean id="credentialsMatcher" class="com.lanyuan.shiro.credentials.RetryLimitHashedCredentialsMatcher"> <!-- hashAlgorithmName必须的,没有默认值。可以有MD5或者SHA-1,如果对密码安全有更高要求可以用SHA-256或者更高。 这里使用MD5 storedCredentialsHexEncoded默认是true,此时用的是密码加密用的是Hex编码;false时用Base64编码 hashIterations迭代次数,默认值是1。 --> <constructor-arg ref="cacheManager" /> <property name="hashAlgorithmName" value="md5" /> <!--<property name="hashIterations" value="2" />--> <!--<property name="storedCredentialsHexEncoded" value="true" />--> </bean> <!-- 会话Cookie模板 --> <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie"> <!-- sid如果改为JSESSIONID会导致重定向循环 --> <constructor-arg value="sid"/> <property name="httpOnly" value="true"/> <property name="maxAge" value="-1"/> </bean> <bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie"> <constructor-arg value="rememberMe"/> <property name="httpOnly" value="true"/> <property name="maxAge" value="2592000"/><!-- 30天 --> </bean> <!-- rememberMe管理器 --> <bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager"> <!-- rememberMe cookie加密的密钥 建议每个项目都不一样 默认AES算法 密钥长度(128 256 512 位)--> <property name="cipherKey" value="#{T(org.apache.shiro.codec.Base64).decode('4AvVhmFLUs0KTA3Kprsdag==')}"/> <property name="cookie" ref="rememberMeCookie"/> </bean> <bean id="casSubjectFactory" class="org.apache.shiro.cas.CasSubjectFactory"/> <!-- 凭证匹配器 --> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="casRealm" /> <property name="sessionManager" ref="sessionManager"/> <!-- 使用下面配置的缓存管理器 --> <property name="cacheManager" ref="cacheManager" /> <property name="rememberMeManager" ref="rememberMeManager"/> <property name="subjectFactory" ref="casSubjectFactory"/> </bean> <!-- 相当于调用SecurityUtils.setSecurityManager(securityManager) --> <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager"/> <property name="arguments" ref="securityManager"/> </bean> <!--自定义Realm --> <!-- <bean id="myRealm" class="com.lanyuan.shiro.MyRealm"> <property name="credentialsMatcher" ref="credentialsMatcher" /> <property name="cachingEnabled" value="false" /> --> <!-- 如需要自定义缓存时间放开以下.修改 ehcache.xml--> <!--<property name="authenticationCachingEnabled" value="true"/>--> <!--<property name="authenticationCacheName" value="authenticationCache"/>--> <!--<property name="authorizationCachingEnabled" value="true"/>--> <!--<property name="authorizationCacheName" value="authorizationCache"/>--> <!-- </bean> --> <!-- <property name="userService" ref="userService"/> --> <bean id="casRealm" class="com.lanyuan.shiro.MyCasRealm"> <property name="cachingEnabled" value="true"/> <property name="authenticationCachingEnabled" value="true"/> <property name="authenticationCacheName" value="authenticationCache"/> <property name="authorizationCachingEnabled" value="true"/> <property name="authorizationCacheName" value="authorizationCache"/> <!--该地址为cas server地址 --> <property name="casServerUrlPrefix" value="${shiro.casServer.url}"/> <!-- 该地址为是当前应用 CAS 服务 URL,即用于接收并处理登录成功后的 Ticket 的, 必须和loginUrl中的service参数保持一致,否则服务器会判断service不匹配--> <property name="casService" value="${shiro.client.cas}"/> </bean> <bean id="sysUserFilter" class="com.lanyuan.shiro.filter.SysUserFilter"/> <bean id="kickoutSessionControlFilter" class="com.lanyuan.shiro.filter.KickoutSessionControlFilter"> <property name="cacheManager" ref="cacheManager"/> <property name="sessionManager" ref="sessionManager"/> <property name="kickoutAfter" value="false"/> <property name="maxSession" value="1"/> <property name="kickoutUrl" value="/login.shtml"/> </bean> <bean id="casFilter" class="org.apache.shiro.cas.CasFilter"> <!--配置验证错误时的失败页面(Ticket 校验不通过时展示的错误页面) --> <property name="failureUrl" value="${shiro.failureUrl}"/> </bean> <bean id="casLogoutFilter" class="io.github.howiefh.cas.session.CasLogoutFilter"> <property name="sessionManager" ref="sessionManager"/> </bean> <bean id="logoutFilter" class="org.apache.shiro.web.filter.authc.LogoutFilter"> <property name="redirectUrl" value="${shiro.logout.url}"/> </bean> <!-- 配置shiro的过滤器工厂类,id- shiroFilter要和我们在web.xml中配置的过滤器一致 --> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager" /> <!-- <property name="loginUrl" value="/login.shtml" /> <property name="successUrl" value="/index.shtml" /> --> <property name="loginUrl" value="${shiro.login.url}"/> <property name="successUrl" value="${shiro.login.success.url}"/> <property name="unauthorizedUrl" value="/denied.jsp" /> <!-- 自定义权限配置 --> <property name="filterChainDefinitionMap" ref="chainDefinitionSectionMetaSource" /> <property name="filters"> <util:map> <entry key="cas" value-ref="casFilter"/> <entry key="logout" value-ref="logoutFilter" /> <entry key="casLogout" value-ref="casLogoutFilter" /> <entry key="sysUser" value-ref="sysUserFilter"/> <entry key="kickout" value-ref="kickoutSessionControlFilter"/> </util:map> </property> </bean> <!--自定义filterChainDefinitionMap --> <bean id="chainDefinitionSectionMetaSource" class="com.lanyuan.shiro.ChainDefinitionSectionMetaSource"> <property name="filterChainDefinitions"> <value> /casFailure.jsp = anon /cas = casLogout,cas /logout = logout /favicon.ico = anon /admin_files/** = anon /fonts/** = anon /404/** = anon /error.jsp = anon /js/** = anon /layer-v1.9.2/** = anon /notebook/** = anon /login.shtml = anon /denied.jsp = anon /install.shtml = anon /lanyuan.shtml = anon /** = casLogout,user </value> </property> </bean> <bean id="sessionIdGenerator" class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator"/> <!-- 会话DAO --> <bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO"> <property name="activeSessionsCacheName" value="shiro-activeSessionCache"/> <property name="sessionIdGenerator" ref="sessionIdGenerator"/> </bean> <!-- 会话验证调度器 --> <!-- 全局的会话信息检测扫描信息间隔30分钟--> <bean id="sessionValidationScheduler" class="org.apache.shiro.session.mgt.quartz.QuartzSessionValidationScheduler"> <property name="sessionValidationInterval" value="1800000"/> <property name="sessionManager" ref="sessionManager"/> </bean> <!-- 会话管理器 --> <!-- 全局的会话信息设置成30分钟,sessionValidationSchedulerEnabled参数就是是否开启扫描 --> <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager"> <property name="globalSessionTimeout" value="1800000"/> <property name="deleteInvalidSessions" value="true"/> <property name="sessionValidationSchedulerEnabled" value="true"/> <property name="sessionValidationScheduler" ref="sessionValidationScheduler"/> <property name="sessionDAO" ref="sessionDAO"/> <property name="sessionIdCookieEnabled" value="true"/> <property name="sessionIdCookie" ref="sessionIdCookie"/> </bean> <!--shiro缓存管理器 --> <bean id="cacheManager" class="com.lanyuan.shiro.spring.SpringCacheManagerWrapper" > <property name="cacheManager" ref="springCacheManager"/> </bean> <bean id="springCacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"> <property name="cacheManager" ref="ehcacheManager"/> </bean> <!--ehcache--> <bean id="ehcacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> <property name="configLocation" value="classpath:ehcache.xml"/> </bean> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" /> </beans> spring-shiro.xml <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0" metadata-complete="false"> <display-name>gtsys</display-name> <!-- 单点登出 --> <!-- <listener> <listener-class>org.jasig.cas.client.session.SingleSignOutHttpSessionListener</listener-class> </listener> <filter> <filter-name>CAS Single Sign Out Filter</filter-name> <filter-class>org.jasig.cas.client.session.SingleSignOutFilter</filter-class> </filter> <filter-mapping> <filter-name>CAS Single Sign Out Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-shiro.xml,classpath:spring-application.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <listener> <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class> </listener> <filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <async-supported>true</async-supported> <init-param> <param-name>targetFilterLifecycle</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.shtml</url-pattern> </servlet-mapping> <filter> <filter-name>encoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> --> <servlet-mapping> <servlet-name>jsp</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.eot</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.ttf</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.xml</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.swf</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.zip</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.gif</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.jpg</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.png</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.woff</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>login.shtml</welcome-file> </welcome-file-list> </web-app> web.xml ## shiro shiro.session.timeout=1800000 shiro.session.validate.timespan=1800000 # cas\u767B\u5F55URL shiro.login.url=https://localhost:8443/cas-server/login?service=http://securitycenter.com:8080/gtsys/cas # cas logout shiro.logout.url=https://localhost:8443/cas-server/logout?service=http://securitycenter.com:8080/gtsys # cas\u767B\u5F55\u6210\u529F\u8DF3\u8F6CURL shiro.login.success.url=http://securitycenter.com:8080/gtsys/index.shtml # cas\u670D\u52A1\u5668URL shiro.casServer.url=https://localhost:8443/cas-server # \u5BA2\u6237\u7AEFCAS\u767B\u5F55URL shiro.client.cas=http://securitycenter.com:8080/gtsys/cas # \u5BA2\u6237\u7AEFCAS\u9A8C\u8BC1\u5931\u8D25\u8DF3\u8F6CURL shiro.failureUrl=/casFailure.jsp ## dataSource dataSource.driver=com.mysql.jdbc.Driver dataSource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8 dataSource.username=root dataSource.password=1234 properties文件 <?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true" monitoring="autodetect" dynamicConfig="true"> <diskStore path="java.io.tmpdir"/> <!-- <diskStore>==========当内存缓存中对象数量超过maxElementsInMemory时,将缓存对象写到磁盘缓存中(需对象实现序列化接口) * <diskStore path="">==用来配置磁盘缓存使用的物理路径,Ehcache磁盘缓存使用的文件后缀名是*.data和*.index * name=================缓存名称,cache的唯一标识(ehcache会把这个cache放到HashMap里) * maxElementsOnDisk====磁盘缓存中最多可以存放的元素数量,0表示无穷大 * maxElementsInMemory==内存缓存中最多可以存放的元素数量,若放入Cache中的元素超过这个数值,则有以下两种情况 * 1)若overflowToDisk=true,则会将Cache中多出的元素放入磁盘文件中 * 2)若overflowToDisk=false,则根据memoryStoreEvictionPolicy策略替换Cache中原有的元素 * eternal==============缓存中对象是否永久有效,即是否永驻内存,true时将忽略timeToIdleSeconds和timeToLiveSeconds * timeToIdleSeconds====缓存数据在失效前的允许闲置时间(单位:秒),仅当eternal=false时使用,默认值是0表示可闲置时间无穷大,此为可选属性 * 即访问这个cache中元素的最大间隔时间,若超过这个时间没有访问此Cache中的某个元素,那么此元素将被从Cache中清除 * timeToLiveSeconds====缓存数据在失效前的允许存活时间(单位:秒),仅当eternal=false时使用,默认值是0表示可存活时间无穷大 * 即Cache中的某元素从创建到清楚的生存时间,也就是说从创建开始计时,当超过这个时间时,此元素将从Cache中清除 * overflowToDisk=======内存不足时,是否启用磁盘缓存(即内存中对象数量达到maxElementsInMemory时,Ehcache会将对象写到磁盘中) * 会根据标签中path值查找对应的属性值,写入磁盘的文件会放在path文件夹下,文件的名称是cache的名称,后缀名是data * diskPersistent=======是否持久化磁盘缓存,当这个属性的值为true时,系统在初始化时会在磁盘中查找文件名为cache名称,后缀名为index的文件 * 这个文件中存放了已经持久化在磁盘中的cache的index,找到后会把cache加载到内存 * 要想把cache真正持久化到磁盘,写程序时注意执行net.sf.ehcache.Cache.put(Element element)后要调用flush()方法 * diskExpiryThreadIntervalSeconds==磁盘缓存的清理线程运行间隔,默认是120秒 * diskSpoolBufferSizeMB============设置DiskStore(磁盘缓存)的缓存区大小,默认是30MB * memoryStoreEvictionPolicy========内存存储与释放策略,即达到maxElementsInMemory限制时,Ehcache会根据指定策略清理内存 * 共有三种策略,分别为LRU(最近最少使用)、LFU(最常用的)、FIFO(先进先出) --> <!-- 注意,以下缓存是永久有效,是系统初始化数据到缓存中,如果不需要永久有效,请另写,或在 --> <cache name="cache" maxEntriesLocalHeap="10000" maxEntriesLocalDisk="1000" eternal="true" diskSpoolBufferSizeMB="20" timeToIdleSeconds="0" timeToLiveSeconds="0" memoryStoreEvictionPolicy="LFU" transactionalMode="off"> </cache> <!-- 登录记录缓存 锁定10分钟 --> <cache name="passwordRetryCache" maxEntriesLocalHeap="2000" eternal="false" timeToIdleSeconds="600" timeToLiveSeconds="0" overflowToDisk="false" statistics="true"> </cache> <!-- <cache name="authorizationCache" maxEntriesLocalHeap="2000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="0" overflowToDisk="false" statistics="true"> </cache> <cache name="authenticationCache" maxEntriesLocalHeap="2000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="0" overflowToDisk="false" statistics="true"> </cache> --> <cache name="shiro-activeSessionCache" maxEntriesLocalHeap="2000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="0" overflowToDisk="false" statistics="true"> </cache> <cache name="shiro-kickout-session" maxEntriesLocalHeap="2000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="0" overflowToDisk="false" statistics="true"> </cache> </ehcache> ehcache.xml package com.lanyuan.shiro; //import com.github.zhangkaitao.shiro.chapter15.service.UserService; import java.util.List; import javax.inject.Inject; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.cas.CasRealm; import org.apache.shiro.subject.PrincipalCollection; import com.lanyuan.entity.ResFormMap; import com.lanyuan.mapper.ResourcesMapper; import com.lanyuan.mapper.UserMapper; /** * <p>User: Zhang Kaitao * <p>Date: 14-2-13 * <p>Version: 1.0 */ public class MyCasRealm extends CasRealm { // private UserService userService; // // public void setUserService(UserService userService) { // this.userService = userService; // } @Inject private ResourcesMapper resourcesMapper; @Inject private UserMapper userMapper; @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { String username = (String)principals.getPrimaryPrincipal(); // PathMatchingFilterChainResolver SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); //authorizationInfo.setRoles(userService.findRoles(username)); // authorizationInfo.setStringPermissions(userService.findPermissions(username)); String userId = SecurityUtils.getSubject().getSession().getAttribute("userSessionId").toString(); List<ResFormMap> rs = resourcesMapper.findUserResourcess(userId); for (ResFormMap resources : rs) { authorizationInfo.addStringPermission(resources.get("resKey").toString()); } return authorizationInfo; } } MyCasRealm.java ``` ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:util="http://www.springframework.org/schema/util" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <aop:config proxy-target-class="true"></aop:config> <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> <property name="securityManager" ref="securityManager"/> </bean> </beans> spring-mvc-shiro.xml ``` 这个是更改 网上的蓝缘系统的 cas server 和cas client参考的 http://howiefh.github.io/2015/05/19/shiro-cas-single-sign-on/?utm_source=tuicool 不知道为什么会返回404
ffmpeg实现web上视频转码为mp4格式用video标签却无法播放
1.问题描述:调用ffmpeg将avi格式视频转码->mp4格式,使用最简单的<video>标签进行播放只能播放声音,没有画面(黑屏)。而暴风影音等本地视频播放软件却能够正常播放转码后的视频。 2.环境:SSH框架准备实现视频上传后的自动转码并且能够网页内播放,火狐浏览器。 3.已知mp4格式分为两种,其中H264类型才能进行html播放,但按照转码命令说已经转码成:视频H264、音频aac格式了,但是仍然是黑屏(有声音)。 4.未知:(1)转码时显示的相关命令行具体意义。(2)网上所说用格式工厂进行转码即可,有没有能够通过代码调用的视频转码方法予以解决呢? 5.以下为问题截图: (1)视频转码Java代码: ``` List<String> convert = new ArrayList<String>(); convert.add(ffmpegPath); // 添加转换工具路径 convert.add("-i"); // 添加参数"-i",该参数指定要转换的文件 convert.add(sourceVideoPath); // 添加要转换格式的视频文件的路径 convert.add("-acodec"); convert.add("aac"); convert.add("-vcodec"); convert.add("libx264"); convert.add("-y"); convert.add(targetFolder+fileRealNameNoExtension+targetExtension); ``` (2)转码时的输出: ``` ffmpeg version N-93678-g4b7166c9d5 Copyright (c) 2000-2019 the FFmpeg developers built with gcc 8.3.1 (GCC) 20190414 configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libdav1d --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enable-libspeex --enable-libxvid --enable-libaom --enable-libmfx --enable-amf --enable-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --enable-dxva2 --enable-avisynth --enable-libopenmpt libavutil 56. 26.100 / 56. 26.100 libavcodec 58. 52.100 / 58. 52.100 libavformat 58. 27.103 / 58. 27.103 libavdevice 58. 7.100 / 58. 7.100 libavfilter 7. 50.100 / 7. 50.100 libswscale 5. 4.100 / 5. 4.100 libswresample 3. 4.100 / 3. 4.100 libpostproc 55. 4.100 / 55. 4.100 Input #0, avi, from 'E:\Test\projectVideos\temp\1557994804863.avi': Metadata: genre : Other track : 1 encoder : Lavf54.63.104 Duration: 00:00:16.80, start: 0.000000, bitrate: 2286 kb/s Stream #0:0: Video: h264 (Main) (H264 / 0x34363248), yuv420p(progressive), 1920x1080 [SAR 1:1 DAR 16:9], 2151 kb/s, 25 fps, 25 tbr, 25 tbn, 50 tbc Stream #0:1: Audio: mp3 (U[0][0][0] / 0x0055), 44100 Hz, mono, fltp, 128 kb/s Stream mapping: Stream #0:0 -> #0:0 (h264 (native) -> h264 (libx264)) Stream #0:1 -> #0:1 (mp3 (mp3float) -> aac (native)) Press [q] to stop, [?] for help [libx264 @ 0000000002ebf4c0] using SAR=1/1 [libx264 @ 0000000002ebf4c0] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX [libx264 @ 0000000002ebf4c0] profile Progressive High, level 4.0, 4:2:0, 8-bit [libx264 @ 0000000002ebf4c0] 264 - core 157 r2970 5493be8 - H.264/MPEG-4 AVC codec - Copyleft 2003-2019 - http://www.videolan.org/x264.html - options: cabac=1 ref=3 deblock=1:0:0 analyse=0x3:0x113 me=hex subme=7 psy=1 psy_rd=1.00:0.00 mixed_ref=1 me_range=16 chroma_me=1 trellis=1 8x8dct=1 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=-2 threads=6 lookahead_threads=1 sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=3 b_pyramid=2 b_adapt=1 b_bias=0 direct=1 weightb=1 open_gop=0 weightp=2 keyint=250 keyint_min=25 scenecut=40 intra_refresh=0 rc_lookahead=40 rc=crf mbtree=1 crf=23.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=1:1.00 Output #0, mp4, to 'E:\Test\projectVideos\encvideos\1557994804863.mp4': Metadata: genre : Other track : 1 encoder : Lavf58.27.103 Stream #0:0: Video: h264 (libx264) (avc1 / 0x31637661), yuv420p, 1920x1080 [SAR 1:1 DAR 16:9], q=-1--1, 25 fps, 12800 tbn, 25 tbc Metadata: encoder : Lavc58.52.100 libx264 Side data: cpb: bitrate max/min/avg: 0/0/0 buffer size: 0 vbv_delay: -1 Stream #0:1: Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, mono, fltp, 69 kb/s Metadata: encoder : Lavc58.52.100 aac frame= 1 fps=0.0 q=0.0 size= 0kB time=00:00:00.06 bitrate= 5.5kbits/s speed=0.138x frame= 46 fps= 23 q=0.0 size= 0kB time=00:00:01.88 bitrate= 0.2kbits/s speed=0.936x frame= 64 fps= 25 q=28.0 size= 0kB time=00:00:02.57 bitrate= 0.1kbits/s speed=1.02x frame= 88 fps= 29 q=28.0 size= 0kB time=00:00:03.55 bitrate= 0.1kbits/s speed=1.17x frame= 108 fps= 31 q=28.0 size= 0kB time=00:00:04.34 bitrate= 0.1kbits/s speed=1.23x frame= 133 fps= 33 q=28.0 size= 0kB time=00:00:05.34 bitrate= 0.1kbits/s speed=1.32x frame= 155 fps= 34 q=28.0 size= 0kB time=00:00:06.22 bitrate= 0.1kbits/s speed=1.35x frame= 171 fps= 33 q=28.0 size= 0kB time=00:00:06.87 bitrate= 0.1kbits/s speed=1.33x frame= 186 fps= 33 q=28.0 size= 0kB time=00:00:07.47 bitrate= 0.1kbits/s speed=1.32x frame= 195 fps= 31 q=28.0 size= 0kB time=00:00:07.82 bitrate= 0.0kbits/s speed=1.25x frame= 206 fps= 30 q=28.0 size= 0kB time=00:00:08.26 bitrate= 0.0kbits/s speed=1.22x frame= 214 fps= 29 q=28.0 size= 0kB time=00:00:08.59 bitrate= 0.0kbits/s speed=1.17x frame= 223 fps= 28 q=28.0 size= 0kB time=00:00:08.96 bitrate= 0.0kbits/s speed=1.14x frame= 229 fps= 27 q=28.0 size= 0kB time=00:00:09.19 bitrate= 0.0kbits/s speed=1.09x frame= 232 fps= 25 q=28.0 size= 0kB time=00:00:09.28 bitrate= 0.0kbits/s speed=1.01x frame= 235 fps= 24 q=28.0 size= 256kB time=00:00:09.42 bitrate= 222.5kbits/s speed=0.965x frame= 240 fps= 23 q=28.0 size= 256kB time=00:00:09.63 bitrate= 217.7kbits/s speed=0.928x frame= 243 fps= 22 q=28.0 size= 256kB time=00:00:09.72 bitrate= 215.6kbits/s speed=0.894x frame= 247 fps= 21 q=28.0 size= 256kB time=00:00:09.89 bitrate= 212.1kbits/s speed=0.856x frame= 253 fps= 21 q=28.0 size= 512kB time=00:00:10.12 bitrate= 414.3kbits/s speed=0.832x frame= 258 fps= 20 q=28.0 size= 512kB time=00:00:10.33 bitrate= 406.0kbits/s speed=0.812x frame= 264 fps= 20 q=28.0 size= 512kB time=00:00:10.56 bitrate= 397.0kbits/s speed=0.791x frame= 268 fps= 19 q=28.0 size= 768kB time=00:00:10.72 bitrate= 586.5kbits/s speed=0.773x frame= 272 fps= 19 q=28.0 size= 768kB time=00:00:10.91 bitrate= 576.5kbits/s speed=0.753x frame= 278 fps= 19 q=28.0 size= 768kB time=00:00:11.14 bitrate= 564.5kbits/s speed=0.743x frame= 281 fps= 18 q=28.0 size= 768kB time=00:00:11.26 bitrate= 558.7kbits/s speed=0.725x frame= 286 fps= 18 q=28.0 size= 1024kB time=00:00:11.47 bitrate= 731.3kbits/s speed=0.715x frame= 291 fps= 17 q=28.0 size= 1024kB time=00:00:11.67 bitrate= 718.3kbits/s speed=0.701x frame= 296 fps= 17 q=25.0 size= 1024kB time=00:00:11.86 bitrate= 707.0kbits/s speed=0.687x frame= 303 fps= 17 q=28.0 size= 1280kB time=00:00:12.14 bitrate= 863.5kbits/s speed=0.681x frame= 308 fps= 17 q=28.0 size= 1280kB time=00:00:12.35 bitrate= 848.9kbits/s speed=0.67x frame= 312 fps= 16 q=28.0 size= 1280kB time=00:00:12.51 bitrate= 837.8kbits/s speed=0.661x frame= 319 fps= 16 q=28.0 size= 1280kB time=00:00:12.79 bitrate= 819.6kbits/s speed=0.658x frame= 341 fps= 17 q=28.0 size= 1280kB time=00:00:13.65 bitrate= 768.0kbits/s speed=0.684x frame= 362 fps= 18 q=28.0 size= 1280kB time=00:00:14.48 bitrate= 723.7kbits/s speed=0.708x frame= 391 fps= 19 q=28.0 size= 1280kB time=00:00:15.67 bitrate= 669.0kbits/s speed=0.746x frame= 419 fps= 19 q=28.0 size= 1280kB time=00:00:16.67 bitrate= 629.0kbits/s speed=0.774x frame= 419 fps= 19 q=-1.0 Lsize= 1538kB time=00:00:16.71 bitrate= 753.7kbits/s speed=0.753x video:1480kB audio:43kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.976535% [libx264 @ 0000000002ebf4c0] frame I:2 Avg QP:13.37 size: 32816 [libx264 @ 0000000002ebf4c0] frame P:143 Avg QP:14.70 size: 6977 [libx264 @ 0000000002ebf4c0] frame B:274 Avg QP:13.65 size: 1647 [libx264 @ 0000000002ebf4c0] consecutive B-frames: 9.8% 7.6% 4.3% 78.3% [libx264 @ 0000000002ebf4c0] mb I I16..4: 38.7% 53.1% 8.1% [libx264 @ 0000000002ebf4c0] mb P I16..4: 17.5% 18.5% 0.2% P16..4: 5.5% 0.4% 0.2% 0.0% 0.0% skip:57.7% [libx264 @ 0000000002ebf4c0] mb B I16..4: 2.0% 0.7% 0.0% B16..8: 3.7% 0.2% 0.0% direct: 2.9% skip:90.5% L0:49.2% L1:48.4% BI: 2.4% [libx264 @ 0000000002ebf4c0] 8x8 transform intra:48.1% inter:84.8% [libx264 @ 0000000002ebf4c0] coded y,uvDC,uvAC intra: 3.9% 31.3% 4.5% inter: 0.7% 5.4% 0.2% [libx264 @ 0000000002ebf4c0] i16 v,h,dc,p: 22% 68% 4% 6% [libx264 @ 0000000002ebf4c0] i8 v,h,dc,ddl,ddr,vr,hd,vl,hu: 29% 27% 42% 0% 0% 0% 0% 0% 0% [libx264 @ 0000000002ebf4c0] i4 v,h,dc,ddl,ddr,vr,hd,vl,hu: 31% 28% 24% 2% 4% 3% 4% 2% 3% [libx264 @ 0000000002ebf4c0] i8c dc,h,v,p: 48% 39% 11% 2% [libx264 @ 0000000002ebf4c0] Weighted P-Frames: Y:23.1% UV:22.4% [libx264 @ 0000000002ebf4c0] ref P L0: 65.5% 9.2% 23.1% 1.9% 0.3% [libx264 @ 0000000002ebf4c0] ref B L0: 71.1% 28.4% 0.5% [libx264 @ 0000000002ebf4c0] ref B L1: 98.8% 1.2% [libx264 @ 0000000002ebf4c0] kb/s:723.03 [aac @ 0000000002dc0980] Qavg: 47784.133 生成mp4视频为:E:\Test\projectVideos\temp\1557994804863.mp4 ``` (3)播放时的截图 ![图片说明](https://img-ask.csdn.net/upload/201905/16/1557997780_707491.png) (4) 播放视频jsp代码(使用的是video-js,但测试时也试了一下不加视频插件直接<video>标签播放,结果一样) ``` <video id="playVideo" class="video-js vjs-default-skin" controls ="true" preload="auto" width="960" height="480" poster="/images/${VIDEO.vpicture}" data-setup='{}'> <source src="/videos/${VIDEO.vpath}" type='video/mp4' /> </video> ``` ("/videos"为虚拟路径 实为本地存储地址) 希望好心人能够予以慷慨解答!~ 补充:在转wmv格式到MP4格式时出现了 ``` ConverVideoTest说:传入工具类的源视频为:E:\Test\projectVideos\temp\1558578421815.wmv ----接收到文件(E:\Test\projectVideos\temp\1558578421815.wmv)需要转换------- ----开始转文件(E:\Test\projectVideos\temp\1558578421815.wmv)-------------------------- 源视频类型为:wmv 可以转换,统一转为mp4文件 调用了ffmpeg.exe工具 该文件夹存在。 ffmpeg输入的命令:E:\ffmpeg\bin\ffmpeg.exe-iE:\Test\projectVideos\temp\1558578421815.wmv-acodecaac-vcodeclibx264-yE:\Test\projectVideos\encvideos\1558578421815.mp4 ffmpeg version N-93678-g4b7166c9d5 Copyright (c) 2000-2019 the FFmpeg developers built with gcc 8.3.1 (GCC) 20190414 configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libdav1d --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enable-libspeex --enable-libxvid --enable-libaom --enable-libmfx --enable-amf --enable-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --enable-dxva2 --enable-avisynth --enable-libopenmpt libavutil 56. 26.100 / 56. 26.100 libavcodec 58. 52.100 / 58. 52.100 libavformat 58. 27.103 / 58. 27.103 libavdevice 58. 7.100 / 58. 7.100 libavfilter 7. 50.100 / 7. 50.100 libswscale 5. 4.100 / 5. 4.100 libswresample 3. 4.100 / 3. 4.100 libpostproc 55. 4.100 / 55. 4.100 Input #0, asf, from 'E:\Test\projectVideos\temp\1558578421815.wmv': Metadata: DeviceConformanceTemplate: M1 WMFSDKNeeded : 0.0.0.0000 WM/WMADRCPeakReference: 7851 WM/WMADRCPeakTarget: 7851 WM/WMADRCAverageReference: 1027 WM/WMADRCAverageTarget: 1027 WMFSDKVersion : 12.0.7601.17514 IsVBR : 0 Duration: 00:00:16.58, bitrate: 1969 kb/s Stream #0:0(chi): Audio: wmapro (b[1][0][0] / 0x0162), 48000 Hz, stereo, fltp, 256 kb/s Stream #0:1(chi): Video: vc1 (Advanced) (WVC1 / 0x31435657), yuv420p, 1352x696 [SAR 1:1 DAR 169:87], 3400 kb/s, 30 tbr, 1k tbn, 60 tbc Stream mapping: Stream #0:1 -> #0:0 (vc1 (native) -> h264 (libx264)) Stream #0:0 -> #0:1 (wmapro (native) -> aac (native)) Press [q] to stop, [?] for help [libx264 @ 0000000000531c80] using SAR=1/1 [libx264 @ 0000000000531c80] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX [libx264 @ 0000000000531c80] profile Progressive High, level 3.2, 4:2:0, 8-bit [libx264 @ 0000000000531c80] 264 - core 157 r2970 5493be8 - H.264/MPEG-4 AVC codec - Copyleft 2003-2019 - http://www.videolan.org/x264.html - options: cabac=1 ref=3 deblock=1:0:0 analyse=0x3:0x113 me=hex subme=7 psy=1 psy_rd=1.00:0.00 mixed_ref=1 me_range=16 chroma_me=1 trellis=1 8x8dct=1 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=-2 threads=6 lookahead_threads=1 sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=3 b_pyramid=2 b_adapt=1 b_bias=0 direct=1 weightb=1 open_gop=0 weightp=2 keyint=250 keyint_min=25 scenecut=40 intra_refresh=0 rc_lookahead=40 rc=crf mbtree=1 crf=23.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=1:1.00 frame= 11 fps=0.0 q=0.0 size= 0kB time=-577014:32:22.77 bitrate= -0.0kbits/s dup=1 drop=0 speed=N/A frame= 52 fps= 48 q=0.0 size= 0kB time=-577014:32:22.77 bitrate= -0.0kbits/s dup=1 drop=0 speed=N/A frame= 85 fps= 54 q=0.0 size= 0kB time=-577014:32:22.77 bitrate= -0.0kbits/s dup=1 drop=0 speed=N/A frame= 145 fps= 64 q=0.0 size= 0kB time=-577014:32:22.77 bitrate= -0.0kbits/s dup=47 drop=0 speed=N/A frame= 171 fps= 61 q=0.0 size= 0kB time=-577014:32:22.77 bitrate= -0.0kbits/s dup=55 drop=0 speed=N/A Too many packets buffered for output stream 0:0. [libx264 @ 0000000000531c80] frame I:2 Avg QP:15.28 size: 56950 [libx264 @ 0000000000531c80] frame P:34 Avg QP:14.18 size: 1252 [libx264 @ 0000000000531c80] frame B:93 Avg QP:15.53 size: 140 [libx264 @ 0000000000531c80] consecutive B-frames: 3.1% 1.6% 2.3% 93.0% [libx264 @ 0000000000531c80] mb I I16..4: 14.9% 79.5% 5.6% [libx264 @ 0000000000531c80] mb P I16..4: 0.7% 1.1% 0.0% P16..4: 4.1% 1.4% 1.3% 0.0% 0.0% skip:91.4% [libx264 @ 0000000000531c80] mb B I16..4: 0.0% 0.0% 0.0% B16..8: 3.6% 0.0% 0.0% direct: 0.0% skip:96.4% L0:36.8% L1:63.2% BI: 0.0% [libx264 @ 0000000000531c80] 8x8 transform intra:74.4% inter:80.1% [libx264 @ 0000000000531c80] coded y,uvDC,uvAC intra: 38.4% 33.4% 20.3% inter: 0.5% 0.2% 0.0% [libx264 @ 0000000000531c80] i16 v,h,dc,p: 61% 25% 9% 6% [libx264 @ 0000000000531c80] i8 v,h,dc,ddl,ddr,vr,hd,vl,hu: 32% 31% 21% 2% 3% 3% 3% 3% 3% [libx264 @ 0000000000531c80] i4 v,h,dc,ddl,ddr,vr,hd,vl,hu: 27% 32% 14% 4% 5% 5% 5% 4% 6% [libx264 @ 0000000000531c80] i8c dc,h,v,p: 76% 13% 8% 4% [libx264 @ 0000000000531c80] Weighted P-Frames: Y:0.0% UV:0.0% [libx264 @ 0000000000531c80] ref P L0: 85.1% 6.8% 6.5% 1.6% [libx264 @ 0000000000531c80] ref B L0: 48.1% 47.5% 4.4% [libx264 @ 0000000000531c80] ref B L1: 93.2% 6.8% [libx264 @ 0000000000531c80] kb/s:315.41 **Conversion failed!** 生成mp4视频为:E:\Test\projectVideos\temp1558578421815.mp4 ===========视频转码结束,开始截图================= 该文件夹存在。 截图命令:E:\ffmpeg\bin\ffmpeg.exe-ss00:00:01-iE:\Test\projectVideos\temp\1558578421815.wmv-y-fimage2-s154x90E:\Test\projectVideos\images\1558578421815.jpg ffmpeg version N-93678-g4b7166c9d5 Copyright (c) 2000-2019 the FFmpeg developers built with gcc 8.3.1 (GCC) 20190414 configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libdav1d --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enable-libspeex --enable-libxvid --enable-libaom --enable-libmfx --enable-amf --enable-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --enable-dxva2 --enable-avisynth --enable-libopenmpt libavutil 56. 26.100 / 56. 26.100 libavcodec 58. 52.100 / 58. 52.100 libavformat 58. 27.103 / 58. 27.103 libavdevice 58. 7.100 / 58. 7.100 libavfilter 7. 50.100 / 7. 50.100 libswscale 5. 4.100 / 5. 4.100 libswresample 3. 4.100 / 3. 4.100 libpostproc 55. 4.100 / 55. 4.100 Input #0, asf, from 'E:\Test\projectVideos\temp\1558578421815.wmv': Metadata: DeviceConformanceTemplate: M1 WMFSDKNeeded : 0.0.0.0000 WM/WMADRCPeakReference: 7851 WM/WMADRCPeakTarget: 7851 WM/WMADRCAverageReference: 1027 WM/WMADRCAverageTarget: 1027 WMFSDKVersion : 12.0.7601.17514 IsVBR : 0 Duration: 00:00:16.58, bitrate: 1969 kb/s Stream #0:0(chi): Audio: wmapro (b[1][0][0] / 0x0162), 48000 Hz, stereo, fltp, 256 kb/s Stream #0:1(chi): Video: vc1 (Advanced) (WVC1 / 0x31435657), yuv420p, 1352x696 [SAR 1:1 DAR 169:87], 3400 kb/s, 30 tbr, 1k tbn, 60 tbc Stream mapping: Stream #0:1 -> #0:0 (vc1 (native) -> mjpeg (native)) Press [q] to stop, [?] for help [swscaler @ 0000000002ecd4c0] deprecated pixel format used, make sure you did set range correctly Output #0, image2, to 'E:\Test\projectVideos\images\1558578421815.jpg': Metadata: DeviceConformanceTemplate: M1 WMFSDKNeeded : 0.0.0.0000 WM/WMADRCPeakReference: 7851 WM/WMADRCPeakTarget: 7851 WM/WMADRCAverageReference: 1027 WM/WMADRCAverageTarget: 1027 WMFSDKVersion : 12.0.7601.17514 IsVBR : 0 encoder : Lavf58.27.103 Stream #0:0(chi): Video: mjpeg, yuvj420p(pc), 154x90 [SAR 2535:2233 DAR 169:87], q=2-31, 200 kb/s, 30 fps, 30 tbn, 30 tbc Metadata: encoder : Lavc58.52.100 mjpeg Side data: cpb: bitrate max/min/avg: 0/0/200000 buffer size: 0 vbv_delay: -1 [image2 @ 0000000000628e00] Could not get frame filename number 2 from pattern 'E:\Test\projectVideos\images\1558578421815.jpg'. Use '-frames:v 1' for a single image, or '-update' option, or use a pattern such as %03d within the filename. av_interleaved_write_frame(): Invalid argument frame= 2 fps=0.0 q=1.6 size=N/A time=00:00:00.06 bitrate=N/A speed=0.102x frame= 2 fps=0.0 q=1.6 Lsize=N/A time=00:00:00.06 bitrate=N/A speed=0.097x video:3kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: unknown Conversion failed! 截图进程结束 截图成功! ``` 即出现了Conversion failed!!!
js中的加法出现问题 代码如下
``` <!DOCTYPE html> <html lang="zh-cmn-Hans"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1"> <title>事件</title> <meta name="keywords" content="关键词列表" /> <meta name="description" content="网页描述" /> <link rel="stylesheet" type="text/css" href="" /> <!--<script type="text/javascript" src="JS文件路径"></script>--> <script type="text/javascript"> function count(){ //获取第一个输入框的值 //获取第二个输入框的值 //获取选择框的值 //获取通过下拉框来选择的值来改变加减乘除的运算法则 //设置结果输入框的值 var a = document.getElementById("txt1").value; var b = document.getElementById("txt2").value; var c = document.getElementById("select").value; var d = ''; switch(c) { case "+": d = a + b; break; case "-": d= a - b; break; case "*": d = a * b; break; case "/": d = a / b; break; } document.getElementById('fruit').value = d; } </script> </head> <body> <input type="text" id="txt1" /> <select id="select"> <option value="+">+</option> <option value="-">-</option> <option value="*">*</option> <option value="/">/</option> </select> <input type="text" id="txt2" /> <input type="button" value="=" onclick="count()" /> <!-- 通过 = 按钮来调用创建的函数,得到结果 --> <input type="text" id="fruit" /> </body> </html> ``` 除了加法 其他的都正常
一个关于JSON传递数据的问题
(可能涉及的方面比较多,不知道是不是应该放这个区) 最近在学YUI,里面的dataSource和dataTable,看他的[url=http://developer.yahoo.com/yui/examples/datatable/dt_dynamicdata.html]演示[/url]很爽的样子,于是就想把它和ROR结合起来,但在尝试服务器端分页的时候出了问题,说data error。 现在困惑我的是,以下几点我都不是很懂: 1.ROR生成的JSON格式是不是“对的”? 因为看到了很多种生成JSON的方法,有直接to_json的,还有gem install json之后再parse的,甚至还有一个修正“ruby生成的JSON不带引号”问题的方法[code="ruby"]ActiveSupport::JSON.unquote_hash_key_identifiers = false[/code] Google的时候还看到有的说是render :text => "xxx",有的说是render :json => "xxx",也不知道到底听谁的…… 还有这样的: [code="ruby"]irb(main):001:0> Product.find(:all).to_json => "[\"#<Product:0x4711cf0>\",\"#<Product:0x4711cc8>\",\"#<Product:0x4711ca0>\",\"#<Product:0x4711c78>\",\"#<Product:0x4711c50>\",\"#<Product:0x4711c28>\",\"#<Product:0x4711c00>\",\"#<Product:0x4711bd8>\"]"[/code] 所以,问题一是:[color=darkred][b]怎么才能用ROR生成出标准的JSON格式来啊?[/b][/color] 2.JS里调用,YUI用的是PHP版: [code="javascript"] var myDataSource = new YAHOO.util.DataSource("assets/php/json_proxy.php?"); [/code] 我试图调用它来当试验数据,但不行,貌似是它只能站内引用; 我又试图下载这个文件来研究,但下载下来只是一个文本形式的东东,感觉下载下来的已经是输出结果了。 也有人写过JAVA版的,但问题同上…… 我也找到过ROR版的调用,说是这样: [code="javascript"] var myDataSource = new YAHOO.util.DataSource("http://localhost:3000/product/list/index.json?"); [/code] 同时在Controller里写: [code="ruby"] @products = Product.find(:all) respond_to do |format| format.html format.xml { render :xml => @products } format.json { render :text => @products } end [/code] 但由于不知道:text对还是:json对,并且无论我用哪种,生成出来的都会有奇怪的属性而导致跟YUI的例子生成的结果格式不一样…… 所以,问题二是:[color=red][b]在YUI(或者说Javascript)那边,应该怎么调用“用ROR生成好的JSON数据”呢?[/b][/color] (其实在YUI里面还有问题,不过如果先把这两点最大的疑惑弄清楚,剩下的就可以自行研究了……)
新手Echarts问题:为什么官网有些案例无法直接调用?
因为工作需要,公司最近需要我们去调用一下echarts。 因为以前没有用过echarts,只好先去学习一下。 今天在测试echarts时却发现了一个问题: 官网发的大部分案例都可以直接复制执行,还有一些是需要json文件的暂且不论。 今天测试的这个,我看过代码没有调用json文件的记录,却还是显示一片空白。 echarts环境:echarts用的是官网的2.08M的源码包,浏览器是 firfox. ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>test</title> <script src="echarts.js"></script> </head> <body> <div id="charts" style="position: absolute;width: 80%;height: 80%;"> </div> </body> <script> var charts=echarts.init(document.getElementById('charts')); //为了代码可读性,我把系统给的数据全部以 data 代替 var data0 = [ data ]; var data = [ data ]; // See https://github.com/ecomfe/echarts-stat var myRegression = ecStat.regression('logarithmic', data); myRegression.points.sort(function(a, b) { return a[0] - b[0]; }); option = { legend: { data: ['1990', '2015'], bottom: 20 }, title: { text: '1990 and 2015 per capita life expectancy and GDP', subtext: 'By ecStat.regression', sublink: 'https://github.com/ecomfe/echarts-stat', left: 'center' }, tooltip: { trigger: 'axis', axisPointer: { type: 'cross' } }, grid: { top: 80, bottom: 90 }, xAxis: { type: 'value', splitLine: { lineStyle: { type: 'dashed' } }, }, yAxis: { type: 'value', splitLine: { lineStyle: { type: 'dashed' } }, }, series: [{ name: '1990', type: 'scatter', symbolSize: function(data) { return Math.sqrt(data[2]) / 5e2; }, label: { emphasis: { show: true, formatter: function(param) { return param.data[3]; }, position: 'top' } }, itemStyle: { normal: { shadowBlur: 10, shadowColor: 'rgba(120, 36, 50, 0.5)', shadowOffsetY: 5, color: new echarts.graphic.RadialGradient(0.4, 0.3, 1, [{ offset: 0, color: 'rgb(251, 118, 123)' }, { offset: 1, color: 'rgb(204, 46, 72)' }]) } }, data: data0 }, { name: '2015', type: 'scatter', symbolSize: function(data) { return Math.sqrt(data[2]) / 5e2; }, label: { emphasis: { show: true, formatter: function(param) { return param.data[3]; }, position: 'top' } }, itemStyle: { normal: { shadowBlur: 10, shadowColor: 'rgba(25, 100, 150, 0.5)', shadowOffsetY: 5, color: new echarts.graphic.RadialGradient(0.4, 0.3, 1, [{ offset: 0, color: 'rgb(129, 227, 238)' }, { offset: 1, color: 'rgb(25, 183, 207)' }]) } }, data: data1 }, { name: 'line', type: 'line', lineStyle: { normal: { color: '#2f4554' } }, smooth: true, showSymbol: false, data: myRegression.points, markPoint: { itemStyle: { normal: { color: 'transparent' } }, label: { normal: { show: true, position: 'left', formatter: myRegression.expression, textStyle: { color: '#333', fontSize: 14 } } }, data: [{ coord: myRegression.points[myRegression.points.length - 1] }] } }] }; charts.setOption(option); </script> </html> ``` 如果我数据的修改影响了判断,这里是源码--->[Echarts代码源码](https://echarts.baidu.com/examples/editor.html?c=scatter-logarithmic-regression "")
highchart实时刷新数据,x轴不显示所需时间
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default1.aspx.cs" Inherits="HighchartsDemo._Default1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>汽油吸附脱硫装置2#S-ZORB</title> <!-- 注意文件名应该和你下载的文件名保持一致 --> <script type="text/javascript"src="HighCharts/jquery-1.8.3.min.js"></script> <script type="text/javascript"src="HighCharts/highcharts.js"></script> <script type="text/javascript"src="HighCharts/TimeConvertor.js"></script> </head> <body> <script type="text/javascript"> //<![CDATA[ $(function (datetimeCom, growth) { // Highcharts.Chart Begin Highcharts.setOptions({ global: { useUTC: false //当X轴类型为datetime日期时间型的,需要设置时区 } }); //声明报表对象 var chart = new Highcharts.Chart({ chart: { //将报表对象渲染到层上 renderTo: 'container', //图表放置的容器,DIV defaultSeriesType: 'spline', //图表类型为曲线图,可取值有:line、spline、area、areaspline、bar、column等 events: { load: loadTime } }, //chart end title: { text: '汽油吸附脱硫装置2#S-ZORB曲线' }, yAxis: { title: { text: '2#S-ZORB实时值' } }, xAxis: { title: { text: '时间' }, type: 'datetime', //坐标间隔 labels: { step: 10, // formatter: function () { // return Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.value); // } } }, //鼠标放在某个点上时的提示信息 //dateFormat,numberFormat是highCharts的工具类 tooltip: { formatter: function () { return '<b>' + this.series.name + '</b><br/>' + Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.xtime) + '<br/>' + this.x + '<br/>' + Highcharts.numberFormat(this.y, 2); } }, //设定报表对象的初始数据 series: [{ name: '2#S-ZORB实时值', data: [] }] }); //获取初始化数据 getInitialData(); //Highcharts.Chart end //获取初始化30分钟数据 function getInitialData() { $.ajax({ type: "Post", //后台获取数据的函数,注意当对该页面重命名时, //必须手动更改该选项 url: "Default1.aspx/getInitialDataByAjax", contentType: "application/json;charset=utf-8", dataType: "json", //成功获取数据 success: function (result) { data = jQuery.parseJSON(result.d); //JSON再次转换为Table 形式; var datetimeCom = '['; var growth = '['; for (var i = 0; i < data.length; i++) { datetimeCom += "\'" + ConertJsonTimeAndFormat(data[i]["x"], 'yyyy/MM/dd hh:mm:ss') + "\',"; growth += data[i]["y"] + ","; } if (datetimeCom != '[') { datetimeCom = datetimeCom.substr(0, datetimeCom.length - 1) + "]"; growth = growth.substr(0, growth.length - 1) + "]"; } chart.xAxis[0].setCategories(eval(datetimeCom)); chart.series[0].setData(eval(growth)); //显示错误 }, error: function (err) { alert(err + "初始化程序出现错误,请尝试刷新!"); } }); } // 每分钟获取后台数据 function getActualData() { var x = (new Date()).getTime(); // 当前时间 $.ajax({ type: "Post", //后台获取数据的函数,注意当对该页面重命名时, //必须手动更改该选项 url: "Default1.aspx/getDataTableByAjax", contentType: "application/json;charset=utf-8", dataType: "json", //成功获取数据 success: function (result) { data = jQuery.parseJSON(result.d); //JSON再次转换为Table 形式; var series = chart.series[0]; series.addPoint([data[0]["x"], data[0]["y"]], false, true); // alert(data[0]["x"]); // var datetimeCom = '['; // for (var i = 0; i < data.length; i++) { // datetimeCom += "\'" + data[i]["x"] + "\',"; // } // if (datetimeCom != '[') { // datetimeCom = datetimeCom.substr(0, datetimeCom.length - 1) + "]"; // } // chart.xAxis[0].setCategories(eval(datetimeCom)); chart.redraw(); }, //显示错误 error: function (err) { alert(err + "调用后台程序出现错误,请尝试刷新!"); } }); } function loadTime() { window.setInterval(getActualData, 2000); } // $(document).ready(function () { // //每隔1分钟自动调用方法,实现图表的实时更新 60000 // window.setInterval(getActualData, 2000); // }); }); //]]> // 后台Date前台转换json格式 function JsonDateFormat(cellval) { var date = new Date(parseInt(cellval.replace("/Date(", "").replace(")/", ""), 10)); var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1; var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate(); return date.getFullYear() + "-" + month + "-" + currentDate; } </script> <div id="container" style="width: 800px; height: 600px; margin: 0 auto"></div> </body> </html> 后台传入数据格式为DataTable。 在线等啊,请高手指教!!!
请教一个JVM内存优化的问题
<p>自己写的一个WEB爬虫程序,程序方面的优化我自己感觉做的不错了,各种对象的使用都想办法不让内存浪费。 <br />但还是吃内存吃的很厉害 <br />我想主要的消耗在于,对于每一个爬下来的网页,都要变成String在内存中分析超链接,这个估计很大。 <br />另外对于每一个分析到的URL,都需要保存起来。 <br /><br /><br />我当前使用的内存优化参数如下 <br />-Xms1024M -Xmx1024M -Xmn512M -Xss128K -XX:+UseParallelGC -XX:ParallelGCThreads=20 -XX:+UseParallelOldGC -XX:MaxPermSize=128M -XX:NewSize=128M -XX:MaxNewSize=128M -XX:SurvivorRatio=8 <br /><br />机器内存是1G。。上面那堆参数,除了最大最小堆内存我也是不求甚解,不是非常明白我设置了什么。网上搜答案也是五花八门,希望大家能推荐一个内存优化参数的文章 <br />另外我上面设置的参数有哪些方面可以优化,或者哪些地方写的不对。 <br /><br />核心的代码我都贴到下面:(我是刚入门的菜鸟,大家别笑话我写的差哦) <br /><br />这个是主类,负责控制,那个monitor大家就当做System.out.println,其实就是</p> <pre name="code" class="java">package com.wood.core; import java.util.concurrent.*; import java.util.*; import com.wood.core.monitor.*; public class CrawlerController implements Runnable { //一个类,用来管理URL,由各抓取线程共享 private URLMap urlmap; //已成功处理URL总数 private int count; //目标完成任务总数 private int total; //管理所有的抓取线程,必要时进行关闭,由于抓取线程存在I/O读取,而I/0读取中的线程是不可中断的,需调用线程的cancel函数 private Crawler[] crawlers; //线程工厂,可以监视产生的线程工作状态 private CrawlerFactory factory; //线程数目 private int threadMax; //当前活动线程 private int threadActive; //线程执行器 private ExecutorService exec; //当系统关闭时取消 private boolean canceled; public CrawlerController(String seed) { this(seed,20,10000); } public CrawlerController(List&lt;string&gt; seeds) { this(seeds,20,10000); } public CrawlerController(String seed,int threadNum) { this(seed,threadNum,10000); } public CrawlerController(List&lt;string&gt; seeds,int threadNum) { this(seeds,threadNum,10000); } public CrawlerController(String seed,int threadNum,int total) { //初始化URLMap,保存抓取启始位置 urlmap=new URLMap(seed); init(threadNum, total); } public CrawlerController(List&lt;string&gt; seeds,int threadNum,int total) { urlmap=new URLMap(seeds); init(threadNum, total); } //构造 private void init(int threadNum,int total) { //初始完成URL总数为0 count=0; //设置目标完成总数 this.total=total; threadMax=threadNum; threadActive=threadNum; //初始化工作线程 crawlers=new Crawler[threadMax]; String id="Crawler "; for(int i=0;i&lt;threadmax;i++) crawlers[i]="new" crawler(id+(i+1),this,urlmap);="" factory="new" crawlerfactory();="" exec="Executors.newCachedThreadPool(factory);" canceled="false;" }="" 检查当前工作线程状态,并打印系统状态="" private="" boolean="" check()="" {="" if(canceled)="" return="" false;="" int="" count="getCount();" if(count=""&gt;total) { MonitorHolder.getMonitor().print("已抓取"+COUNT+"页面,完成目标任务"+total+"页面\n"); cancel(); return false; } threadActive=factory.getActive(); /*if(threadActive&lt;=0) { MonitorHolder.getMonitor().print("无活动工作线程,抓取任务提前结束\n"); cancel(); return false; }*/ MonitorHolder.getMonitor().print_status("统计信息:成功抓取"+COUNT+"页面,当前活动线程为"+threadActive+"个\n"); return true; } //结束抓取 public void cancel() { //调用每个抓取线程的离开方法 for(Crawler cw:crawlers) cw.cancel(); //销毁工厂 factory.destory(); exec.shutdownNow(); MonitorHolder.getMonitor().print("成功结束抓取工作,共抓取"+getCount()+"页面\n"); this.canceled=true; } public synchronized void count() { count++; } public synchronized int getCount() { return count; } public int getTotal() { return total; } public URLMap getMap() { return urlmap; } @Override public void run() { while(!Thread.currentThread().isInterrupted() &amp;&amp; !canceled) { try { MonitorHolder.getMonitor().print("初始化完毕\n"); MonitorHolder.getMonitor().print("开始抓取工作\n"); for(Crawler cw:crawlers) exec.execute(cw); int check_count=0; while (check()){ TimeUnit.SECONDS.sleep(5); check_count++; if(check_count==24) { //每2分钟把待处理URL队列打乱一次 urlmap.shuffle(); MonitorHolder.getMonitor().print("控制信息!!!待抓取URL顺序将打乱\n"); check_count=0; System.gc(); } } } catch (InterruptedException e) { MonitorHolder.getMonitor().print("抓取工作被中断\n"); cancel(); } } } public static void main(String[] args) { List&lt;string&gt; seeds=new ArrayList&lt;string&gt;(15); //问问的各个分类 seeds.add("http://wenwen.soso.com/"); seeds.add("http://wenwen.soso.com/z/c1879048192.htm"); seeds.add("http://wenwen.soso.com/z/c1090519040.htm"); seeds.add("http://wenwen.soso.com/z/c1627389952.htm"); seeds.add("http://wenwen.soso.com/z/c855638016.htm"); seeds.add("http://wenwen.soso.com/z/c1191182336.htm"); seeds.add("http://wenwen.soso.com/z/c1191182336.htm"); seeds.add("http://wenwen.soso.com/z/c620756992.htm"); seeds.add("http://wenwen.soso.com/z/c553648128.htm"); seeds.add("http://wenwen.soso.com/z/c385875968.htm"); seeds.add("http://wenwen.soso.com/z/c687865856.htm"); seeds.add("http://wenwen.soso.com/z/c16777216.htm"); seeds.add("http://wenwen.soso.com/z/c318767104.htm"); seeds.add("http://wenwen.soso.com/z/c150994944.htm"); seeds.add("http://wenwen.soso.com/z/c922746880.htm"); seeds.add("http://wenwen.soso.com/z/c83886080.htm"); CrawlerController controller=new CrawlerController(seeds,5,2000000); List&lt;string&gt; format=new ArrayList&lt;string&gt;(10); //问问回答问题的格式 format.add("http://wenwen.soso.com/z/q"); controller.getMap().addLimit(format); Thread thread=new Thread(controller); thread.start(); } } </pre> <p><br /></p> <pre name="code" class="java">package com.wood.core; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.regex.*; import java.io.*; import java.net.*; import com.wood.core.monitor.*; public class Crawler implements Runnable { //抓取线程ID private String id; //控制器 private CrawlerController controller; //URL,供各线程共享 private URLMap urlmap; private boolean canceled; //保存抓取的网页内容,用于分析超链接 private String content; //字符集 private String charset; //匹配超链接的正则表达式 private String link_reg="&lt;a\\s+(.*?)href\\s*=\\s*\"?(.*?)[\"(\\s*?)](.*?)&gt;"; private Pattern link_pattern=Pattern.compile(link_reg,Pattern.CASE_INSENSITIVE); //匹配字符集的正则表达式 private String charset_reg="&lt;meta\\s+http-equiv=\"content-type\"\\s+content=\"text html;="" charset="(.*?)\&amp;quot;(.*?)"&gt; "; private Pattern charset_pattern=Pattern.compile(charset_reg, Pattern.CASE_INSENSITIVE); private Pattern dir_path_pattern=Pattern.compile("^\\w+$", Pattern.CASE_INSENSITIVE); //保存当前抓取的URL的主机 private String host; //生成待建立的文件夹名 private String host_path; //抓取网页的根目录 private String root_path="E:\\web"; private File root_dir=new File(root_path); //输入来自URL,输出到文件 private InputStreamReader in=null; private OutputStreamWriter out=null; //输入输出缓冲区 private char[] buf=new char[10240]; //网页内容缓冲区 private StringBuilder contentbuilder=new StringBuilder(1024*1024); //通过一个URL,下载网页内容 private void download(URL url) { in=null; out=null; //建立抓取文件 String urlfile=url.getFile(); if(urlfile.endsWith("/")) urlfile+="indexindex"; File file=new File(host_path,urlfile); File file_dir=new File(file.getParent()); if(!file_dir.exists()) file_dir.mkdirs(); MonitorHolder.getMonitor().print(id+"开始准备下载"+url.toString()+"\n"); try { //打开链接 URLConnection conn=url.openConnection(); //超时30秒 conn.setConnectTimeout(30000); conn.setDoOutput(true); //不是HTML不下载 /*String type=conn.getContentType(); if( (type==null)|| (!type.equals("text/html")) ) return;*/ //将网页内容的缓冲区清空 contentbuilder.setLength(0); in=new InputStreamReader(conn.getInputStream(),charset); out=new OutputStreamWriter(new FileOutputStream(file),charset); int len; //读取网页内容,并写入文件,保存到网页内容缓冲里面 while((len=in.read(buf, 0, 10240)) &gt;0) { out.write(buf, 0, len); //append可以减小系统损耗 contentbuilder.append(buf, 0, len); } out.flush(); //将网页内容缓冲区的内容读到content中,用于分析 content=null; content=contentbuilder.toString(); } catch (IOException e) { MonitorHolder.getMonitor().print("错误!!!"+id+"下载页面"+url.toString()+"错误\n"); } finally{ try { if(in!=null) in.close(); if(out!=null) out.close(); } catch (IOException e) { } in=null; out=null; } } public Crawler(String id,CrawlerController controller,URLMap urlmap) { this.id=id; this.controller=controller; this.urlmap=urlmap; this.charset="utf-8"; canceled=false; MonitorHolder.getMonitor().print(id+"就绪\n"); } //设置字符集,通过正则表达式获取字符集格式 //为了性能,该功能并未使用 private void setCharset() { Matcher matcher=charset_pattern.matcher(content); String CHARSET="GB2312"; if(matcher.find()) CHARSET=matcher.group(1).trim(); this.charset=CHARSET; try { content=new String(content.getBytes("GB2312"),CHARSET); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } //从网页内容中分析超链接 private List&lt;string&gt; retrieveLinks(URL url) { List&lt;string&gt; urls=new LinkedList&lt;string&gt;(); if(content==null) return urls; Matcher matcher=link_pattern.matcher(content); String link; String host_reg="http://"+host; String host_nowww; if(host.contains("www")) host_nowww=host.substring(host.lastIndexOf("w")+2); else { host_nowww=host; } while(matcher.find()) { //通过抓取第1组的内容 link=matcher.group(2).trim().toLowerCase(); if (link.length() &lt; 1) { continue; } //网页内部链接,忽略 if (link.charAt(0) == '#') { continue; } //发送邮件链接,忽略 if (link.indexOf("mailto:") != -1) { continue; } if (link.toLowerCase().indexOf("javascript") != -1) { continue; } //分析绝对地址或相对地址 if (link.indexOf("://") == -1){ if (link.charAt(0) == '/') //处理绝对地址 link = "http://" + host+ link; else if(link.startsWith("./")) link="http://" + host+ link.substring(1); else { String file = url.getFile(); String file_path=file.substring(0, file.lastIndexOf('/')); while(link.startsWith("../")) { link=link.substring(link.indexOf("/")+1); file_path=file_path.substring(0, file_path.lastIndexOf("/")); } link="http://"+host+file_path+"/"+link; } } int index = link.indexOf('#'); if (index != -1) { link = link.substring(0, index); } if(!urlmap.testHost(link)) continue; if(!urlmap.testLimit(link)) continue; urls.add(link); } return urls; } //设置主机并建立目录 private void setHost(String host) { this.host=host; this.host_path=root_path+"\\"+host; File host_dir=new File(host_path); if(!host_dir.exists()) host_dir.mkdirs(); } @Override public void run() { if(!root_dir.exists()) root_dir.mkdirs(); while(!Thread.currentThread().isInterrupted() &amp;&amp; !canceled &amp;&amp; (controller.getCount()&lt;controller.gettotal()) )="" {="" try="" {="" 获得一个待抓取的url,如果没有可用url,则进入阻塞状态,该方法调用是线程安全的="" string="" urlstring="urlmap.getURL();" monitorholder.getmonitor().print(id+"开始抓取"+urlstring+"\n");="" 建立url="" url="" url="new" url(urlstring);="" 设置主机="" sethost(url.gethost());="" 清空网页内容,并下贼="" content="null;" download(url);="" 未下载到内容="" if(content="=null)" {="" continue;="" }="" monitorholder.getmonitor().print(id+"抓取"+urlstring+"完毕,进行解析\n");="" setcharset();="" 分析超链接="" list&lt;string=""&gt; urls=retrieveLinks(url); //将分析到的超连接加入到待抓取的URL队列中,并将成功抓取数+1 urlmap.addAll(urls); controller.count(); MonitorHolder.getMonitor().print(id+"解析"+urlstring+"完毕,共计"+urls.size()+"个超链接,开始新任务\n"); content=null; TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { MonitorHolder.getMonitor().print(id+"被中断\n"); canceled=true; } catch (MalformedURLException e) { MonitorHolder.getMonitor().print(id+"报告:URL格式错误\n"); }catch (Exception e) { e.printStackTrace(); } } } //退出,由控制器调用,关闭所有底层I/O资源 public void cancel() { try { if(in!=null) in.close(); } catch (IOException e) { } try { if(out!=null) out.close(); } catch (IOException e) { e.printStackTrace(); } MonitorHolder.getMonitor().print(id+"停止工作\n"); canceled=true; } } </pre> <p> </p> <pre name="code" class="java">package com.wood.core; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.*; import java.util.*; public class URLMap { //待抓取的URL队列 private LinkedList&lt;string&gt; URLQueue; //缓存解析出来的URL,使用Hash方便快速查找,&lt;k,false&gt;表示未抓取,&lt;k,true&gt;表示抓取结束 private HashMap&lt;string,boolean&gt; cachedURL; private HashSet&lt;string&gt; hosts; private HashSet&lt;string&gt; format_limit; //默认构造器,初始化队列,集合 private URLMap() { URLQueue=new LinkedList&lt;string&gt;(); cachedURL=new HashMap&lt;string,boolean&gt;(50000); hosts=new HashSet&lt;string&gt;(20); format_limit=new HashSet&lt;string&gt;(20); } public URLMap(List&lt;string&gt; seeds) { this(); for(String s:seeds) cachedURL.put(s, false); URLQueue.addAll(seeds); for (String string : seeds) { try { URL test=new URL(string); String host=test.getHost(); hosts.add(host); } catch (MalformedURLException e) { e.printStackTrace(); } } } public URLMap(String seed) { this(); cachedURL.put(seed, false); URLQueue.add(seed); try { URL test=new URL(seed); hosts.add(test.getHost()); } catch (MalformedURLException e) { e.printStackTrace(); } } //将解析出来的URL添加到URLMap中,如果有重复则忽略,URL有效性由外部保证,该方法是线程安全的 public synchronized void addURL(String url) throws InterruptedException { //如果该URL已存在,忽略该URL if(cachedURL.keySet().contains(url)) return; cachedURL.put(url, false); URLQueue.add(url); //有可用URL,唤醒所有阻塞线程 notifyAll(); } //将解析出来的URL添加到URLMap中,如果有重复则忽略,URL有效性由外部保证,该方法是同步的 public synchronized void addAll(List&lt;string&gt; urls) throws InterruptedException { for (String url : urls) { if(cachedURL.keySet().contains(url)) continue; cachedURL.put(url,false); URLQueue.add(url); } notifyAll(); } //从当前URL队列中获取一个URL,如果当前队列无可用URL,则该线程进入阻塞状态 public synchronized String getURL() throws InterruptedException { //该处进入阻塞 while(URLQueue.size()==0) wait(); //将其从队列中删除 String url=URLQueue.remove(); cachedURL.put(url, true); return url; } public boolean testHost(String host) { for(String host_allow:hosts) { if(host.contains(host_allow)) return true; } return false; } public void addHost(List&lt;string&gt; l) { hosts.addAll(l); } public void addLimit(List&lt;string&gt; l) { format_limit.addAll(l); } public boolean testLimit(String url) { if(format_limit.size()==0) return true; else { for(String s:format_limit) if(url.contains(s)) return true; } return false; } //将待抓取队列打乱 private int swap_check=0; public synchronized void shuffle() { swap_check++; int size=URLQueue.size(); if(size&lt;1000) { java.util.Collections.shuffle(URLQueue); swap_check=0; } else { if(size&gt;=1000 &amp;&amp; size&lt;5000) { if(swap_check==5) { java.util.Collections.shuffle(URLQueue); swap_check=0; } } else { if(swap_check==15) { java.util.Collections.shuffle(URLQueue); swap_check=0; } } } } } </pre> <p><br /><br />附件里是内存使用情况<br /><strong>问题补充</strong><br />主要占用内存的是char[] <br />我的策略是所有分析到的有效URL都存储在HashMap中 <br />但是几万个URL不至于占用大多数内存吧? <br />我的工作线程只有5个,设置的多了,一会就崩了 <br /><br />哪位高人路过,帮我看眼吧 <br />祝你新年好运~</p> <p> </p> <p>附件里是内存占用,缓存的URL总数是20000个,一个大概占用80B,程序内存总数是150MB</p> <p>我不知道到底是什么东西不停的吃内存,回收不掉,程序运行的时间越长,线程数越多,内存吃的越快</p>
Ext的combotree取值value问题
有这样一个combotree: [code="javascript"] items: [{ xtype: 'combotree', fieldLabel: '推荐产品', id: 'recommend_product', name: 'product', hiddenName: 'recommend_product', blankText: '必须选择一款产品!', emptyText: '请选择产品……', autoHeight: true, resizable: true, tree: new Ext.tree.TreePanel({ rootVisible: false, hideBorders: true, border: false, root: new Ext.tree.AsyncTreeNode({ id: 'CategoryRoot', text: "", loader: new Ext.tree.TreeLoader({ dataUrl: '/product/show_product_by_type_tree/tree.json', requestMethod: 'GET', preloadChildren: false, clearOnLoad: false, }) }) }), anchor: '90%', allowBlank: false }] [/code] 我想取出它的选中项的Value(不是text)的话,应该怎么做啊?是在后台还是前台啊?完全没有头绪的说…… [b]问题补充:[/b] 呃……我用的是这样一个文件,貌似里面没有setValue和getValue的方法? 唉,哪怕有个API看看也好啊 :? [code="javascript"] /** * 下拉树ComboBoxTree * @extend Ext.form.ComboBox * @xtype 'combotree' * * @author chengbao_zhu */ /** * ---------------------- * Demo ComboBoxTree * ---------------------- */ /*-------------------------------------------------* treecombo = { fieldLabel : '片 源 类 别', width : 127, xtype : 'combotree', passName : 'videoCategory', allowUnLeafClick : false, treeHeight:200, tree : new Ext.tree.TreePanel({ rootVisible : false, root : new Ext.tree.AsyncTreeNode({ id : 'CategoryRoot', text : "影片分类", expanded : true, loader : new Ext.tree.TreeLoader({ dataUrl : UrlPpts.ajax.vdocategory + '?method=tree' }) }) }), allowBlank : false } *-----------------------------------------------------*/ ComboBoxTree = Ext.extend(Ext.form.ComboBox, { /** * ------------------------------------- * 作为隐藏域的name属性 * ------------------------------------- */ passName : 'id', /** * ------------------------------------- * 是否允许非叶子结点的单击事件 * * @default false * ------------------------------------- */ allowUnLeafClick : true, /** * --------------------- * 树渲染的模板tpl * --------------------- */ // tpl: '<div id="treeTpl"></div>', //html代码 /** * ----------------------- * 树显示的高度,默认为180 * ----------------------- */ treeHeight : 180, store : new Ext.data.SimpleStore({ fields : [], data : [[]] }), //Default editable : false, // 禁止手写及联想功能 mode : 'local', triggerAction : 'all', maxHeight : 500, selectedClass : '', onSelect : Ext.emptyFn, emptyText : '请选择...', /** * 清空值 */ clearValue : function() { if (this.passField) { this.passField.value = ''; } this.setRawValue(''); }, /** * 设置传值 * @param passvalue */ setPassValue: function(passvalue){ if (this.passField) this.passField.value = passvalue; }, /** * -------------------------------------- * 下拉树被点击事件添加一处理方法 * @param node * -------------------------------------- */ onTreeSelected : function(node) { }, /** * ---------------------------------- * 树的单击事件处理 * @param node,event * ---------------------------------- */ treeClk : function(node, e) { if (!node.isLeaf() && !this.allowUnLeafClick) { e.stopEvent();// 非叶子节点则不触发 return; } this.setValue(node.text);// 设置option值 this.collapse();// 隐藏option列表 if (this.passField) this.passField.value = node.id;// 以树的节点ID传递 // 选中树节点后的触发事件 this.fireEvent('treeselected', node); }, /** * 初始化 * Init */ initComponent : function() { ComboBoxTree.superclass.initComponent.call(this); this.tree.autoScroll = true; //this.tree.height = this.treeHeight; this.tree.containerScroll = false; this.tplId = Ext.id(); // overflow:auto" this.tpl = '<div id="' + this.tplId + '" style="height:' + this.treeHeight + 'px";overflow:hidden;"></div>'; /** * ----------------------- * 添加treeselected事件, * 选中树节点会激发这个事 * 件, 参数为树的节点 * ------------------------ */ this.addEvents('treeselected'); // this.on('treeselected',this.onTreeSelected,this); }, /** * ------------------ * 事件监听器 * Listener * ------------------ */ listeners : { 'expand' : { fn : function() { if (!this.tree.rendered && this.tplId) { this.tree.render(this.tplId); } this.tree.show(); }, single : true }, 'render' : { fn : function() { this.tree.on('click', this.treeClk, this); /** * ------------------------------------------- * 创建隐藏输入域<input /> * 并将其dom传给passField * ------------------------------------------ */ if (this.passName) { this.passField = this.getEl().insertSibling({ tag : 'input', type : 'hidden', name : this.passName, id : this.passId || Ext.id() }, 'before', true) } this.passField.value = this.passValue !== undefined ? this.passValue : (this.value !== undefined ? this.value : ''); this.el.dom.removeAttribute('name'); } }, 'beforedestroy' : { fn : function(cmp) { this.purgeListeners(); this.tree.purgeListeners(); } } } }); /** * --------------------------------- * 将ComboBoxTree注册为Ext的组件,以便使用 * Ext的延迟渲染机制,xtype:'combotree' * --------------------------------- */ Ext.reg('combotree', ComboBoxTree); [/code] [b]问题补充:[/b] 用了selectText,结果弹出来的是这样的精简过的代码(直接复制的,就不贴图了,其实是个alert框的): [code=""] --------------------------- Microsoft Internet Explorer --------------------------- function(h,a){var c=this.getRawValue();var e=false;if(c.length>0){h=h===undefined?0:h;a=a===undefined?c.length:a;var g=this.el.dom;if(g.setSelectionRange){g.setSelectionRange(h,a)}else{if(g.createTextRange){var b=g.createTextRange();b.moveStart("character",h);b.moveEnd("character",a-c.length);b.select()}}e=Ext.isGecko||Ext.isOpera}else{e=true}if(e){this.focus()}} --------------------------- 确定 --------------------------- [/code] [b]问题补充:[/b] 汗,昨天半夜晕乎乎地,跑去alert…… 我是要它的“value”呢,就是1,2这样的数字,但是用了combotree之后,再调用它的value,出来的也还是汉字的名称而不是数字…… [code="javascript"]Ext.getCmp("recommend_product").selectText(0,3);[/code]这样只是把它的文字选中而已啊 [b]问题补充:[/b] 呃,getValue()和getRawValue()出来的,也变成了汉字的名称,这个combotree是不是把这些都一股脑儿接管了啊…… [b]问题补充:[/b] @蔡华江: 我最开始用到的就是您提供的那个控件,但它有一个让我束手无策的问题:失去焦点时会自己把值清空,后来没办法才用的我发的那个版本的。 不知您是用什么方法来避免“失去焦点时清空值”这一问题的呢? [b]问题补充:[/b] [code="javascript"]items: [{ xtype: 'combotree', fieldLabel: '推荐产品', id: 'recommend_product', name: 'module', hiddenName: 'question.module', blankText: '必须选择一款产品!', emptyText: '请选择产品……', autoHeight: true, resizable: true, tree: product_tree, anchor: '90%', allowBlank: false }] [/code] 我是这么调用的,然后就有取不回值的问题。 不知道您方便把您的代码给我一份吗?我的信箱hexawing#163.com,先谢谢了!
急!!!使用shiro+ssm时自定义Realm项目运行报错
``` 报错信息: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shiroFilter' defined in class path resource [spring-shiro.xml]: Cannot resolve reference to bean 'securityManager' while setting bean property 'securityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityManager' defined in class path resource [spring-shiro.xml]: Cannot resolve reference to bean 'iniRealm' while setting bean property 'realm'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'iniRealm': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.rn.pojo.User com.rn.Realm.UserRealm.us; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.rn.pojo.User] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:334) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1419) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1160) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195) at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:755) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464) at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:410) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5157) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5680) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:1017) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:993) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:652) at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1296) at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:2039) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityManager' defined in class path resource [spring-shiro.xml]: Cannot resolve reference to bean 'iniRealm' while setting bean property 'realm'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'iniRealm': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.rn.pojo.User com.rn.Realm.UserRealm.us; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.rn.pojo.User] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:334) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1419) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1160) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:191) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328) ... 27 more Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'iniRealm': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.rn.pojo.User com.rn.Realm.UserRealm.us; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.rn.pojo.User] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:298) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1148) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:191) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328) ... 37 more Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.rn.pojo.User com.rn.Realm.UserRealm.us; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.rn.pojo.User] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:531) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:295) ... 45 more Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.rn.pojo.User] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:997) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:867) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:779) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:503) ... 47 more - (2701 ms) - 2019-1-11 11:37:39[ INFO](DefaultSingletonBeanRegistry.java:444) Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@684724b0: defining beans [applyServiceImpl,businessTripServiceImpl,contractServiceImpl,customerPriceListServiceImpl,employeeServiceImpl,hospitalServiceImpl,invoiceServiceImpl,leaveServiceImpl,rbrcServiceImpl,reimbursementServiceImpl,reportServiceImpl,roleServiceImpl,salerPerformanceServiceImpl,sampleLedgerServiceImpl,sampleSummaryServiceImpl,statementOfAccountServiceImpl,userGroupServiceImpl,userServiceImpl,workloadServiceImpl,workPlanServiceImpl,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.support.PropertySourcesPlaceholderConfigurer#0,dataSource,transactionManager,sqlSessionFactory,org.springframework.aop.config.internalAutoProxyCreator,transService,org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0,txAdvice,org.mybatis.spring.mapper.MapperScannerConfigurer#0,multipartResolver,iniRealm,securityManager,cacheManager,shiroFilter,lifecycleBeanPostProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,applyMapper,businessTripMapper,contractMapper,customerPriceListMapper,employeeMapper,hospitalMapper,invoiceMapper,leaveMapper,rbrcMapper,reimbursementMapper,reportMapper,roleMapper,salerPerformanceMapper,sampleLedgerMapper,sampleSummaryMapper,statementOfAccountMapper,userGroupMapper,userMapper,workloadMapper,workPlanMapper]; root of factory hierarchy - (2701 ms) - 2019-1-11 11:37:39[DEBUG](DefaultSingletonBeanRegistry.java:500) Retrieved dependent beans for bean '(inner bean)#3d3e97d3': [txAdvice] - (2702 ms) - 2019-1-11 11:37:39[DEBUG](DisposableBeanAdapter.java:303) Invoking destroy method 'close' on bean with name 'dataSource' - (2703 ms) - 2019-1-11 11:37:39[ERROR](ContextLoader.java:331) Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shiroFilter' defined in class path resource [spring-shiro.xml]: Cannot resolve reference to bean 'securityManager' while setting bean property 'securityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityManager' defined in class path resource [spring-shiro.xml]: Cannot resolve reference to bean 'iniRealm' while setting bean property 'realm'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'iniRealm': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.rn.pojo.User com.rn.Realm.UserRealm.us; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.rn.pojo.User] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:334) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1419) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1160) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195) at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:755) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464) at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:410) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5157) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5680) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:1017) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:993) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:652) at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1296) at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:2039) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityManager' defined in class path resource [spring-shiro.xml]: Cannot resolve reference to bean 'iniRealm' while setting bean property 'realm'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'iniRealm': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.rn.pojo.User com.rn.Realm.UserRealm.us; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.rn.pojo.User] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:334) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1419) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1160) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:191) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328) ... 27 more Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'iniRealm': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.rn.pojo.User com.rn.Realm.UserRealm.us; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.rn.pojo.User] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:298) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1148) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:191) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328) ... 37 more Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.rn.pojo.User com.rn.Realm.UserRealm.us; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.rn.pojo.User] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:531) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:295) ... 45 more Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.rn.pojo.User] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:997) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:867) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:779) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:503) ... 47 more 一月 11, 2019 11:37:39 上午 org.apache.catalina.core.StandardContext listenerStart 严重: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shiroFilter' defined in class path resource [spring-shiro.xml]: Cannot resolve reference to bean 'securityManager' while setting bean property 'securityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityManager' defined in class path resource [spring-shiro.xml]: Cannot resolve reference to bean 'iniRealm' while setting bean property 'realm'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'iniRealm': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.rn.pojo.User com.rn.Realm.UserRealm.us; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.rn.pojo.User] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:334) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1419) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1160) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195) at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:755) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464) at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:410) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5157) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5680) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:1017) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:993) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:652) at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1296) at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:2039) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityManager' defined in class path resource [spring-shiro.xml]: Cannot resolve reference to bean 'iniRealm' while setting bean property 'realm'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'iniRealm': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.rn.pojo.User com.rn.Realm.UserRealm.us; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.rn.pojo.User] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:334) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1419) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1160) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:191) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328) ... 27 more Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'iniRealm': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.rn.pojo.User com.rn.Realm.UserRealm.us; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.rn.pojo.User] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:298) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1148) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290) at org.springframework.beans.factory.support.AbstractBea nFactory.getBean(AbstractBeanFactory.java:191) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328) ... 37 more Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.rn.pojo.User com.rn.Realm.UserRealm.us; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.rn.pojo.User] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:531) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:295) ... 45 more Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.rn.pojo.User] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:997) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:867) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:779) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:503) ... 47 more ``` ``` **web.xml** <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:applicationContext-*.xml, classpath:spring-shiro.xml </param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <filter> <filter-name>encodingFilter</filter-name> <filter-class> org.springframework.web.filter.CharacterEncodingFilter </filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- shiro过滤器 --> <filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <init-param> <param-name>targetFilterLifecycle</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:springmvc-servlet.xml, classpath:spring-shiro.xml </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.jpg</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.gif</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.jpeg</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.mp4</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.eot</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.svg</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.ttf</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.woff</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.woff2</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.otf</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.png</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.psd</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.xls</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.pdf</url-pattern> </servlet-mapping> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <context-param> <param-name>webAppRootKey</param-name> <param-value>SMBMS_C12_12.root</param-value> </context-param> <listener> <listener-class> org.springframework.web.util.Log4jConfigListener </listener-class> </listener> <welcome-file-list> <welcome-file>/WEB-INF/jsp/back/customerprice.jsp</welcome-file> </welcome-file-list> ``` ``` ``` **spring-shiro.xml** <bean id="iniRealm" class="com.rn.Realm.UserRealm"> <!-- 配置缓存管理器--> <property name="cacheManager" ref="cacheManager" /> <!-- 配置加密器 --> <property name="credentialsMatcher"> <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher"> <property name="hashAlgorithmName" value="MD5"></property> <!-- 加密算法的名称 --> <property name="hashIterations" value="1024"></property> <!-- 配置加密的次数 --> </bean> </property> </bean> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="iniRealm"></property> </bean> <!-- 用户授权信息Cache --> <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" /> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager"></property> <property name="loginUrl" value="/gologin.html"></property> <property name="successUrl" value="/index.html"></property> <property name="unauthorizedUrl" value="/error.html"></property> <property name="filterChainDefinitions"> <value> /login.html=anon /gologin.html=anon /index.html=authc /role.html=authc,roles[admin] /menu/**=authc,roles[admin],perms[menu:*] </value> </property> </bean> <!-- 配置Shiro在Spring中的生命周期的控制操作 --> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> ``` **springMvc-servlet.xml** <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json;charset=UTF-8</value> </list> </property> </bean> <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>application/json</value> </list> </property> <property name="features"> <list> <!-- Date的日期转换器 --> <value>WriteDateUseDateFormat</value> </list> </property> </bean> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="objectMapper" ref="customObjectMapper"></property> </bean> </mvc:message-converters> </mvc:annotation-driven> <context:component-scan base-package="com.rn.controller,com.rn.dao,com.rn.service,com.rn.service.impl"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <bean id="customObjectMapper" class="com.rn.demo.CustomObjectMapper"></bean> <mvc:resources location="/statics/" mapping="/statics/**"></mvc:resources> <!-- 配置多视图解析器:允许同样的内容数据呈现不同的view --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" > <property name="prefix" value="/WEB-INF/jsp"/> <property name="suffix" value=".jsp"/> </bean> <!-- <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/user/sys/**"/> <bean class="cn.smbms.interceptor.SysInterceptor"/> </mvc:interceptor> </mvc:interceptors> --> <!-- 配置MultipartResolver,用于上传文件,使用spring的CommonsMultipartResolver --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="5000000"/> <property name="defaultEncoding" value="UTF-8"/> </bean> <!-- 配置启用Shiro的注解功能 --> <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> ``` Realm.java package com.rn.Realm; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Resource; 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.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.util.ByteSource; import org.springframework.beans.factory.annotation.Autowired; import com.rn.pojo.User; import com.rn.service.UserService; public class UserRealm extends AuthorizingRealm { @Autowired private UserService userSer; @Autowired private User us; @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) { return null; } @Override protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken token) throws AuthenticationException { //1.将token转换为UsernamePasswordToken UsernamePasswordToken userToken = (UsernamePasswordToken)token; //2.获取token中的登录账户 String user_Name = userToken.getUsername(); //3.查询数据库,是否存在指定的用户名和密码的用户(主键/账户/密码/账户状态/盐) us = null; us = userSer.getpassword(user_Name); //4.1 如果没有查询到,抛出异常 if( us == null ) { throw new UnknownAccountException("账户"+user_Name+"不存在!"); } if( us.getLock() == "1"){ throw new LockedAccountException(us.getUser_Name()+"被锁定!"); } //4.2 如果查询到了,封装查询结果, Object principal = us.getUser_Code(); Object credentials = us.getPassword(); String realmName = this.getName(); //获取盐,用于对密码在加密算法(MD5)的基础上二次加密ֵ SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal, credentials, realmName); //5. 返回给调用login(token)方法 return info; } } ``` ``` 使用ini文件不报错,使用自定义realm就报这个错误 我是个新手,公司又只有我一个java开发,第一次使用shiro,工期比较紧,拜托各位大神帮帮忙。百度了好多解决办法都不行 拜托各位大神,拜托拜托
终于明白阿里百度这样的大公司,为什么面试经常拿ThreadLocal考验求职者了
点击上面↑「爱开发」关注我们每晚10点,捕获技术思考和创业资源洞察什么是ThreadLocalThreadLocal是一个本地线程副本变量工具类,各个线程都拥有一份线程私有的数
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过
《奇巧淫技》系列-python!!每天早上八点自动发送天气预报邮件到QQ邮箱
此博客仅为我业余记录文章所用,发布到此,仅供网友阅读参考,如有侵权,请通知我,我会删掉。 补充 有不少读者留言说本文章没有用,因为天气预报直接打开手机就可以收到了,为何要多此一举发送到邮箱呢!!!那我在这里只能说:因为你没用,所以你没用!!! 这里主要介绍的是思路,不是天气预报!不是天气预报!!不是天气预报!!!天气预报只是用于举例。请各位不要再刚了!!! 下面是我会用到的两个场景: 每日下
死磕YOLO系列,YOLOv1 的大脑、躯干和手脚
YOLO 是我非常喜欢的目标检测算法,堪称工业级的目标检测,能够达到实时的要求,它帮我解决了许多实际问题。 这就是 YOLO 的目标检测效果。它定位了图像中物体的位置,当然,也能预测物体的类别。 之前我有写博文介绍过它,但是每次重新读它的论文,我都有新的收获,为此我准备写一个系列的文章来详尽分析它。这是第一篇,从它的起始 YOLOv1 讲起。 YOLOv1 的论文地址:https://www.c
知乎高赞:中国有什么拿得出手的开源软件产品?(整理自本人原创回答)
知乎高赞:中国有什么拿得出手的开源软件产品? 在知乎上,有个问题问“中国有什么拿得出手的开源软件产品(在 GitHub 等社区受欢迎度较好的)?” 事实上,还不少呢~ 本人于2019.7.6进行了较为全面的 回答 - Bravo Yeung,获得该问题下回答中得最高赞(236赞和1枚专业勋章),对这些受欢迎的 Github 开源项目分类整理如下: 分布式计算、云平台相关工具类 1.SkyWalk
20行Python代码爬取王者荣耀全英雄皮肤
引言 王者荣耀大家都玩过吧,没玩过的也应该听说过,作为时下最火的手机MOBA游戏,咳咳,好像跑题了。我们今天的重点是爬取王者荣耀所有英雄的所有皮肤,而且仅仅使用20行Python代码即可完成。 准备工作 爬取皮肤本身并不难,难点在于分析,我们首先得得到皮肤图片的url地址,话不多说,我们马上来到王者荣耀的官网: 我们点击英雄资料,然后随意地选择一位英雄,接着F12打开调试台,找到英雄原皮肤的图片
简明易理解的@SpringBootApplication注解源码解析(包含面试提问)
欢迎关注文章系列 ,关注我 《提升能力,涨薪可待》 《面试知识,工作可待》 《实战演练,拒绝996》 欢迎关注我博客,原创技术文章第一时间推出 也欢迎关注公 众 号【Ccww笔记】,同时推出 如果此文对你有帮助、喜欢的话,那就点个赞呗,点个关注呗! 《提升能力,涨薪可待篇》- @SpringBootApplication注解源码解析 一、@SpringBootApplication 的作用是什
西游记团队中如果需要裁掉一个人,会先裁掉谁?
2019年互联网寒冬,大批企业开始裁员,下图是网上流传的一张截图: 裁员不可避免,那如何才能做到不管大环境如何变化,自身不受影响呢? 我们先来看一个有意思的故事,如果西游记取经团队需要裁员一名,会裁掉谁呢,为什么? 西游记团队组成: 1.唐僧 作为团队teamleader,有很坚韧的品性和极高的原则性,不达目的不罢休,遇到任何问题,都没有退缩过,又很得上司支持和赏识(直接得到唐太宗的任命,既给
Python语言高频重点汇总
Python语言高频重点汇总 GitHub面试宝典仓库——点这里跳转 文章目录Python语言高频重点汇总**GitHub面试宝典仓库——点这里跳转**1. 函数-传参2. 元类3. @staticmethod和@classmethod两个装饰器4. 类属性和实例属性5. Python的自省6. 列表、集合、字典推导式7. Python中单下划线和双下划线8. 格式化字符串中的%和format9.
究竟你适不适合买Mac?
我清晰的记得,刚买的macbook pro回到家,开机后第一件事情,就是上了淘宝网,花了500元钱,找了一个上门维修电脑的师傅,上门给我装了一个windows系统。。。。。。 表砍我。。。 当时买mac的初衷,只是想要个固态硬盘的笔记本,用来运行一些复杂的扑克软件。而看了当时所有的SSD笔记本后,最终决定,还是买个好(xiong)看(da)的。 已经有好几个朋友问我mba怎么样了,所以今天尽量客观
程序员一般通过什么途径接私活?
二哥,你好,我想知道一般程序猿都如何接私活,我也想接,能告诉我一些方法吗? 上面是一个读者“烦不烦”问我的一个问题。其实不止是“烦不烦”,还有很多读者问过我类似这样的问题。 我接的私活不算多,挣到的钱也没有多少,加起来不到 20W。说实话,这个数目说出来我是有点心虚的,毕竟太少了,大家轻喷。但我想,恰好配得上“一般程序员”这个称号啊。毕竟苍蝇再小也是肉,我也算是有经验的人了。 唾弃接私活、做外
ES6基础-ES6的扩展
进行对字符串扩展,正则扩展,数值扩展,函数扩展,对象扩展,数组扩展。 开发环境准备: 编辑器(VS Code, Atom,Sublime)或者IDE(Webstorm) 浏览器最新的Chrome 字符串的扩展: 模板字符串,部分新的方法,新的unicode表示和遍历方法: 部分新的字符串方法 padStart,padEnd,repeat,startsWith,endsWith,includes 字
Python爬虫爬取淘宝,京东商品信息
小编是一个理科生,不善长说一些废话。简单介绍下原理然后直接上代码。 使用的工具(Python+pycharm2019.3+selenium+xpath+chromedriver)其中要使用pycharm也可以私聊我selenium是一个框架可以通过pip下载 pip install selenium -i https://pypi.tuna.tsinghua.edu.cn/simple/ 
阿里程序员写了一个新手都写不出的低级bug,被骂惨了。
你知道的越多,你不知道的越多 点赞再看,养成习惯 本文 GitHub https://github.com/JavaFamily 已收录,有一线大厂面试点思维导图,也整理了很多我的文档,欢迎Star和完善,大家面试可以参照考点复习,希望我们一起有点东西。 前前言 为啥今天有个前前言呢? 因为你们的丙丙啊,昨天有牌面了哟,直接被微信官方推荐,知乎推荐,也就仅仅是还行吧(心里乐开花)
Java工作4年来应聘要16K最后没要,细节如下。。。
前奏: 今天2B哥和大家分享一位前几天面试的一位应聘者,工作4年26岁,统招本科。 以下就是他的简历和面试情况。 基本情况: 专业技能: 1、&nbsp;熟悉Sping了解SpringMVC、SpringBoot、Mybatis等框架、了解SpringCloud微服务 2、&nbsp;熟悉常用项目管理工具:SVN、GIT、MAVEN、Jenkins 3、&nbsp;熟悉Nginx、tomca
Python爬虫精简步骤1 获取数据
爬虫的工作分为四步: 1.获取数据。爬虫程序会根据我们提供的网址,向服务器发起请求,然后返回数据。 2.解析数据。爬虫程序会把服务器返回的数据解析成我们能读懂的格式。 3.提取数据。爬虫程序再从中提取出我们需要的数据。 4.储存数据。爬虫程序把这些有用的数据保存起来,便于你日后的使用和分析。 这一篇的内容就是:获取数据。 首先,我们将会利用一个强大的库——requests来获取数据。 在电脑上安装
作为一个程序员,CPU的这些硬核知识你必须会!
CPU对每个程序员来说,是个既熟悉又陌生的东西? 如果你只知道CPU是中央处理器的话,那可能对你并没有什么用,那么作为程序员的我们,必须要搞懂的就是CPU这家伙是如何运行的,尤其要搞懂它里面的寄存器是怎么一回事,因为这将让你从底层明白程序的运行机制。 随我一起,来好好认识下CPU这货吧 把CPU掰开来看 对于CPU来说,我们首先就要搞明白它是怎么回事,也就是它的内部构造,当然,CPU那么牛的一个东
破14亿,Python分析我国存在哪些人口危机!
2020年1月17日,国家统计局发布了2019年国民经济报告,报告中指出我国人口突破14亿。 猪哥的朋友圈被14亿人口刷屏,但是很多人并没有看到我国复杂的人口问题:老龄化、男女比例失衡、生育率下降、人口红利下降等。 今天我们就来分析一下我们国家的人口数据吧! 更多有趣分析教程,扫描下方二维码关注vx公号「裸睡的猪」 即可查看! 一、背景 1.人口突破14亿 2020年1月17日,国家统计局发布
web前端javascript+jquery知识点总结
Javascript javascript 在前端网页中占有非常重要的地位,可以用于验证表单,制作特效等功能,它是一种描述语言,也是一种基于对象(Object)和事件驱动并具有安全性的脚本语言 ,语法同java类似,是一种解释性语言,边执行边解释。 JavaScript的组成: ECMAScipt 用于描述: 语法,变量和数据类型,运算符,逻辑控制语句,关键字保留字,对象。 浏览器对象模型(Br
Qt实践录:开篇
本系列文章介绍笔者的Qt实践之路。 背景 笔者首次接触 Qt 大约是十多年前,当时试用了 Qt ,觉得不如 MFC 好用。现在 Qt 的 API、文档等都比较完善,在年初决定重新拾起,正所谓技多不压身,将 Qt 当为一种谋生工具亦未尝不可。利用春节假期的集中时间,快速专攻一下。 本系列名为“Qt实践”,故不是教程,笔者对 Qt 的定位是“使用”,可以帮助快速编写日常的工具,如串口、网络等。所以不
在家远程办公效率低?那你一定要收好这个「在家办公」神器!
相信大家都已经收到国务院延长春节假期的消息,接下来,在家远程办公可能将会持续一段时间。 但是问题来了。远程办公不是人在电脑前就当坐班了,相反,对于沟通效率,文件协作,以及信息安全都有着极高的要求。有着非常多的挑战,比如: 1在异地互相不见面的会议上,如何提高沟通效率? 2文件之间的来往反馈如何做到及时性?如何保证信息安全? 3如何规划安排每天工作,以及如何进行成果验收? ......
作为一个程序员,内存和磁盘的这些事情,你不得不知道啊!!!
截止目前,我已经分享了如下几篇文章: 一个程序在计算机中是如何运行的?超级干货!!! 作为一个程序员,CPU的这些硬核知识你必须会! 作为一个程序员,内存的这些硬核知识你必须懂! 这些知识可以说是我们之前都不太重视的基础知识,可能大家在上大学的时候都学习过了,但是嘞,当时由于老师讲解的没那么有趣,又加上这些知识本身就比较枯燥,所以嘞,大家当初几乎等于没学。 再说啦,学习这些,也看不出来有什么用啊!
这个世界上人真的分三六九等,你信吗?
偶然间,在知乎上看到一个问题 一时间,勾起了我深深的回忆。 以前在厂里打过两次工,做过家教,干过辅导班,做过中介。零下几度的晚上,贴过广告,满脸、满手地长冻疮。   再回首那段岁月,虽然苦,但让我学会了坚持和忍耐。让我明白了,在这个世界上,无论环境多么的恶劣,只要心存希望,星星之火,亦可燎原。   下文是原回答,希望能对你能有所启发。   如果我说,这个世界上人真的分三六九等,
为什么听过很多道理,依然过不好这一生?
记录学习笔记是一个重要的习惯,不希望学习过的东西成为过眼云烟。做总结的同时也是一次复盘思考的过程。 本文是根据阅读得到 App上《万维钢·精英日课》部分文章后所做的一点笔记和思考。学习是一个系统的过程,思维模型的建立需要相对完整的学习和思考过程。以下观点是在碎片化阅读后总结的一点心得总结。
B 站上有哪些很好的学习资源?
哇说起B站,在小九眼里就是宝藏般的存在,放年假宅在家时一天刷6、7个小时不在话下,更别提今年的跨年晚会,我简直是跪着看完的!! 最早大家聚在在B站是为了追番,再后来我在上面刷欧美新歌和漂亮小姐姐的舞蹈视频,最近两年我和周围的朋友们已经把B站当作学习教室了,而且学习成本还免费,真是个励志的好平台ヽ(.◕ฺˇд ˇ◕ฺ;)ノ 下面我们就来盘点一下B站上优质的学习资源: 综合类 Oeasy: 综合
雷火神山直播超两亿,Web播放器事件监听是怎么实现的?
Web播放器解决了在手机浏览器和PC浏览器上播放音视频数据的问题,让视音频内容可以不依赖用户安装App,就能进行播放以及在社交平台进行传播。在视频业务大数据平台中,播放数据的统计分析非常重要,所以Web播放器在使用过程中,需要对其内部的数据进行收集并上报至服务端,此时,就需要对发生在其内部的一些播放行为进行事件监听。 那么Web播放器事件监听是怎么实现的呢? 01 监听事件明细表 名
3万字总结,Mysql优化之精髓
本文知识点较多,篇幅较长,请耐心学习 MySQL已经成为时下关系型数据库产品的中坚力量,备受互联网大厂的青睐,出门面试想进BAT,想拿高工资,不会点MySQL优化知识,拿offer的成功率会大大下降。 为什么要优化 系统的吞吐量瓶颈往往出现在数据库的访问速度上 随着应用程序的运行,数据库的中的数据会越来越多,处理时间会相应变慢 数据是存放在磁盘上的,读写速度无法和内存相比 如何优化 设计
一条链接即可让黑客跟踪你的位置! | Seeker工具使用
搬运自:冰崖的部落阁(icecliffsnet) 严正声明:本文仅限于技术讨论,严禁用于其他用途。 请遵守相对应法律规则,禁止用作违法途径,出事后果自负! 上次写的防社工文章里边提到的gps定位信息(如何防止自己被社工或人肉) 除了主动收集他人位置信息以外,我们还可以进行被动收集 (没有技术含量) Seeker作为一款高精度地理位置跟踪工具,同时也是社交工程学(社会工程学)爱好者...
作为程序员的我,大学四年一直自学,全靠这些实用工具和学习网站!
我本人因为高中沉迷于爱情,导致学业荒废,后来高考,毫无疑问进入了一所普普通通的大学,实在惭愧...... 我又是那么好强,现在学历不行,没办法改变的事情了,所以,进入大学开始,我就下定决心,一定要让自己掌握更多的技能,尤其选择了计算机这个行业,一定要多学习技术。 在进入大学学习不久后,我就认清了一个现实:我这个大学的整体教学质量和学习风气,真的一言难尽,懂的人自然知道怎么回事? 怎么办?我该如何更好的提升
前端JS初级面试题二 (。•ˇ‸ˇ•。)老铁们!快来瞧瞧自己都会了么
1. 传统事件绑定和符合W3C标准的事件绑定有什么区别? 传统事件绑定 &lt;div onclick=""&gt;123&lt;/div&gt; div1.onclick = function(){}; &lt;button onmouseover=""&gt;&lt;/button&gt; 注意: 如果给同一个元素绑定了两次或多次相同类型的事件,那么后面的绑定会覆盖前面的绑定 (不支持DOM事...
Python学习笔记(语法篇)
本篇博客大部分内容摘自埃里克·马瑟斯所著的《Python编程:从入门到实战》(入门类书籍),采用举例的方式进行知识点提要 关于Python学习书籍推荐文章 《学习Python必备的8本书》 Python语法特点: 通过缩进进行语句组织 不需要变量或参数的声明 冒号 1 变量和简单数据结构 1.1 变量命名 只能包含字母、数字和下划线,且不能以数字打头。 1.2 字符串 在Python中,用引号...
[Pyhon疫情大数据分析] 一.腾讯实时数据爬取、Matplotlib和Seaborn可视化分析全国各地区、某省各城市、新增趋势
思来想去,虽然很忙,但还是挤时间针对这次肺炎疫情写个Python大数据分析系列博客,包括网络爬虫、可视化分析、GIS地图显示、情感分析、舆情分析、主题挖掘、威胁情报溯源、知识图谱、预测预警及AI和NLP应用等。第一篇文章将分享腾讯疫情实时数据抓取,获取全国各地和贵州省各地区的实时数据,并将数据存储至本地,最后调用Maplotlib和Seaborn绘制中国各地区、贵州省各城市、新增人数的图形。希望这篇可视化分析文章对您有所帮助!
小白也会用的情人节表白神器
鉴于情人节女朋友总说直男,上网找了个模板,改了一下,发现效果还不错。然后又录了一个视频,发现凑合,能用。现在免费分享给程序员,去表白去吧。​​​​​​。当然比较low因为考研没时间优化,懒着优化了。 先看一下效果吧:页面太多了,这里我只放几个页面里面有音乐,还凑合不是太单调。 所有页面最后的合成效果: 接下来教大家如何使用: 新建文件夹:love 然后建立这几个...
相关热词 c#判断数字不得为负数 c#帧和帧协议 c#算偏移值 c# 在枚举中 c#6 字符串 插值 c#程序中的占位符标签 c#监听数组变化 c# vlc c#索引实现 c# 局域网广播通信
立即提问