spring定时器,怎么注入dao层?

用的spring3.0 注解配置的定时器,基本功能(定时访问)能实现,现在想定时访问数据库,该怎么注入dao层呢??

1个回答

注入用起来多麻烦,搞个单例的,哪里都可以用。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
spring mvc 定时器问题,高手请进。
问题是这样的,我写了个定时器,现在需求是这样的,我前台写了个jsp页面,页面生成动态的时间和一个随机数,我如何做到不访问前台jsp页面,调用定时器,定时访问后台的控制层,控制层返回这个前台jsp页面,前台在动态提交给后台,存入数据库,前台jsp页面和后台业务层和dao层已经写好,不要考虑,大神给我个思路,或者其他办法也行,目的就是定时器定时调度控制层返回前台页面。
在java timer定时器中调用dao层会报错
现在在做一个web项目,使用spring+springMVC+hibernate框架, 问题描述: 项目中有一个扫描的功能,分即时任务、定时任务、周期任务三种,即时任务已经实现了,现在使用java.util.Timer、java.util.TimerTask类做定时任务,重写TimerTask的run方法,在run方法中调用之前已经没有问题的即时任务扫描方法。每次运行定时任务时,会卡在dao层方法的调用上,因为在即时任务的扫描方法中调用了dao层的数据操作方法,报错“No Session found for current thread”。 即时任务的执行流程:前台提交即时任务扫描请求->控制器调用service层的立即扫描方法startImmediateTask(); 定时任务的执行流程:前台提交定时任务扫描请求->控制器调用service层的定时扫描方法startTimerTask()->调用立即扫描方法startImmediateTask()。 下面附上代码和配置文件,请各位大牛帮忙解决啊! service层代码 ```java /** * 开始定时扫描任务 * @param blTask */ public void startTimerTask(final BLTask blTask) { Date startDate = blTask.getStartTime(); TimerTask task = new TimerTask() { @Override public void run() { // 调用扫描方法 startImmediateTask(blTask); } }; Timer timer = new Timer(); timer.schedule(task, startDate); } /** * 开始即时扫描任务 * @param blTask */ public void startImmediateTask(BLTask blTask) { BLScanParam blScanParam = new BLScanParam(); BLPolicyGroup blPolicyGroup = null; // 策略组 List<BLCheckItem> blCheckItems = null; // 检查项 Map<Long, BLCheckScript> blCheckScriptMap = new HashMap<Long, BLCheckScript>(); // 检查脚本 Long pgId = null; // 策略组ID String alias = null; // 策略别名、检查项别名 Long osType = blTask.getOsType(); // 操作系统类型 List<Long> csIds = new ArrayList<Long>(); // 检查脚本ID数组 blScanParam.setBlTask(blTask); pgId = blTask.getPgId(); // 通过策略组ID查找策略组 blPolicyGroup = blPolicyGroupDao.get(pgId); if (blPolicyGroup == null) { return; } blScanParam.setBlPolicyGroup(blPolicyGroup); alias = blPolicyGroup.getAlias(); // 通过别名、操作系统类别查找所有匹配的检查项 blCheckItems = blCheckItemDao.queryByProerties(new String[]{"alias", "osType"}, new Object[]{alias, osType}); if (blCheckItems == null || blCheckItems.size() <= 0) { return; } blScanParam.setBlCheckItems(blCheckItems); for (BLCheckItem blCheckItem : blCheckItems) { csIds.add(blCheckItem.getCsId()); } int size = csIds.size(); // 获取当前策略组下的所有检查项的检测脚本 List<BLCheckScript> blCheckScripts = blCheckScriptDao.queryByProerties("csId", (Long[])csIds.toArray(new Long[size])); for (BLCheckScript blCheckScript : blCheckScripts) { // 获取当前策略组下的所有检测脚本,并放入map中 blCheckScriptMap.put(blCheckScript.getCsId(), blCheckScript); } blScanParam.setBlCheckScriptMap(blCheckScriptMap); // 分割ip为数组,传入TaskDispatch String[] ips = getIps(blTask.getIpArea()); TaskDispatch taskDispatch = new TaskDispatch(ips, blScanParam); taskDispatch.StartTask(); // 将当前TaskDispatch对象的引用放入taskDispatchMap中,供停止任务时使用 taskDispatchMap.put(blTask.getTkId(), taskDispatch); } ``` BaseDao的部分代码 ```java public class BaseDao<E> implements Dao<E> { public SessionFactory getSessionFactory() { return this.sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public Session getSession() { return this.sessionFactory.getCurrentSession(); } @Resource(name = "sessionFactory") public void setSF(SessionFactory sessionFactory) { setSessionFactory(sessionFactory); } } ``` applicationContext.xml ```xml <?xml version="1.0" encoding="UTF-8"?> <context:annotation-config /> <context:component-scan base-package="com.djbh" /> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="com.mysql.jdbc.Driver" /> <property name="jdbcUrl" value="jdbc:mysql://192.168.1.247:3306/djbh_db?useUnicode=true&amp;characterEncoding=utf-8" /> <property name="user" value="root" /> <property name="password" value="mysql" /> <!-- <property name="driverClass" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" /> <property name="jdbcUrl" value="jdbc:sqlserver://localhost:1433;DatabaseName=DJBH_DB" /> <property name="user" value="sa" /> <property name="password" value="123456" /> --> <property name="acquireIncrement" value="3" /> <property name="idleConnectionTestPeriod" value="120" /> <property name="initialPoolSize" value="3" /> <property name="minPoolSize" value="3" /> <property name="maxPoolSize" value="15" /> <property name="numHelperThreads" value="3" /> <property name="preferredTestQuery" value="select 1" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop> <!-- <prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop> --> <!-- <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop> --> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.use_outer_join">true</prop> <prop key="hibernate.jdbc.fetch_size">30</prop> <prop key="hibernate.jdbc.batch_size">30</prop> <prop key="hibernate.jdbc.batch_versioned_data">true</prop> <prop key="hibernate.cache.use_second_level_cache">true</prop> <prop key="hibernate.cache.use_query_cache">true</prop> <prop key="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</prop> <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop> <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="javax.persistence.validation.mode">none</prop> </props> </property> <property name="dataSource" ref="dataSource" /> <property name="packagesToScan"> <list> <value>com.djbh.model</value> </list> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" /> <!-- 启动对@AspectJ注解的支持 --> <aop:aspectj-autoproxy/> </beans> ``` springmvc-servlet.xml ```xml <?xml version="1.0" encoding="UTF-8"?> <mvc:annotation-driven/> <mvc:resources location="/static/" mapping="/static/**"/> <mvc:resources location="/attachment/report_html/" mapping="/attachment/report_html/**"/> <context:component-scan base-package="com.djbh.controller" /> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass"><value>org.springframework.web.servlet.view.JstlView</value></property> <property name="prefix"><value>/WEB-INF/page/</value></property> <property name="suffix"><value>.jsp</value></property> </bean> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename" value="messages" /> <property name="useCodeAsDefaultMessage" value="true" /> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--<property name="maxUploadSize" value="10485760"></property> --> </bean> <aop:aspectj-autoproxy proxy-target-class="true" /> </beans> ``` web.xml ```xml <?xml version="1.0" encoding="UTF-8"?> <display-name>djbh</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath*:applicationContext*.xml </param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>core.web.SystemInitListener</listener-class> </listener> <filter> <filter-name>loginFilter</filter-name> <filter-class>core.web.LoginFilter</filter-class> </filter> <filter-mapping> <filter-name>loginFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>openSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>singleSession</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>openSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>characterEncoding</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>characterEncoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list> </web-app> ```
有关spring定时器@Scheduled(fixedRate = 1000*15*1)的错误
2018-02-08 13:27:39 [com.twpow.commun.dao.SiteBasicDataTableDao.saveException]-[DEBUG] <== Updates: 1 2018-02-08 13:27:39 [org.mybatis.spring.SqlSessionUtils]-[DEBUG] Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2a3c18ce] 2018-02-08 13:27:39 [org.springframework.jdbc.datasource.DataSourceUtils]-[DEBUG] Returning JDBC Connection to DataSource 2018-02-08 13:27:39 [org.springframework.scheduling.support.TaskUtils$LoggingErrorHandler]-[ERROR] Unexpected error occurred in scheduled task.
spring quartz数据源的问题
spring中配置了两个数据源:一个是默认的dataSource;另一个是dataSourceShare. 配置了两个spring quartz定时器,每个定时器分别要操作不同的数据源对应的数据库中的UserInfo表 各自的service和dao中也是分别注入的各自的datasource,但是连接的时候总是操作的是默认的dataSource数据源。 求高手帮忙啊
ssm 框架,在本地环境下完美运行,在服务器上定时器执行两次
## 此处为 spring-mybatis.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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd"> <!-- 自动扫描 --> <!-- 激活自动代理功能 --> <!-- 引入配置文件 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="${initialSize}"></property> <!-- 连接池最大数量 --> <property name="maxActive" value="${maxActive}"></property> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${maxIdle}"></property> <!-- 连接池最小空闲 --> <property name="minIdle" value="${minIdle}"></property> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="${maxWait}"></property> </bean> <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:com/bls/mp/mapping/*.xml"></property> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.bls.mp.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd" > <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 --> <context:component-scan base-package="com.bls.mp.*"/> <!--避免IE执行AJAX时,返回JSON出现下载文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- <bean id="thirdDataService" class="com.bls.mp.service.impl.ThirdDataServiceImpl"/>--> <bean class="com.bls.mp.common.SpringTool"/> <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 --> <!-- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /> JSON转换器 </list> </property> </bean>--> <!-- 定义跳转的文件的前后缀 ,视图模式配置--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 --> <property name="prefix" value="/WEB-INF/resources/jsp/" /> <property name="suffix" value=".jsp" /> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property> </bean> <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 --> <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> <!-- 全局异常处理器 --> <bean class="com.bls.mp.common.exception.CustomExceptionResolver"></bean> <mvc:annotation-driven/> <!-- 拦截器配置 --> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/setadmin"/> <!--<mvc:mapping path="/user/userList"/> --> <mvc:mapping path="/Blocker"/> <mvc:mapping path="/grouponteam/grouponRanking"/> <mvc:mapping path="/grouponteam/arriverTime"/> <mvc:mapping path="/grouponteam/paging"/> <mvc:mapping path="/grouponteam/conditionGrouponT"/> <mvc:mapping path="/hospital/hospitalInfo"/> <mvc:mapping path="/hospital/setting"/> <mvc:mapping path="/hospital/orderdetails"/> <mvc:mapping path="/grouponteam/grouponTeamCountAndMoney"/> <mvc:mapping path="/grouponteam/OrderRefundList"/> <mvc:mapping path="/grouponteam/orderdetails"/> <mvc:mapping path="/grouponteam/paging"/> <mvc:mapping path="/grouponteam/conditionGrouponT"/> <mvc:mapping path="/grouponteam/grouponRanking"/> <mvc:mapping path="/grouponteam/arriverTime"/> <mvc:mapping path="/grouponteam/grouponTeamCountAndMoney"/> <mvc:mapping path="/imguoload"/> <mvc:mapping path="/imguoloads"/> <mvc:mapping path="/uploadFile"/> <mvc:mapping path="/uploadCenter"/> <mvc:mapping path="/onTheShelves"/> <mvc:mapping path="/updateTheRecommended"/> <mvc:mapping path="/deleteByGoods"/> <mvc:mapping path="/restoreGoods"/> <mvc:mapping path="/goods/goodslist"/> <mvc:mapping path="/goods/hasBeenOn"/> <mvc:mapping path="/goods/NotOn"/> <mvc:mapping path="/goods/RecycleBin"/> <mvc:mapping path="/goods/searchName"/> <mvc:mapping path="/goods/goodsdiy"/> <mvc:mapping path="/upload/uploadFile"/> <mvc:mapping path="/CreateClassImg"/> <mvc:mapping path="/imglist"/> <mvc:mapping path="/up_img"/> <mvc:mapping path="/moveImg"/> <mvc:mapping path="/deleteImg"/> <mvc:mapping path="/template/templateURL"/> <mvc:mapping path="/template/templateParentAll"/> <mvc:mapping path="/template/templatAll"/> <mvc:mapping path="/template/changeT"/> <mvc:mapping path="/template/deleteT"/> <mvc:mapping path="/TemplateMsg/addTemplateMsg"/> <mvc:mapping path="/TemplateMsg/templateMsgList"/> <mvc:mapping path="/TemplateMsg/templateSendlist"/> <mvc:mapping path="/TemplateMsg/TemplateSendMsg"/> <mvc:mapping path="/TemplateMsg/updataPTID"/> <mvc:mapping path="/TemplateMsg/deleteMB"/> <mvc:mapping path="/ThirdData/getdata"/> <mvc:mapping path="/ThirdData/updata"/> <mvc:mapping path="/setMoney/setMoneyList"/> <mvc:mapping path="/setMoney/setArriveMoney"/> <mvc:mapping path="/setMoney/checkfileCert"/> <mvc:mapping path="/setMoney/SetMoneyType"/> <mvc:mapping path="/user/userlists"/> <mvc:mapping path="/user/uOpenId"/> <mvc:mapping path="/visitor/theAlmostMoon"/> <mvc:mapping path="/visitor/SixAlmostMoon"/> <mvc:mapping path="/visitor/tops"/> <mvc:mapping path="/weixin/REFUND"/> <bean class="com.bls.mp.interceptor.AuthInterceptor"></bean> </mvc:interceptor> </mvc:interceptors> <task:annotation-driven/> <!-- 配置访问静态文件 --> <mvc:default-servlet-handler/> <mvc:resources location="/images/" mapping="/images/**"/> <mvc:resources location="/WEB-INF/js/" mapping="/js/**"/> <mvc:resources location="/WEB-INF/resources/jsp/" mapping="/jsp/**"/> <mvc:resources location="/WEB-INF/resources/css/" mapping="/css/**"/> </beans> ``` ## 此处为web.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_3_0.xsd" version="3.0"> <display-name>Archetype Created Web Application</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-redis.xml,classpath:spring-mybatis.xml</param-value> </context-param> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <async-supported>true</async-supported> <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> <filter> <filter-name>CORSFilter</filter-name> <filter-class>com.bls.mp.common.MyFilter</filter-class> <init-param> <param-name>excludedPages</param-name> <param-value>/UserAuthServlet</param-value> </init-param> </filter> <filter-mapping> <filter-name>CORSFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <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> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> </web-app> ``` ## 此处为tomcat 配置 ``` <Server port="8005" shutdown="SHUTDOWN"> <Listener className="org.apache.catalina.startup.VersionLoggerListener" /> <Listener SSLEngine="on" className="org.apache.catalina.core.AprLifecycleListener" /> <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" /> <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" /> <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" /> <GlobalNamingResources> <Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase" /> </GlobalNamingResources> <Service name="Catalina"> <Connector connectionTimeout="20000" maxPostSize="0" port="8080" protocol="HTTP/1.1" redirectPort="8443" /> <Connector maxPostSize="0" port="8009" protocol="AJP/1.3" redirectPort="8443" /> <Engine defaultHost="localhost" name="Catalina"> <Realm className="org.apache.catalina.realm.LockOutRealm"> <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase" /> </Realm> <Host autoDeploy="true" name="yuming.cn" appBase="" unpackWARs="true" xmlNamespaceAware="false" xmlValidation="false"> <Context crossContext="true" docBase="/www/server/tomcat/webapps/xiangmu" path="" reloadable="true" /> </Host> </Engine> </Service> </Server> ``` ## spring-radis.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:p="http://www.springframework.org/schema/p" 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-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:property-placeholder location="classpath:*.properties"/> <!--设置数据池--> <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxIdle" value="${redis.maxIdle}"></property> <property name="minIdle" value="${redis.minIdle}"></property> <property name="maxTotal" value="${redis.maxTotal}"></property> <property name="maxWaitMillis" value="${redis.maxWaitMillis}"></property> <property name="testOnBorrow" value="${redis.testOnBorrow}"></property> </bean> <!--链接redis--> <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <property name="hostName" value="${redis.host}"></property> <property name="port" value="${redis.port}"></property> <property name="password" value="${redis.password}"></property> <property name="poolConfig" ref="poolConfig"></property> </bean> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" p:connection-factory-ref="connectionFactory" > <!--以下针对各种数据进行序列化方式的选择--> <property name="keySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> </property> <property name="valueSerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> </property> <property name="hashKeySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> </property> <!--<property name="hashValueSerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> </property>--> </bean> </beans> ```
spring task xml起了作用可以用,但注解就不行,ehcache缓存没起作用,
applicationContext-task.xml ,注释部分解除了是可以使用的,但我想用注解 ``` 头部删除 <task:annotation-driven/> <!-- <bean id="task" class="task.TestTask"></bean> <task:scheduled-tasks> <task:scheduled ref="task" method="test" cron="0 * 13 * * ?"/> </task:scheduled-tasks> --> <!-- --> </beans> ``` TestTask.java 这是测试 定时器的, 测试类 ``` package task; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class TestTask { @Scheduled(cron = "0/5 * 11 * * ?") public void test() { System.out.println("-----执行------"); } } ``` 这是 CityCache.java 缓存 测试类 ``` package cache; import java.util.List; import javax.annotation.Resource; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Controller; import org.springframework.stereotype.Service; import dao.AreaDao; import dao.CityDao; import dao.ProvinceDao; import entity.Area; import entity.City; import entity.Province; @Controller public class CityCache { @Resource private ProvinceDao provinceDao; @Resource private CityDao cityDao; @Resource private AreaDao areaDao; @Cacheable(value = "province") public List<Province> listProvince() { // TODO Auto-generated method stub return provinceDao.list(); } @Cacheable(value = "province") public List<Province> listProvince1() { // TODO Auto-generated method stub return null; } @Cacheable(value = "city") public List<City> listCityByProvinceId(String id) { // TODO Auto-generated method stub return cityDao.listCityByProvinceId(id); } @Cacheable(value = "area") public List<Area> listAreaByAreaId(String id) { // TODO Auto-generated method stub return areaDao.listAreaByCityId(id); } } ``` applicationContext.xml ``` 头部占位置 删了 <!-- dataSource --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/city" /> <property name="username" value="root" /> <property name="password" value="root" /> </bean> <!-- DataSource JNDI --> <!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean" p:jndiName="java:comp/env/jdbc/house"></bean> --> <!-- AOP 实现事务管理 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="dataSource"> </bean> <!-- 配置事务相关属性 --> <tx:advice id="advice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="save*"/> <tx:method name="update*"/> <tx:method name="delete*"/> <tx:method name="*"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut expression="execution(public * service.impl.*.*(..))" id="servicePointcut"/> <aop:advisor advice-ref="advice" pointcut-ref="servicePointcut"/> </aop:config> <!-- sqlSessionFactory 会话工厂--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 注入数据源 --> <property name="dataSource" ref="dataSource"></property> <!-- 注入mybatis配置文件路径 --> <property name="configLocation" value="classpath:mybatis-config.xml"></property> </bean> <!-- sqlSession 注:SqlSessionTemplate 没有提供set方法注入--> <!-- <bean id="session" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg> </bean> --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="dao"></property> </bean> <!-- 启用缓存注解功能 --> <!-- <cache:annotation-driven cache-manager="springCacheManager" proxy-target-class="false"/> --> <cache:annotation-driven cache-manager="cacheManager"/> <bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> <property name="configLocation" value="classpath:ehcache.xml"/> </bean> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"> <property name="cacheManager" ref="cacheManagerFactory"/> </bean> <import resource="applicationContext-task.xml"/> </beans> ``` springmvc.xml ``` 头部删除 <!-- 使用 annotation 方式完成映射 --> <!-- 让spring扫描报下的所有类,让标注spring注解的类生效 --> <context:component-scan base-package="controller,dao,service,cache,task"/> <mvc:annotation-driven> <!-- 消息转换器 --> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes" value="text/html;charset=UTF-8"/> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- --> <mvc:resources location="/statics/" mapping="/**"/> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans> ``` mybatis-config.xml ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN" "ibatis-3-config.dtd"> <configuration> <settings> <setting name="logImpl" value="LOG4J"/> <setting name="cacheEnabled" value="true" /> </settings> <typeAliases> <package name="entity"/> </typeAliases> </configuration> ``` 在缓存哪方面我看了下 感觉是@Cacheable(value = "province")没起作用,我把province写错运行也没有报错,按说,我的ehcache。xml中没有配置名字,在@Cacheable(value = "province")中使用会 抛出异常。 如有大神看出问题请告知 ,谢谢
spring中管理timerTask配置文件正确,不执行代码,是否和其它配置有冲突?
<?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:jdbc="http://www.springframework.org/schema/jdbc" xmlns:p="http://www.springframework.org/schema/p" 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/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd" default-autowire="byName" default-lazy-init="true"> <description>define all the basic bean mappings</description> <context:annotation-config /> <!-- jedis pool配置 --> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxActive" value="200" /> <property name="maxIdle" value="10" /> <property name="maxWait" value="1000" /> <property name="testOnBorrow" value="true" /> </bean> <!-- jedis pool配置 --> <bean id="jedisPool" class="redis.clients.jedis.JedisPool"> <constructor-arg index="0" ref="jedisPoolConfig" /> <constructor-arg index="1" value="172.16.1.165"/> <constructor-arg index="2" value="6379"/> </bean> <!-- 配置所有的配置信息 --> <bean id="constants" class="com.gozap.chouti.digg.core.commons.Constants"> <property name="scoffPic" value="http://img.gozap.com/group1/M00/51/A1/wKgCIk5XCSSIAoY_AACjisrsXVs070.jpg.jpg"></property> <property name="rumorPic" value="http://img.gozap.com/group1/M00/4F/8A/wKgCIk5V7PyMX4vTAABYVNWWTQU258.jpg.jpg"></property> <property name="titleMaxLength" value="300"></property> <property name="urlMaxLength" value="512"></property> </bean> <!-- for properties files --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath*:config/jdbc.properties</value> </list> </property> </bean> <!-- 数据库连接池 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://172.16.1.153:3306/chouti_digg?useUnicode=true&amp;characterEncoding=UTF-8" /> <property name="username" value="chouti_digg" /> <property name="password" value="chouti" /> <property name="defaultAutoCommit" value="true"></property> </bean> <!-- Mybatis's sqlSessionFactory config --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="classpath:ibatis/mybatis-config.xml"/> </bean> <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 新榜榜单数据根据一定规则入热榜 --> <bean id="choutiLinkNewToHot" class="com.gozap.chouti.digg.content.service.ChoutiLinkNewToHot"> </bean> <!-- 配置spring定时器 --> <bean id="scheduleLinkNewToHotTask" class="org.springframework.scheduling.timer.ScheduledTimerTask"> <property name="timerTask"><ref local="choutiLinkNewToHot"/></property> <property name="delay" ><value>5000</value></property> <property name="period"><value>5000</value></property> </bean> <!-- 启动spring定时器 --> <bean class="org.springframework.scheduling.timer.TimerFactoryBean"> <property name="scheduledTimerTasks"> <list><ref local="scheduleLinkNewToHotTask"/></list> </property> </bean> <!-- 启用事务 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <!-- 扫描指定package下所有带有如@controller,@services,@resource,并把所注释的注册为Spring Beans --> <context:component-scan base-package="com.gozap.chouti.digg"> <context:include-filter type="regex" expression="com\.gozap\.chouti\.digg..*?\.service\..*"/> </context:component-scan> <!-- Support @Transactional tag --> <tx:annotation-driven /> <!-- scan mappers and let them be autowired --> <bean id="mapperConfig" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.gozap.chouti.digg.core.dao" /> </bean> <!-- 激活annotation功能 --> <context:annotation-config /> <!-- 激活annotation功能 --> <context:spring-configured /> </beans>
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
spring 和 Ehcache web做页面缓存配置出异常?
<div class="iteye-blog-content-contain" style="font-size: 14px;"> <p>项目用的是spring mvc + hibernate 的结构。现在想用 Ehcache web做一个简单的页面缓存。网上找了很多例子但是就是报异常:</p> <pre name="code" class="java">Caused by: net.sf.ehcache.CacheException: Error configuring from file:/D:/workspace/sulai/webapp/WEB-INF/classes/ehcache.xml. Initial cause was Error configuring from input stream. Initial cause was null:90: Element &lt;ehcache&gt; does not allow nested &lt;transactionManagerLookup&gt; elements. at net.sf.ehcache.config.ConfigurationFactory.parseConfiguration(ConfigurationFactory.java:95) at net.sf.ehcache.config.ConfigurationFactory.parseConfiguration(ConfigurationFactory.java:131) at net.sf.ehcache.CacheManager.parseConfiguration(CacheManager.java:241) at net.sf.ehcache.CacheManager.init(CacheManager.java:190) at net.sf.ehcache.CacheManager.&lt;init&gt;(CacheManager.java:183) at net.sf.ehcache.CacheManager.create(CacheManager.java:343) at net.sf.ehcache.CacheManager.getInstance(CacheManager.java:364) at net.sf.ehcache.constructs.web.filter.SimplePageCachingFilter.getCacheManager(SimplePageCachingFilter.java:100) at net.sf.ehcache.constructs.web.filter.CachingFilter.doInit(CachingFilter.java:83) at net.sf.ehcache.constructs.web.filter.Filter.init(Filter.java:191) ... 27 more</pre> <p> 这是我的web.xml,是按照网上例子搞的。</p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;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_2_5.xsd" version="2.5"&gt; &lt;!-- Shiro Filter --&gt; &lt;filter&gt; &lt;filter-name&gt;shiroFilter&lt;/filter-name&gt; &lt;filter-class&gt;org.springframework.web.filter.DelegatingFilterProxy&lt;/filter-class&gt; &lt;init-param&gt; &lt;param-name&gt;targetFilterLifecycle&lt;/param-name&gt; &lt;param-value&gt;true&lt;/param-value&gt; &lt;/init-param&gt; &lt;/filter&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;shiroFilter&lt;/filter-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;!-- 异常处理过滤器拦截所有请求/* 或可改成*.action --&gt; &lt;filter&gt; &lt;filter-name&gt;SulaiExceptionFilter&lt;/filter-name&gt; &lt;filter-class&gt;com.sulai.core.exception.filter.SulaiExceptionFilter&lt;/filter-class&gt; &lt;init-param&gt; &lt;param-name&gt;errorPage&lt;/param-name&gt; &lt;param-value&gt;/jsp/error/error.jsp&lt;/param-value&gt; &lt;/init-param&gt; &lt;/filter&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;SulaiExceptionFilter&lt;/filter-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;!-- Ehcache web 页面缓存过滤器 --&gt; &lt;filter&gt; &lt;filter-name&gt;PageCacheFilter&lt;/filter-name&gt; &lt;filter-class&gt;net.sf.ehcache.constructs.web.filter.SimplePageCachingFilter&lt;/filter-class&gt; &lt;/filter&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;PageCacheFilter&lt;/filter-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;!-- spring MVC 配置 --&gt; &lt;servlet&gt; &lt;servlet-name&gt;spring&lt;/servlet-name&gt; &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt; &lt;!-- 自定义servlet.xml配置文件的位置和名称,默认为WEB-INF目录下,名称为[&lt;servlet-name&gt;]-servlet.xml,如spring-servlet.xml --&gt; &lt;init-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt;classpath:spring-servlet.xml&lt;/param-value&gt; &lt;/init-param&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;spring&lt;/servlet-name&gt; &lt;url-pattern&gt;*.action&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;!-- DWR ScriptSession过滤器 --&gt; &lt;servlet&gt; &lt;servlet-name&gt;initScriptSessionListener&lt;/servlet-name&gt; &lt;servlet-class&gt; com.sulai.message.util.InitScriptSession &lt;/servlet-class&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;!--dwr servlet--&gt; &lt;servlet&gt; &lt;servlet-name&gt;dwr-invoker&lt;/servlet-name&gt; &lt;servlet-class&gt; org.directwebremoting.servlet.DwrServlet &lt;/servlet-class&gt; &lt;init-param&gt; &lt;param-name&gt;debug&lt;/param-name&gt; &lt;param-value&gt;true&lt;/param-value&gt; &lt;/init-param&gt; &lt;init-param&gt; &lt;param-name&gt;crossDomainSessionSecurity&lt;/param-name&gt; &lt;param-value&gt;false&lt;/param-value&gt; &lt;/init-param&gt; &lt;init-param&gt; &lt;param-name&gt;allowScriptTagRemoting&lt;/param-name&gt; &lt;param-value&gt;true&lt;/param-value&gt; &lt;/init-param&gt; &lt;init-param&gt; &lt;param-name&gt;pollAndCometEnabled&lt;/param-name&gt; &lt;param-value&gt;true&lt;/param-value&gt; &lt;/init-param&gt; &lt;init-param&gt; &lt;param-name&gt;activeReverseAjaxEnabled&lt;/param-name&gt; &lt;param-value&gt;true&lt;/param-value&gt; &lt;/init-param&gt; &lt;init-param&gt; &lt;param-name&gt;org.directwebremoting.extend.ServerLoadMonitor&lt;/param-name&gt; &lt;param-value&gt;org.directwebremoting.impl.PollingServerLoadMonitor&lt;/param-value&gt; &lt;/init-param&gt; &lt;init-param&gt; &lt;param-name&gt;disconnectedTime&lt;/param-name&gt; &lt;param-value&gt;60000&lt;/param-value&gt; &lt;/init-param&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;dwr-invoker&lt;/servlet-name&gt; &lt;url-pattern&gt;/dwr/*&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;!-- Spring log4j加载 --&gt; &lt;context-param&gt; &lt;param-name&gt;webAppRootKey&lt;/param-name&gt; &lt;param-value&gt;webapp.root&lt;/param-value&gt; &lt;/context-param&gt; &lt;context-param&gt; &lt;param-name&gt;log4jConfigLocation&lt;/param-name&gt; &lt;param-value&gt;classpath:log4j.xml&lt;/param-value&gt; &lt;/context-param&gt; &lt;context-param&gt; &lt;param-name&gt;log4jRefreshInterval&lt;/param-name&gt; &lt;param-value&gt;60000&lt;/param-value&gt; &lt;/context-param&gt; &lt;listener&gt; &lt;listener-class&gt;org.springframework.web.util.Log4jConfigListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;!-- Spring配置 --&gt; &lt;listener&gt; &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;!-- 定时器servletContext加载 --&gt; &lt;listener&gt; &lt;listener-class&gt;com.sulai.util.jobs.JobContextListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;!-- 指定Spring Bean的配置文件所在目录。默认配置在WEB-INF目录下 --&gt; &lt;context-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt; classpath:applicationContext.xml, classpath:applicationContext-dao.xml, classpath:applicationContext-shiro.xml, classpath:messages.xml &lt;/param-value&gt; &lt;/context-param&gt; &lt;filter&gt; &lt;filter-name&gt;Set Character Encoding&lt;/filter-name&gt; &lt;filter-class&gt;org.springframework.web.filter.CharacterEncodingFilter&lt;/filter-class&gt; &lt;init-param&gt; &lt;param-name&gt;encoding&lt;/param-name&gt; &lt;param-value&gt;utf8&lt;/param-value&gt; &lt;/init-param&gt; &lt;/filter&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;Set Character Encoding&lt;/filter-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;filter&gt; &lt;filter-name&gt;UrlRewriteFilter&lt;/filter-name&gt; &lt;filter-class&gt;org.tuckey.web.filters.urlrewrite.UrlRewriteFilter&lt;/filter-class&gt; &lt;/filter&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;UrlRewriteFilter&lt;/filter-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;dispatcher&gt;REQUEST&lt;/dispatcher&gt; &lt;dispatcher&gt;FORWARD&lt;/dispatcher&gt; &lt;/filter-mapping&gt; &lt;!-- 404 自定义页面 --&gt; &lt;error-page&gt; &lt;error-code&gt;404&lt;/error-code&gt; &lt;location&gt; /jsp/error/error.jsp &lt;/location&gt; &lt;/error-page&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;index.action&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;/web-app&gt;</pre> <p> 这是 ehcache.xml</p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true" monitoring="autodetect" dynamicConfig="true"&gt; &lt;diskStore path="D:\\workspace\\sulai\\webapp\\pageCache"/&gt; &lt;cacheManagerEventListenerFactory class="" properties=""/&gt; &lt;defaultCache maxElementsInMemory="1000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" maxElementsOnDisk="10000" diskSpoolBufferSizeMB="30" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" statistics="false" /&gt; &lt;cache name="PageCacheFilter" maxElementsInMemory="1000" maxElementsOnDisk="10000" eternal="false" overflowToDisk="true" diskSpoolBufferSizeMB="20" timeToIdleSeconds="300" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LFU" transactionalMode="off" /&gt; &lt;/ehcache&gt;</pre> <p> 麻烦大神们看看哪里有问题?</p> <p> </p> </div>
数据库连接错误
项目架构struts2+hibernate+spring有一个每隔一秒的spring定时器执行数据库的增删改查操作 事物配置如下: <!-- 指定事务管理器 --> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" /> <!-- 配置事务的传播特性 --> <aop:config proxy-target-class="true"> <!-- 配置一个切入点,匹配dao包下 所有以Impl结尾的类的所有方法的执行 --> <aop:advisor pointcut="execution(* *..*DaoImpl.*(..))" advice-ref="txAdvice" /> <!-- 指定在txAdvice切入点应用txAdvice事务切面 --> </aop:config> <tx:advice id="txAdvice"> <tx:attributes> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="query*" read-only="true" /> <tx:method name="find*" read-only="true"/> <tx:method name="get*" read-only="true"/> <tx:method name="execute*" propagation="REQUIRED"/> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> 当使用此配置时(定时任务执行一段时间后)出现如下异常: Exception in thread "com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#1" java.lang.OutOfMemoryError: Java heap space 当使用如下配置时: <!-- 指定事务管理器 --> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" /> <!-- 配置事务的传播特性 --> <aop:config proxy-target-class="true"> <!-- 配置一个切入点,匹配dao包下 所有以Impl结尾的类的所有方法的执行 --> <aop:advisor pointcut="execution(* com.lyn.job.company.service.impl.UpCompanyMatchManagerServiceImpl.*(..))" advice-ref="txAdvice" /> <!-- 指定在txAdvice切入点应用txAdvice事务切面 --> </aop:config> <tx:advice id="txAdvice"> <tx:attributes> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="query*" read-only="true" /> <tx:method name="find*" read-only="true"/> <tx:method name="get*" read-only="true"/> <tx:method name="execute*" propagation="REQUIRED"/> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> 注:此配置事物直接指定到了定时器的service层,但是定时任务执行一段时间后程序报如下错误: 2012-07-30 09:51:19,716 ERROR [org.quartz.core.ErrorLogger] - [Job (DEFAULT.upCompanyMatchJobDetail threw an exception.] org.quartz.SchedulerException: Job threw an unhandled exception. [See nested exception: org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Cannot open connection] at org.quartz.core.JobRunShell.run(JobRunShell.java:213) at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:534) Caused by: org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Cannot open connection at org.springframework.orm.hibernate3.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:596) at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:371) at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:354) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:103) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:625) at com.lyn.job.company.service.impl.UpCompanyMatchManagerServiceImpl$$EnhancerByCGLIB$$a5f981c9.match(<generated>) at com.lyn.job.company.UpCompanyMatchJob.execute(UpCompanyMatchJob.java:20) at org.quartz.core.JobRunShell.run(JobRunShell.java:202) ... 1 more Caused by: org.hibernate.exception.GenericJDBCException: Cannot open connection at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:126) at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:114) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:52) at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:449) at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:167) at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:142) at org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:85) at org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1354) at org.springframework.orm.hibernate3.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:555) ... 11 more Caused by: java.sql.SQLException: Connections could not be acquired from the underlying database! at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:106) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:529) at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:128) at org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider.getConnection(LocalDataSourceConnectionProvider.java:81) at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:446) ... 16 more Caused by: com.mchange.v2.resourcepool.CannotAcquireResourceException: A ResourcePool could not acquire a resource from its primary factory or source. at com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(BasicResourcePool.java:1319) at com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(BasicResourcePool.java:557) at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:477) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:525) ... 19 more 急求指点,万分感谢!
struts2注解url没跳转到action里的方法,没报错也没跳转
我补下图片: ![图片说明](https://img-ask.csdn.net/upload/201509/21/1442781387_310218.png) package com.AppServer.action; import javax.annotation.Resource; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.ExceptionMapping; import org.apache.struts2.convention.annotation.ExceptionMappings; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.ParentPackage; import org.apache.struts2.convention.annotation.Result; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.stereotype.Service; import com.AppServer.bean.User; import com.AppServer.dao.UserDAO; import com.AppServer.service.UserService; import com.demo.interceptor.MethodCacheInterceptor; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; @Controller @ParentPackage("struts-default") @Namespace(value = "msgAction") @ExceptionMappings({ @ExceptionMapping(exception = "java.lange.RuntimeException", result = "error") }) public class MsgAction extends ActionSupport { private String username; private String password; @Resource private UserService userService; @Action(value = "msg" , results = { @Result(name = "success", location = "/success.jsp"), @Result(name = "failure", location = "/failure.jsp"), @Result(name = "error", location = "/login.jsp")}) //获取用户信息 public String getInfo() { System.out.println("进来玩"); return SUCCESS; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } url访问如下:http://127.0.0.1:8080/AppServer_1.1/msgAction/msg.do 访问之后没报错,没进去getInfo这个方法 struts2.xml: <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <!-- 指定Web应用的默认编码,相当于调用request的setCharacterEncoding方法 --> <constant name="struts.i18n.encoding" value="UTF-8" /> <!-- 设置浏览器是否缓存静态内容,默认值为true(生产环境下使用),开发阶段最好关闭 --> <constant name="struts.serve.static.browserCache" value="false" /> <!-- 当Struts2的配置文件修改后,系统是否自动重新加载配置文件,默认值为false(生产环境下使用),开发阶段最好打开 --> <constant name="struts.configuration.xml.reload" value="true" /> <!-- 开发模式下使用,这样可以打印出更详细的日志信息 --> <constant name="struts.devMode" value="true" /> <!-- 默认的视图主题 --> <constant name="struts.ui.theme" value="simple" /> <!-- 把Action对象交给Spring创建和管理 --> <constant name="struts.objectFactory" value="spring" /> <!-- Struts2处理的请求后缀,默认值是action --> <constant name="struts.action.extension" value="do" /> <!-- 国际化资源文件 <constant name="struts.custom.i18n.resources" value="globalMessages" /> --> <package name="msg" extends="struts-default"> <default-action-ref name="indexPage" /> <global-results> <result name="exceptionPage">/error/exceptionPage.jsp</result> </global-results> <global-exception-mappings> <exception-mapping result="exceptionPage" exception="java.lang.Exception" /> </global-exception-mappings> <action name="indexPage"> <result>/login.jsp</result> </action> <!-- <action name="msg" method="getInfo" class="com.AppServer.action.MsgAction"> <result name="success">/success.jsp</result> <result name="failure">/failure.jsp</result> <result name="error">/login.jsp</result> </action> --> </package> </struts> 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:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd" default-autowire="byName" default-lazy-init="true"> <!-- 说明:下面有的Bean配置提供了多种方案,请根据需要采用某一种(别忘了注释掉其他同类方案) --> <!-- 自动扫描Spring注解配置 并保证@Required,@Autowired的属性被注入--> <context:component-scan base-package="com" /> <!-- 自动加载属性配置文件 --> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 配置数据源:方法一,使用C3P0方式(推荐) --> <!-- <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" --> <!-- destroy-method="close" --> <!-- p:driverClass="${jdbc.driverClassName}" --> <!-- p:jdbcUrl="${jdbc.url}" --> <!-- p:user="${jdbc.username}" --> <!-- p:password="${jdbc.password}" /> --> <!-- <context:property-placeholder location="classpath:jdbc.properties"/> --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <!-- property池启动时的初始值 --> <property name="password" value="${jdbc.password}"/> <!-- 连接name="initialSize" value="${initialSize}"/>--> <property name="initialSize" value="1"/> <!-- 连接池的最大值 --> <property name="maxActive" value="500"/> <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 --> <property name="maxIdle" value="2"/> <!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 --> <property name="minIdle" value="1"/> </bean> <!-- 配置数据源:方法二,使用DBCP方式(不推荐) --> <!-- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}" /> --> <!-- 配置数据源:方法三,使用JNDI方式 --> <!-- <jee:jndi-lookup id="dataSource" jndi-name="${jndi.name}" /> --> <!-- 配置Hibernate的数据源代理工厂:方法一,使用p属性通配符,按文件名搜索匹配的映射文件 --> <!-- <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" p:dataSource-ref="dataSource" > <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop> <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop> <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop> </props> </property> 加载hibernate的jpa注解形式实体 <property name="packagesToScan"> <list> <value>com.xmm.demo.domain*</value> </list> </property> </bean> --> <!-- 配置Hibernate的数据源代理工厂:方法二,使用list集合,按文件名搜索匹配的映射文件 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" p:dataSource-ref="dataSource"> <property name="mappingLocations"> <list> <value>classpath*:/com/**/*.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop> <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop> <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop> </props> </property> </bean> <!-- 配置Hibernate的数据源代理工厂:方法三,使用p属性通配符,按目录搜索映射文件 --> <!-- <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" p:dataSource-ref="dataSource" p:mappingDirectoryLocations="classpath*:/com/**/domain"> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop> <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop> <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop> </props> </property> </bean> --> <!-- 配置Hibernate的数据源代理工厂:方法四,使用hibernate.cfg.xml --> <!-- <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" p:dataSource-ref="dataSource" p:configLocation="classpath:hibernate.cfg.xml"> </bean> --> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" p:sessionFactory-ref="sessionFactory" /> <!-- 配置声明式事务:方法一,在Service实现类或者public实现方法上使用注解@Transactional,则此类或方法就会启用事务机制 --> <!-- <tx:annotation-driven transaction-manager="transactionManager" /> --> <!-- 配置声明式事务:方法二,使用tx/aop命名空间的配置(其实还有方法三,由于快要过时不推荐使用了,这里就不给出方法三的配置了) --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="edit*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="new*" propagation="REQUIRED" /> <tx:method name="set*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="change*" propagation="REQUIRED" /> <tx:method name="get*" propagation="REQUIRED" read-only="true" /> <tx:method name="find*" propagation="REQUIRED" read-only="true" /> <tx:method name="load*" propagation="REQUIRED" read-only="true" /> <tx:method name="search*" propagation="REQUIRED" read-only="true" /> <tx:method name="*" propagation="REQUIRED" read-only="true" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="mypointcut" expression="execution(* com.**.service..*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="mypointcut" /> </aop:config> <!-- 下面三个Bean的配置可有可无,但配置后用处更大,通常用于BaseDao类、其他Dao类或特殊工具类中 --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate" p:sessionFactory-ref="sessionFactory" /> <bean id="hibernateDaoSupport" class="org.springframework.orm.hibernate4.support.HibernateDaoSupport" p:hibernateTemplate-ref="hibernateTemplate" abstract="true"/> <bean id="sessionFactoryUtils" class="org.springframework.orm.hibernate4.SessionFactoryUtils" abstract="true"/> </beans> tomcat6.0:服务器运行正常: 九月 21, 2015 4:22:24 上午 org.apache.catalina.core.AprLifecycleListener init 信息: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: D:\Java\jdk1.7.0\bin;E:\tomcat6\bin 九月 21, 2015 4:22:25 上午 org.apache.coyote.http11.Http11Protocol init 信息: Initializing Coyote HTTP/1.1 on http-8080 九月 21, 2015 4:22:25 上午 org.apache.catalina.startup.Catalina load 信息: Initialization processed in 516 ms 九月 21, 2015 4:22:25 上午 org.apache.catalina.core.StandardService start 信息: Starting service Catalina 九月 21, 2015 4:22:25 上午 org.apache.catalina.core.StandardEngine start 信息: Starting Servlet Engine: Apache Tomcat/6.0.41 九月 21, 2015 4:22:25 上午 org.apache.catalina.startup.HostConfig deployDirectory 信息: Deploying web application directory AppServer_1.1 九月 21, 2015 4:22:25 上午 org.apache.catalina.loader.WebappClassLoader validateJarFile 信息: validateJarFile(E:\tomcat6\webapps\AppServer_1.1\WEB-INF\lib\servlet-api.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class 九月 21, 2015 4:22:26 上午 org.apache.catalina.core.ApplicationContext log 信息: Set web app root system property: 'webapp.root' = [E:\tomcat6\webapps\AppServer_1.1\] 九月 21, 2015 4:22:26 上午 org.apache.catalina.core.ApplicationContext log 信息: Initializing log4j from [classpath:log4j.properties] 九月 21, 2015 4:22:26 上午 org.apache.catalina.core.ApplicationContext log 信息: Initializing Spring root WebApplicationContext 九月 21, 2015 4:22:34 上午 org.apache.coyote.http11.Http11Protocol start 信息: Starting Coyote HTTP/1.1 on http-8080 九月 21, 2015 4:22:34 上午 org.apache.jk.common.ChannelSocket init 信息: JK: ajp13 listening on /0.0.0.0:8009 九月 21, 2015 4:22:34 上午 org.apache.jk.server.JkMain start 信息: Jk running ID=0 time=0/23 config=null 九月 21, 2015 4:22:34 上午 org.apache.catalina.startup.Catalina start 信息: Server startup in 9364 ms 测试定时任务:2015-09-21 04:30:00:074 测试定时任务:2015-09-21 04:40:00:004 url访问地址:http://127.0.0.1:8080/AppServer_1.1/msgAction/msg.do 没有进去action的getinfo方法,这是为什么?而且也没有任何的报错!!!!!!!!!!!
There is no Action mapped for namespace
使用的是J2EE+SHH框架, 具体代码如下: --- **struts.xml** ``` <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <constant name="struts.custom.i18n.resources" value="message" /> <constant name="struts.i18n.encoding" value="UTF-8" /> <!-- 指定Struts 2默认的ObjectFactory Bean - 交给Spring管理 --> <constant name="struts.objectFactory" value="spring" /> <!-- 开发者模式 --> <!-- <constant name="struts.devMode" value="true" /> --> <!-- 指定每次配置文件更改后,自动重新加载 --> <constant name="struts.configuration.xml.reload" value="false" /> </struts> ``` --- **applicationContext.xml** ``` **<?xml version="1.0" encoding="UTF-8"?> <!-- context是自动扫描和使用注解的上下文前缀;aop,tx是事物管理的前缀 -->** <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task" 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/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd" default-autowire="byName"> <!-- 采用自动扫描的方式查找bean(DAO,Service等等),多个用逗号隔开 --> <context:component-scan base-package="com.cheer.bookshop" /> <!-- 定时器任务 --> <task:annotation-driven /> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <description>配置数据源</description> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/bookstore?useUnicode=true&amp;characterEncoding=UTF-8"></property> <property name="username" value="root"></property> <property name="password" value="123456"></property> <!-- 初始化连接数量 --> <property name="initialSize" value="1"/> <!-- 最大活动连接数量,一般等于数据库的最大并发数 --> <property name="maxActive" value="100"/> <!-- 最大空闲(等待)连接数量 --> <property name="maxIdle" value="-1"/> <!-- 最小空闲(等待)连接数量 --> <property name="minIdle" value="0"/> <!-- 获取连接时等待时间,超出将抛异常,单位毫秒 --> <property name="maxWait" value="10000"/> </bean> <!-- 配置hibernate session工厂 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <description>将数据源注入到sessionFactory,使用注解方式</description> <property name="dataSource" ref="dataSource"></property> <!-- 配置hibernate的一些属性 --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.current_session_context_class">thread</prop> <prop key="hibernate.connection.release_mode">after_transaction</prop><!-- 释放session --> </props> </property> <!-- 自动扫描注解方式配置的hibernate映射文件(实体类) --> <property name="packagesToScan"> <list> <value>com.cheer.bookshop.Model</value> </list> </property> </bean> <!-- 定义事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <description> 增加事务管理</description> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 拦截器方式配置事务特性 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <!-- 给business配置事务管理 --> <aop:config proxy-target-class="true"> <aop:pointcut id="allManagerMethod" expression="execution (* com.cheer.bookshop.*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="allManagerMethod" /> </aop:config> </beans> ``` --- **JSP页面登陆Form表单** ``` <s:form action="userlogin.action" method="post"> <p><font color="red">&nbsp;&nbsp;&nbsp;${msg}</font></p> <div class="form_row"> <label class="contact"><strong>Username:</strong></label> <input type="text" class="contact_input" name="user.username" value="${user.username}"/> </div> <div class="form_row"> <label class="contact"><strong>Password:</strong></label> <input type="password" class="contact_input" name="user.password" value="${user.password}"/> </div> <div class="form_row"> <div class="terms"> <input type="checkbox" name="terms" /> Remember me </div> </div> <div class="form_row"> <input type="submit" class="register" value="login" /> </div> </s:form> ``` --- **Action类** ``` package com.cheer.bookshop.action; import java.io.IOException; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.Result; import com.cheer.bookshop.Model.User; import com.cheer.bookshop.service.impl.UserServiceImpl; import com.opensymphony.xwork2.ActionSupport; @Namespace("/") public class UserAction extends ActionSupport { @Resource private UserServiceImpl userServiceImpl; private User user; private String msg; //用户登录 @Action(value = "userlogin", results = {@Result(name = "success", location = "/index.jsp"), @Result(name = "input", location = "/jsp/user/myaccount.jsp", type = "redirect") }) public String login(){ User userdb = userServiceImpl.login(user.getUsername()); if(userdb != null){ String password = user.getPassword(); if(password.equals(userdb.getPassword())){ user=userdb; return SUCCESS; }else{ msg="密码错误,请重新输入!"; return INPUT; } }else{ msg="用户名不存在,请注册!"; return INPUT; } } //用户注册 @Action(value = "userregister", results = {@Result(name = "success", location = "/jsp/user/myaccount.jsp", type = "redirect") }) public String register(){ userServiceImpl.register(user); return SUCCESS; } //验证用户名是否已经被使用 @Action(value = "validateUsername") public String validateUsername() throws IOException{ HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html;charset=UTF-8"); String username = request.getParameter("username"); boolean flag = userServiceImpl.validateUsername(username); if(flag){ response.getWriter().println("<p><font color='red'>用户名已经存在</font></p>"); }else{ response.getWriter().println("<p><font color='green'>用户名可以使用</font></p>"); } return NONE; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } } ``` --- 如上,Action有配置userlogin,登陆页form表单提交路径也是一样,单就是无法调整至aciton里,eclipse也没有报错,该如何解决? There is no Action mapped for namespace / and action name userlogin.
ssm使用shiro启动报错
报错内容 Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginRealm': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.warehouse.service.UserLogingService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.warehouse.service.UserLogingService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)} shiro.xml配置 ``` <!-- 配置Shiro核心Filter --> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <!-- 安全管理器 --> <property name="securityManager" ref="securityManager" /> <!-- 未认证,跳转到哪个页面 --> <property name="loginUrl" value="/login.html" /> <!-- 登陆成功页面 --> <property name="successUrl" value="/index.html" /> <!-- 认证后,没有权限跳转页面 --> <property name="unauthorizedUrl" value="/unauthorized.html" /> <property name="filterChainDefinitions"> <value> /WEB-INF/views/login.html* = anon /loging.do* = anon /WEB-INF/llb/* = anon /res/** = anon /** = authc </value> </property> </bean> <!-- 配置Realm --> <bean id="loginRealm" class="com.warehouse.service.LoginRealm"> </bean> <!-- 安全管理器 --> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="loginRealm" /> <!-- <property name="cacheManager" ref="shiroCacheManager" /> --> </bean> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> ``` applicationContext.xml配置 ``` applicationContext.xml配置 <import resource="applicationContext-shiro.xml"/> <!-- 开启定时任务 --> <task:annotation-driven /> <!-- MyBatis配置 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 显式指定Mapper文件位置 --> <property name="mapperLocations" value="classpath*:/mybatis/*Mapper.xml" /> <!-- mybatis配置文件路径 --> <property name="configLocation" value="classpath:/mybatis-config.xml" /> <property name="typeHandlersPackage" value="package com.warehouse.util" /> </bean> <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory" /> <!-- 这个执行器会批量执行更新语句, 还有SIMPLE 和 REUSE --> <!-- <constructor-arg index="1" value="BATCH"/> --> </bean> <!-- 扫描basePackage接口 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 映射器接口文件的包路径, --> <property name="basePackage" value="com.warehouse.dao" /> </bean> <!-- 使用annotation定义事务 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" /> <!-- 数据源配置, 使用Tomcat JDBC连接池 --> <bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close"> <!-- Connection Info --> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- Connection Pooling Info --> <property name="maxActive" value="${jdbc.pool.maxActive}" /> <property name="maxIdle" value="${jdbc.pool.maxIdle}" /> <property name="minIdle" value="0" /> <property name="defaultAutoCommit" value="false" /> </bean> <!-- production环境 --> <beans profile="production"> <context:property-placeholder ignore-unresolvable="true" file-encoding="utf-8" location="classpath:config.properties,classpath:jdbc.properties" /> </beans> ``` springMVC.xml配置 ``` <context:component-scan base-package="com.warehouse.*" /> <!--jsp可以不用添加这个 如果修改成html就必须用这个 --> <mvc:default-servlet-handler /> <mvc:annotation-driven /> <!--上面这个是为了html可以用 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /> </list> </property> </bean> <!--模板 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /> </list> </property> </bean> <mvc:resources mapping="/res/**" location="/res/" /> <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <property name="templateLoaderPath" value="/WEB-INF/views/" /> <property name="freemarkerSettings"> <props> <prop key="template_update_delay">0</prop> <prop key="default_encoding">UTF-8</prop> <prop key="number_format">0.##########</prop> <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop> <prop key="classic_compatible">true</prop> <prop key="template_exception_handler">ignore</prop> <prop key="auto_import">ftl/public.ftl as p,ftl/page.ftl as pg </prop> </props> </property> <property name="freemarkerVariables"> <map> <entry key="listProduct" value-ref="ProductDiretciv" /> </map> </property> </bean> <bean id="viewResolver" class="com.warehouse.freemarker.RichFreeMarkerViewResolver"> <property name="suffix"> <value>.html</value> </property> <property name="contentType" value="text/html;charset=UTF-8"></property> </bean> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views" /> <property name="suffix" value=".*" /> </bean> <!-- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/views/" p:suffix=".html"/> --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /> </list> </property> </bean> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> ``` @Controller @Scope("prototype") public class UserLogingController { @RequestMapping("loging.do") @ResponseBody public String loging(ForeginUser fuser) { Subject subject = SecurityUtils.getSubject(); AuthenticationToken token = new UsernamePasswordToken(fuser.getUsername(), fuser.getPassword()); try { subject.login(token); return _HTML_INDEX_; } catch (AuthenticationException e) { e.printStackTrace(); return _HTML_LOGIN_; } } }@Controller @Scope("prototype") public class UserLogingController { @RequestMapping("loging.do") @ResponseBody public String loging(ForeginUser fuser) { Subject subject = SecurityUtils.getSubject(); AuthenticationToken token = new UsernamePasswordToken(fuser.getUsername(), fuser.getPassword()); try { subject.login(token); return _HTML_INDEX_; } catch (AuthenticationException e) { e.printStackTrace(); return _HTML_LOGIN_; } } } ``` ``` package com.warehouse.realm; public class LoginRealm extends AuthorizingRealm { @Resource private UserLogingService userlogingService; @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) { return null; } @Override // 认证 protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken upToken = (UsernamePasswordToken) token; ForeginUser resultUser = userlogingService.findByUsername(upToken.getUsername()); if (resultUser == null) { return new SimpleAuthenticationInfo(resultUser, null, getName()); } else { return new SimpleAuthenticationInfo(resultUser, resultUser.getPassword(), getName()); } } } package com.warehouse.service; @Service public class UserLogingServiceImpl implements UserLogingService { @Resource private UserLogingMapper userLogingMapeer; @Override public ForeginUser checkLoaderInfo(ForeginUser fuser) { return userLogingMapeer.findByUser(fuser); } @Override public ForeginUser findByUsername(String username) { return userLogingMapeer.findByUsername(username); } }
相见恨晚的超实用网站
相见恨晚的超实用网站 持续更新中。。。
爬虫福利二 之 妹子图网MM批量下载
爬虫福利一:27报网MM批量下载 点击 看了本文,相信大家对爬虫一定会产生强烈的兴趣,激励自己去学习爬虫,在这里提前祝:大家学有所成! 目标网站:妹子图网 环境:Python3.x 相关第三方模块:requests、beautifulsoup4 Re:各位在测试时只需要将代码里的变量path 指定为你当前系统要保存的路径,使用 python xxx.py 或IDE运行即可。 ...
字节跳动视频编解码面经
三四月份投了字节跳动的实习(图形图像岗位),然后hr打电话过来问了一下会不会opengl,c++,shador,当时只会一点c++,其他两个都不会,也就直接被拒了。 七月初内推了字节跳动的提前批,因为内推没有具体的岗位,hr又打电话问要不要考虑一下图形图像岗,我说实习投过这个岗位不合适,不会opengl和shador,然后hr就说秋招更看重基础。我当时想着能进去就不错了,管他哪个岗呢,就同意了面试...
开源一个功能完整的SpringBoot项目框架
福利来了,给大家带来一个福利。 最近想了解一下有关Spring Boot的开源项目,看了很多开源的框架,大多是一些demo或者是一个未成形的项目,基本功能都不完整,尤其是用户权限和菜单方面几乎没有完整的。 想到我之前做的框架,里面通用模块有:用户模块,权限模块,菜单模块,功能模块也齐全了,每一个功能都是完整的。 打算把这个框架分享出来,供大家使用和学习。 为什么用框架? 框架可以学习整体...
源码阅读(19):Java中主要的Map结构——HashMap容器(下1)
HashMap容器从字面的理解就是,基于Hash算法构造的Map容器。从数据结构的知识体系来说,HashMap容器是散列表在Java中的具体表达(并非线性表结构)。具体来说就是,利用K-V键值对中键对象的某个属性(默认使用该对象的“内存起始位置”这一属性)作为计算依据进行哈希计算(调用hashCode方法),然后再以计算后的返回值为依据,将当前K-V键值对在符合HashMap容器构造原则的基础上,放置到HashMap容器的某个位置上,且这个位置和之前添加的K-V键值对的存储位置完全独立,不一定构成连续的存储
c++制作的植物大战僵尸,开源,一代二代结合游戏
此游戏全部由本人自己制作完成。游戏大部分的素材来源于原版游戏素材,少部分搜集于网络,以及自己制作。 此游戏为同人游戏而且仅供学习交流使用,任何人未经授权,不得对本游戏进行更改、盗用等,否则后果自负。目前有六种僵尸和六种植物,植物和僵尸的动画都是本人做的。qq:2117610943 开源代码下载 提取码:3vzm 点击下载--&gt; 11月28日 新增四种植物 统一植物画风,全部修...
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它是一个过程,是一个不断累积、不断沉淀、不断总结、善于传达自己的个人见解以及乐于分享的过程。
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过...
Python——画一棵漂亮的樱花树(不同种樱花+玫瑰+圣诞树喔)
最近翻到一篇知乎,上面有不少用Python(大多是turtle库)绘制的树图,感觉很漂亮,我整理了一下,挑了一些我觉得不错的代码分享给大家(这些我都测试过,确实可以生成) one 樱花树 动态生成樱花 效果图(这个是动态的): 实现代码 import turtle as T import random import time # 画樱花的躯干(60,t) def Tree(branch, ...
linux系列之常用运维命令整理笔录
本博客记录工作中需要的linux运维命令,大学时候开始接触linux,会一些基本操作,可是都没有整理起来,加上是做开发,不做运维,有些命令忘记了,所以现在整理成博客,当然vi,文件操作等就不介绍了,慢慢积累一些其它拓展的命令,博客不定时更新 free -m 其中:m表示兆,也可以用g,注意都要小写 Men:表示物理内存统计 total:表示物理内存总数(total=used+free) use...
Python 基础(一):入门必备知识
Python 入门必备知识,你都掌握了吗?
深度学习图像算法在内容安全领域的应用
互联网给人们生活带来便利的同时也隐含了大量不良信息,防范互联网平台有害内容传播引起了多方面的高度关注。本次演讲从技术层面分享网易易盾在内容安全领域的算法实践经验,包括深度...
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 IT 类的外包开发,是非标品开发,所以很有可能在开发过程中会有这样那样的需求修改,而这种需求修改很容易造成扯皮,进而影响到费用支付,甚至出现做完了项目收不到钱的情况。 那么,怎么保证自己的薪酬安全呢? 我们在开工前,一定要做好一些证据方面的准备(也就是“讨薪”的理论依据),这其中最重要的就是需求文档和验收标准。一定要让需求方提供这两个文档资料作为开发的基础。之后开发...
网页实现一个简单的音乐播放器(大佬别看。(⊙﹏⊙))
今天闲着无事,就想写点东西。然后听了下歌,就打算写个播放器。 于是乎用h5 audio的加上js简单的播放器完工了。 演示地点演示 html代码如下` music 这个年纪 七月的风 音乐 ` 然后就是css`*{ margin: 0; padding: 0; text-decoration: none; list-...
Python十大装B语法
Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。
数据库优化 - SQL优化
以实际SQL入手,带你一步一步走上SQL优化之路!
2019年11月中国大陆编程语言排行榜
2019年11月2日,我统计了某招聘网站,获得有效程序员招聘数据9万条。针对招聘信息,提取编程语言关键字,并统计如下: 编程语言比例 rank pl_ percentage 1 java 33.62% 2 cpp 16.42% 3 c_sharp 12.82% 4 javascript 12.31% 5 python 7.93% 6 go 7.25% 7 p...
通俗易懂地给女朋友讲:线程池的内部原理
餐盘在灯光的照耀下格外晶莹洁白,女朋友拿起红酒杯轻轻地抿了一小口,对我说:“经常听你说线程池,到底线程池到底是个什么原理?”
经典算法(5)杨辉三角
写在前面: 我是 扬帆向海,这个昵称来源于我的名字以及女朋友的名字。我热爱技术、热爱开源、热爱编程。技术是开源的、知识是共享的。 这博客是对自己学习的一点点总结及记录,如果您对 Java、算法 感兴趣,可以关注我的动态,我们一起学习。 用知识改变命运,让我们的家人过上更好的生活。 目录一、杨辉三角的介绍二、杨辉三角的算法思想三、代码实现1.第一种写法2.第二种写法 一、杨辉三角的介绍 百度
腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹?
昨天,有网友私信我,说去阿里面试,彻底的被打击到了。问了为什么网上大量使用ThreadLocal的源码都会加上private static?他被难住了,因为他从来都没有考虑过这个问题。无独有偶,今天笔者又发现有网友吐槽了一道腾讯的面试题,我们一起来看看。 腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹? 在互联网职场论坛,一名程序员发帖求助到。二面腾讯,其中一个算法题:64匹...
面试官:你连RESTful都不知道我怎么敢要你?
干货,2019 RESTful最贱实践
为啥国人偏爱Mybatis,而老外喜欢Hibernate/JPA呢?
关于SQL和ORM的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行了一番讨论,感触还是有一些,于是就有了今天这篇文。 声明:本文不会下关于Mybatis和JPA两个持久层框架哪个更好这样的结论。只是摆事实,讲道理,所以,请各位看官勿喷。 一、事件起因 关于Mybatis和JPA孰优孰劣的问题,争论已经很多年了。一直也没有结论,毕竟每个人的喜好和习惯是大不相同的。我也看...
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // doshom...
致 Python 初学者
欢迎来到“Python进阶”专栏!来到这里的每一位同学,应该大致上学习了很多 Python 的基础知识,正在努力成长的过程中。在此期间,一定遇到了很多的困惑,对未来的学习方向感到迷茫。我非常理解你们所面临的处境。我从2007年开始接触 python 这门编程语言,从2009年开始单一使用 python 应对所有的开发工作,直至今天。回顾自己的学习过程,也曾经遇到过无数的困难,也曾经迷茫过、困惑过。开办这个专栏,正是为了帮助像我当年一样困惑的 Python 初学者走出困境、快速成长。希望我的经验能真正帮到你
Python 编程实用技巧
Python是一门很灵活的语言,也有很多实用的方法,有时候实现一个功能可以用多种方法实现,我这里总结了一些常用的方法,并会持续更新。
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,
程序员:我终于知道post和get的区别
IT界知名的程序员曾说:对于那些月薪三万以下,自称IT工程师的码农们,其实我们从来没有把他们归为我们IT工程师的队伍。他们虽然总是以IT工程师自居,但只是他们一厢情愿罢了。 此话一出,不知激起了多少(码农)程序员的愤怒,却又无可奈何,于是码农问程序员。 码农:你知道get和post请求到底有什么区别? 程序员:你看这篇就知道了。 码农:你月薪三万了? 程序员:嗯。 码农:你是怎么做到的? 程序员:
"狗屁不通文章生成器"登顶GitHub热榜,分分钟写出万字形式主义大作
前言 GitHub 被誉为全球最大的同性交友网站,……,陪伴我们已经走过 10+ 年时间,它托管了大量的软件代码,同时也承载了程序员无尽的欢乐。 上周给大家分享了一篇10个让你笑的合不拢嘴的Github项目,而且还拿了7万+个Star哦,有兴趣的朋友,可以看看, 印象最深刻的是 “ 呼吸不止,码字不停 ”: 老实交代,你是不是经常准备写个技术博客,打开word后瞬间灵感便秘,码不出字? 有什么
推荐几款比较实用的工具,网站
1.盘百度PanDownload 这个云盘工具是免费的,可以进行资源搜索,提速(偶尔会抽风????) 不要去某站买付费的???? PanDownload下载地址 2.BeJSON 这是一款拥有各种在线工具的网站,推荐它的主要原因是网站简洁,功能齐全,广告相比其他广告好太多了 bejson网站 3.二维码美化 这个网站的二维码美化很好看,网站界面也很...
《程序人生》系列-这个程序员只用了20行代码就拿了冠军
你知道的越多,你不知道的越多 点赞再看,养成习惯GitHub上已经开源https://github.com/JavaFamily,有一线大厂面试点脑图,欢迎Star和完善 前言 这一期不算《吊打面试官》系列的,所有没前言我直接开始。 絮叨 本来应该是没有这期的,看过我上期的小伙伴应该是知道的嘛,双十一比较忙嘛,要值班又要去帮忙拍摄年会的视频素材,还得搞个程序员一天的Vlog,还要写BU
程序员把地府后台管理系统做出来了,还有3.0版本!12月7号最新消息:已在开发中有github地址
第一幕:缘起 听说阎王爷要做个生死簿后台管理系统,我们派去了一个程序员…… 996程序员做的梦: 第一场:团队招募 为了应对地府管理危机,阎王打算找“人”开发一套地府后台管理系统,于是就在地府总经办群中发了项目需求。 话说还是中国电信的信号好,地府都是满格,哈哈!!! 经常会有外行朋友问:看某网站做的不错,功能也简单,你帮忙做一下? 而这次,面对这样的需求,这个程序员
网易云6亿用户音乐推荐算法
网易云音乐是音乐爱好者的集聚地,云音乐推荐系统致力于通过 AI 算法的落地,实现用户千人千面的个性化推荐,为用户带来不一样的听歌体验。 本次分享重点介绍 AI 算法在音乐推荐中的应用实践,以及在算法落地过程中遇到的挑战和解决方案。 将从如下两个部分展开: AI 算法在音乐推荐中的应用 音乐场景下的 AI 思考 从 2013 年 4 月正式上线至今,网易云音乐平台持续提供着:乐屏社区、UGC
Spring Security 实战干货:基于注解的接口角色访问控制
1. 前言 欢迎阅读 Spring Security 实战干货[1] 系列文章 。在上一篇 基于配置的接口角色访问控制[2] 我们讲解了如何通过 javaConfig 的方式配置接口的角色访问控制。其实还有一种更加灵活的配置方式 基于注解 。今天我们就来探讨一下。DEMO 获取方式在文末。 2. Spring Security 方法安全 Spring Security 基于注解的安全...
8年经验面试官详解 Java 面试秘诀
    作者 | 胡书敏 责编 | 刘静 出品 | CSDN(ID:CSDNnews) 本人目前在一家知名外企担任架构师,而且最近八年来,在多家外企和互联网公司担任Java技术面试官,前后累计面试了有两三百位候选人。在本文里,就将结合本人的面试经验,针对Java初学者、Java初级开发和Java开发,给出若干准备简历和准备面试的建议。   Java程序员准备和投递简历的实
面试官如何考察你的思维方式?
1.两种思维方式在求职面试中,经常会考察这种问题:北京有多少量特斯拉汽车? 某胡同口的煎饼摊一年能卖出多少个煎饼? 深圳有多少个产品经理? 一辆公交车里能装下多少个乒乓球? 一
碎片化的时代,如何学习
今天周末,和大家聊聊学习这件事情。 在如今这个社会,我们的时间被各类 APP 撕的粉碎。 刷知乎、刷微博、刷朋友圈; 看论坛、看博客、看公号; 等等形形色色的信息和知识获取方式一个都不错过。 貌似学了很多,但是却感觉没什么用。 要解决上面这些问题,首先要分清楚一点,什么是信息,什么是知识。 那什么是信息呢? 你一切听到的、看到的,都是信息,比如微博上的明星出轨、微信中的表情大战、抖音上的...
相关热词 c# plc s1200 c#里氏转换原则 c# 主界面 c# do loop c#存为组套 模板 c# 停掉协程 c# rgb 读取图片 c# 图片颜色调整 最快 c#多张图片上传 c#密封类与密封方法
立即提问