怎样用spring aop 拦截servlet

附件中的小例子可以用spring aop拦截普通类的方法,但是不能拦截servlet,可能是因为servlet是由web容器实例化而不是有spring容器实例化。请问怎样可以实现spring aop拦截servlet?或者怎样用spring实例化servlet?谢谢!

8个回答

这里的理解显然是没有弄清servlet开发中的一些理解
[quote]
这样确实可以解决,应该还要更好的方案吧,spring可以实例化struts2的antion,肯定是可以实例化servlet的

还是感谢mginobili[/quote]

struct的action、spring mvc等是通过自定义Servlet实现的,如struct的ActionServlet,spring mvc的DispatcherServlet。
他们都是在servlet规范之上构建的。

spring如何在servlet中启动,是通过配置listener启动spring容器。spring容器再去管理spring的bean.

spring为何能管理action,因为action是简历在spring容器之中。

以上三点可以看到。无论是action,还是spring bean,都是在servlet规范之上整合的。

servlet的由servlet容器管理,tomcat,jetty等,如果你想通过spring实例化servlet,那么就需要在spring中操作tomcat,jetty实例化servlet的代码。

是否可行没有操作过。

不过我们可以看到,spring自己的启动(listener启动)、spring mvc都是通过servlet转到spring之上的bean处理。

不过你的想法可以换一下,servlet转发到spring bean,通过aop处理。网络上很多spring gwt整合的例子。见:
http://jiangyongyuan.iteye.com/blog/143455

可以使用适配器模式

在servlet中定义一个对象obj(对象的类中有servlet同名的所有方法)

servlet的所有后台操作 改为调用这个对象 进行
比如servlet.doPost()方法
中就调用obj.doPost()

然后就可以再spring的配置中 对这个obj进行AOP拦截了

很不明白你为什么要为servlet做AOP,如果是需要对所有web请求进行拦截直接写个Filter配置到web.xml里面不就行了?还有一个问题,spring是不能实例化action的,action对象是struts生成的,你需要对struts.xml进行配置来让spring进行托管

呵呵,可以看看Spring提供的httpinvoker,这里就是用到的Servlet

可以考虑在 你的servlet中调用一个ActionBean,而该Bean是对Spring容器管理的,那么就很容易使用Spring的AOP特性完成你的要求了。

其实,如果你使用springMVC 作为你的Web框架,那么最终的servlet就是一个ActionBean。

如你所提到的 Spring可以实例化struts2的antion 那是因为struts2为集成spring做了相应的接口(因为Spring实在是太流行了),很多Web框架其实都有提供与Spring的集成接口。

你是用的是GWT吗?,我不知道GWT是否有提供针对Spring的集成接口,我想官方可能不会提供吧,因为google有自己的guice,但我想在民间,一定有人为GWT集成Spring做过努力了,你尝试搜索 Spring + GWT 试试看,....

如果真的还没有成熟的扩展用于 GWT集成Spring,那就自己写一个吧,其实并不难,就是在你的servlet中 用某中策略 去选择 Spring容易总的一个Bean,再将客户请求委托给Bean处理即可.

我觉得你的要求是不可实现的。
spring的aop是如何实现的?是因为你将对象交给它托管了,它才能对它托管的对象实例化和方法调用的时候进行拦截。如果一个对象的实例化和方法调用不是通过它,它怎么能控制住呢?

servlet是由web容器实例化和调用的,spring控制不了他们。最多只是用过滤器做一些处理

servlet 和 aop直接 adapter

一:代码级
二:运行期--cglib之流

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
一个用spring aop拦截struts action的问题
最近我需要在不改变原有的代码的前提下,记录到达struts action的HttpServletRequest和HttpServletResponse,我的第一想法就是用spring aop来做拦截。但是,这样做使得原来struts action无法获得struts上下文的内容信息,为了说明问题,我写了一个小原型,代码如下: [color=red]类SimpleAction,这个类是用来封装获得HttpServletRequest和HttpServletResponse的方法的,跟本主题关系不大,可以跳过。[/color] package action; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.interceptor.ServletRequestAware; import org.apache.struts2.interceptor.ServletResponseAware; import org.apache.struts2.interceptor.SessionAware; import com.opensymphony.xwork2.ActionSupport; public class SimpleAction extends ActionSupport implements ServletRequestAware, ServletResponseAware ,SessionAware{ protected HttpServletRequest servletRequest; protected HttpServletResponse servletResponse; protected Map session; public Map getSession() { return session; } public void setSession(Map session) { this.session = session; } public void setServletRequest(HttpServletRequest request) { this.servletRequest = request; } public HttpServletRequest getServletRequest() { return this.servletRequest; } public void setServletResponse(HttpServletResponse response) { this.servletResponse = response; } public HttpServletResponse getServletResponse() { return this.servletResponse; } } 类LoginAction,这个类的execute就是struts处理action调用的方法,但是奇怪的是,在这个方法中,本应得到jsp传来的值得username和password为空(把spring aop相关配置注释掉之后,username和password能正常传值)。loginService.validate()用作判断username和password是否符合,不符合以抛出异常的方式来告知调用者。在加上spring aop后,由于[color=red]username和password为空[/color],所以就一直返回结果"usernameInvalid"。 package action; import org.apache.struts2.interceptor.ServletRequestAware; import org.apache.struts2.interceptor.ServletResponseAware; import org.apache.struts2.interceptor.SessionAware; import service.LoginService; import exception.*; public class LoginAction extends SimpleAction { private String username; private String password; private LoginService loginService; public LoginService getLoginService() { return loginService; } public void setLoginService(LoginService loginService) { this.loginService = loginService; } 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; } @Override public void validate() { } @Override public String execute() { try{ this.getServletRequest().setAttribute("username", username); this.getServletRequest().setAttribute("password", password); System.out.println("username"+username); System.out.println("username"+getUsername()); boolean result = loginService.validate(username, password); }catch(UsernameException ue) { return "usernameInvalid"; }catch(PasswordException pe) { return "passwordInvalid"; }catch(Exception e) { e.printStackTrace(); return INPUT; } return SUCCESS; } } 下面是advice类,用来处理调用方法后的日志记录工作 package advice; import java.io.*; import java.lang.reflect.Method; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.springframework.aop.AfterReturningAdvice; import org.springframework.aop.MethodBeforeAdvice; import org.springframework.aop.ThrowsAdvice; public class LogActionAdvice implements AfterReturningAdvice { public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object target) { // TODO Auto-generated method stub try { PropertyConfigurator.configure("after.properties"); Logger logger = Logger.getLogger(target.getClass()); logger.debug("..."); }catch(Exception e) { e.printStackTrace(); } } } 下面是login页面,这个页面的username空间对应action的username属性,所以应该不是struts没有配alias的问题,这里是login.jsp代码 <%@ page language="java" pageEncoding="GB2312"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//CN"> <html> <head> <title>login2</title> </head> <body> <s:form name="login" action="login" method="post" > <s:textfield name="username" label="帐号"></s:textfield> <s:password name="password" label="密码"></s:password> <s:submit></s:submit> </s:form> </body> </html> 下面是配置文件,首先是struts的配置文件struts.xml: <?xml version="1.0" encoding="GB2312" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="struts2" extends="struts-default"> <action name="login" class="LoginAction"> <result name="success">/index.jsp</result> <result name="input">/login.jsp</result> <result name="usernameInvalid">/usernameInvalid.jsp</result> <result name="passwordInvalid">/passwordInvalid.jsp</result> </action> </package> </struts> 再来是spring的配置文件applicationContext.xml,红色部分是advice的配置,具体是匹配所有*Action的execute方法。 <?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:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:ehcache="http://www.springmodules.org/schema/ehcache" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springmodules.org/schema/ehcache http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd" default-lazy-init="true" default-autowire="byName"> [color=red] <aop:config> <aop:advisor id="methodAroundAdviceAdvisor" advice-ref="logActionAdvice" pointcut="execution(* *..*Action.execute(..))" /> </aop:config> <bean id="logActionAdvice" class="advice.LogActionAdvice" />[/color] <bean name="loginService" class="service.LoginService" /> <bean name="LoginAction" class="action.LoginAction"> <property name="loginService"> <ref bean="loginService"/> </property> </bean> </beans> 最后是web.xml的源码: <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" 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"> <!-- 加载struts2核心 --> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 指明spring配置文件在何处 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 加载spring配置文件applicationContext.xml --> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> </web-app> 在这个原型中出现的问题是,在LoginAction中,username和password为空,但是,[color=red]如果把它们set到 HttpServletRequest中,在页面usernameInvalid.jsp中却能够得到username和password的值。[/color]事先我查过一些资料,说用spring aop自动生成的代理无法获得struts上下文传递的变量值,但是我想不通为何把它们set到HttpServletRequest后却能够在前端页面显示出正确的值。 谢谢您的阅读和帮助!
spring拦截器莫名其妙的拦截
使用Spring MVC 写了个拦截器用来拦截Controller中的方法: @Override public void before(Method method, Object[] args, Object target) throws Throwable { System.out.println("---------------"); System.out.println("method.getDeclaringClass().getName() = " + method.getDeclaringClass().getName()); System.out.println("method.getName()=" + method.getName()); System.out.println("----------------"); } 配置文件: <bean id="btnInterceptor" class="cn.edu.swu.oa.safe.aop.BtnInterceptor"></bean> <bean id="btnAutoProxy" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"> <property name="beanNames"> <value>*Controller</value> </property> <property name="interceptorNames"> <list> <value>btnInterceptor</value> </list> </property> </bean> 但是运行观察控制台发现输出结果为: [http-8080-1] DEBUG org.springframework.web.servlet.DispatcherServlet - DispatcherServlet with name 'app' processing request for [/weboa/safe/buildFuncTree.do] --------------- method.getDeclaringClass().getName() = java.lang.Object method.getName()=toString ---------------- [http-8080-1] DEBUG org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping - Mapping [/safe/buildFuncTree.do] to handler 'cn.edu.swu.oa.safe.controller.SafeController@571688' [http-8080-1] DEBUG org.springframework.web.bind.annotation.support.HandlerMethodInvoker - Invoking request handler method: public void cn.edu.swu.oa.safe.controller.SafeController.buildFuncTree (javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) --------------- method.getDeclaringClass().getName() = cn.edu.swu.oa.safe.controller.SafeController method.getName()=buildFuncTree ---------------- 我不清楚 --------------- method.getDeclaringClass().getName() = java.lang.Object method.getName()=toString ---------------- 这部分是从哪来的,而且tomcat启动时也打印很多次这部分信息
通过Spring 的AOP实现日志, 当通过反射获取方法对象时报错"NoSuchMethodFoundException"
![图片说明](https://img-ask.csdn.net/upload/201904/11/1554964364_603440.png) **下面的是controller中的方法** ``` @Controller @RequestMapping("/permission") public class PermissionController { @Autowired private PermissionService permissionService; @RequestMapping("/findAll.do") public String findAll(Model model){ List<Permission> permissionList = permissionService.findAll(); model.addAttribute("permissionList", permissionList); return "permission-list"; } } ``` ![图片说明](https://img-ask.csdn.net/upload/201904/11/1554964390_944812.png) **下面的是aop相关的代码,如果要获取的方法带有Molde 参数, 当执行到最后"method = clazz.getMethod(methodName,classArgs);"时报错. 我试过了, 如果没有参数则不会报错, 如果参数 是int基本数据类型也会报错, 换成Integer就不会报错** ``` @Autowired private SysLogService sysLogService; private Class clazz; //访问的类 private Method method; //访问的方法 @Autowired private HttpServletRequest request; //前置通知, 拦截所有controller下的方法 //用来获取 开始时间visitTime, 执行的哪一个类clazz, 执行的哪一个方法method @Before("execution(* com.sjune.ssm.controller.*Controller.*(..))") public void doBefore(JoinPoint joinPoint) throws NoSuchMethodException {//参数为切入点 clazz = joinPoint.getTarget().getClass(); //具体要访问的类 //具体访问的方法 String methodName = joinPoint.getSignature().getName();//获取访问的方法的名称 Object[] args = joinPoint.getArgs();//获取访问方法的参数 if (args == null || args.length == 0){ //如果访问的方法无参 method = clazz.getMethod(methodName); //根据方法名获取方法 } else { //有参数, 遍历参数, 获取参数的class, 把他们装入class[]中 //new 一个class[]数组, 数组长度为args的长度 Class[] classArgs = new Class[args.length]; //遍历args for (int i = 0; i < args.length; i++) { classArgs[i] = args[i].getClass(); } method = clazz.getMethod(methodName,classArgs);//根据方法名和参数获取方法 } } ``` ``` ``` 报错 ![图片说明](https://img-ask.csdn.net/upload/201904/11/1554964408_719148.png) ``` Exception org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.reflect.UndeclaredThrowableException org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:986) org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:870) javax.servlet.http.HttpServlet.service(HttpServlet.java:635) org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855) javax.servlet.http.HttpServlet.service(HttpServlet.java:742) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320) org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:158) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) Root Cause java.lang.reflect.UndeclaredThrowableException com.sjune.ssm.controller.PermissionController$$EnhancerBySpringCGLIB$$cb1ce0b3.findAll(<generated>) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:498) org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:871) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:777) org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978) org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:870) javax.servlet.http.HttpServlet.service(HttpServlet.java:635) org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855) javax.servlet.http.HttpServlet.service(HttpServlet.java:742) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320) org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:158) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) Root Cause java.lang.NoSuchMethodException: com.sjune.ssm.controller.PermissionController.findAll(org.springframework.validation.support.BindingAwareModelMap) java.lang.Class.getMethod(Class.java:1786) com.sjune.ssm.controller.SysLogAop.doBefore(SysLogAop.java:58) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:498) org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:643) org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:625) org.springframework.aop.aspectj.AspectJMethodBeforeAdvice.before(AspectJMethodBeforeAdvice.java:44) org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:51) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) org.springframework.aop.aspectj.AspectJAfterAdvice.invoke(AspectJAfterAdvice.java:47) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689) com.sjune.ssm.controller.PermissionController$$EnhancerBySpringCGLIB$$cb1ce0b3.findAll(<generated>) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:498) org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:871) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:777) org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978) org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:870) javax.servlet.http.HttpServlet.service(HttpServlet.java:635) org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855) javax.servlet.http.HttpServlet.service(HttpServlet.java:742) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320) org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:158) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ```
springmvc+spring访问不了后台@Controller
web.xml ------------------------------ <?xml version="1.0" encoding="UTF-8"?> <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"> <display-name>engfac</display-name> <!-- 字符编码配置 --> <filter> <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- spring mvc 拦截器配置 --> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 程序Session配置 <session-config> Session过期时间(单位:分) <session-timeout>30</session-timeout> </session-config> --><!-- 激活Tomcat的defaultServlet来处理静态文件 --> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.jpg</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.gif</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.png</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>jsp</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>jsp</servlet-name> <url-pattern>*.jsp</url-pattern> </servlet-mapping> <!-- 欢迎页 --> <welcome-file-list> <welcome-file>login.html</welcome-file> </welcome-file-list> </web-app> ====================== spring-servlet.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" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd 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"> <!-- 开启注解模式驱动 --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 启用spring mvc 注解 --> <context:annotation-config /> <!-- 对静态资源文件的访问,交给default servlet handler处理 --> <mvc:default-servlet-handler/> <!-- 设置使用注解的类所在的jar包 --> <context:component-scan base-package="it.com.action.*"> </context:component-scan> <!-- 完成请求和注解POJO的映射 --> <bean class= "org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/> <!-- JSP视图文件解析配置 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/"/> <property name="suffix" value=".jsp"/> </bean> <!-- 上传文件拦截,设置最大上传文件大小 10M=10*1024*1024(B)=10485760 bytes --> <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> </beans> ========================================= applicationContext.xml ---------------------------------------------- <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd "> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://115.29.52.245:3306/fen_mydb" /> <property name="username" value="root" /> <property name="password" value="exlive2.0root" /> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="configLocation" value="classpath:conf.xml" /> <property name="dataSource" ref="dataSource" /> </bean> </beans> 这个访问不到后台, ![图片说明](https://img-ask.csdn.net/upload/201611/25/1480069566_993678.png) ![图片说明](https://img-ask.csdn.net/upload/201611/25/1480069602_96207.jpg) ![图片说明](https://img-ask.csdn.net/upload/201611/25/1480069635_760875.jpg)
JAVAEE、SSM框架,报错:HTTP Status 500 求大神解决!
![这是页面报错信息](https://img-ask.csdn.net/upload/201707/31/1501509503_963548.png) ![这是所引用的jar包,并额外引入了tomcat的jar包](https://img-ask.csdn.net/upload/201707/31/1501509660_138809.png) <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <filter> <filter-name>encodingFilter</filter-name> <filter-class> org.springframework.web.filter.CharacterEncodingFilter </filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <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:NETCTOSS.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app> 这是 web.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:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd"> <!-- 配置组件扫描 --> <context:component-scan base-package="cn.tedu.netctoss"/> <!-- 配置MVC注解扫描 --> <mvc:annotation-driven /> <!-- 配置视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/"/> <property name="suffix" value=".jsp"/> </bean> <!-- 配置拦截器 --> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**"/> <mvc:exclude-mapping path="/toLogin.do"/> <bean class="cn.tedu.nectoss.interceptors.SessionInterceptor"/> </mvc:interceptor> </mvc:interceptors> <!-- 读取db.properties文件 --> <util:properties id="db" location="classpath:db.properties" /> <!-- 配置连接池 --> <bean id="ds" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="#{db.driver}"/> <property name="url" value="#{db.url}"/> <property name="username" value="#{db.user}"/> <property name="password" value="#{db.pwd}"/> </bean> <!-- 配置SqlSessionFactoryBean --> <bean id="ssfb" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 指定连接池 --> <property name="dataSource" ref="ds"/> <!-- 指定映射文件 --> <property name="mapperLocations" value="cn/tedu/netctoss/entity/mapper/*.xml"/> </bean> <!-- 配置MapperScannerConfigurer *--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 指定映射器所在的包名 --> <property name="basePackage" value="cn.tedu.netctoss.dao"/> <!-- 指定注解类 ****--> <!-- <property name="annotationClass" value=""/> --> </bean> </beans> 这是容器的设置 ![项目结构](https://img-ask.csdn.net/upload/201707/31/1501510038_931664.png) 另外:我用的是jdk1.6(系统有双jdk 1.6和1.8) 也试过高版本的spring-webmvc 还是报错 测试文件全部通过,包括dao层,Servlet层 但一在tomcat上跑就不行 ![Controller代码](https://img-ask.csdn.net/upload/201707/31/1501510216_810696.png) ![唯一的jsp文件](https://img-ask.csdn.net/upload/201707/31/1501510290_591488.png)
maven项目 update project 后,Spring的注解不能使用,
<?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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.infosec.controller"> </context:component-scan> <mvc:annotation-driven /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 资源映射 --> <mvc:resources location="/WEB-INF/css/" mapping="/css/**" /> <mvc:resources location="/WEB-INF/js/" mapping="/js/**" /> <mvc:resources location="/WEB-INF/image/" mapping="/image/**" /> <mvc:resources location="/WEB-INF/alert/" mapping="/alert/**" /> <!-- 定义文件上传解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 设定默认编码 --> <property name="defaultEncoding" value="UTF-8"></property> <!-- 设定文件上传的最大值5MB,5*1024*1024 --> <property name="maxUploadSize" value="5242880"></property> </bean> <!--配置拦截器, 多个拦截器,顺序执行 --> <mvc:interceptors> <mvc:interceptor> <!-- 匹配的是url路径, 如果不配置或/**,将拦截所有的Controller --> <mvc:mapping path="/**" /> <mvc:exclude-mapping path="/css/**"/> <mvc:exclude-mapping path="/js/**"/> <mvc:exclude-mapping path="/image/**"/> <mvc:exclude-mapping path="/alert/**"/> <bean class="com.infosec.interceptor.CommonInterceptor"></bean> </mvc:interceptor> <!-- 当设置多个拦截器时,先按顺序调用preHandle方法,然后逆序调用每个拦截器的postHandle和afterCompletion方法 --> </mvc:interceptors> </beans> <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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" 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-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 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> <!-- 事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 数据源 --> <property name="dataSource" ref="dataSource" /> </bean> <!-- 通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 传播行为 --> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="create*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="find*" propagation="SUPPORTS" read-only="true" /> <tx:method name="select*" propagation="SUPPORTS" read-only="true" /> <tx:method name="get*" propagation="SUPPORTS" read-only="true" /> </tx:attributes> </tx:advice> <!-- 切面 --> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.infosec.service.*.*(..))" /> </aop:config> </beans> <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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" 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-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 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> <!-- 扫描包加载Service实现类 --> <context:component-scan base-package="com.infosec.service" /> </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 mvc+hibernate4事务控制
``` 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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>spring-mvc</display-name> <!--配置欢迎界面 --> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <error-page> <error-code>404</error-code> <location>/error/404.jsp</location> </error-page> <error-page> <error-code>500</error-code> <location>/error/exception.jsp</location> </error-page> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- Log4j配置 --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>WEB-INF/log4j.properties</param-value> </context-param> <!-- 开一条watchdog线程每60秒扫描一下配置文件的变化 --> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>60000</param-value> </context-param> <!--配置log4j包 --> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <!--配置listener --> <!--在这里可以配置spring的监听器,启动的时候需要把spring中的bean都注册到spring容器中 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--配置filter对编码进行转换 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value><!-- 强制转码 --> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--配置servlet --> <!--我们希望spring的控制器比其他servlet优先启动,所以你需要设置load-on-startup 这个东西:值越小越先启动(0-5),没有或者为负数的时候,servlet被选用的时候才加载--> <servlet> <servlet-name>controller</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:controll-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>controller</servlet-name> <url-pattern>*.action</url-pattern> </servlet-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> <init-param> <param-name>sessionFactory</param-name> <param-value>sessionFactory</param-value> </init-param> </filter> <filter-mapping> <filter-name>openSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> applicationContext.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr" 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.directwebremoting.org/schema/spring-dwr http://www.directwebremoting.org/schema/spring-dwr-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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:hibernate.properties</value> </list> </property> </bean> <!-- DWR配置--> <dwr:annotation-config></dwr:annotation-config> <!-- 扫描需要转换的java对象 --> <dwr:annotation-scan scanRemoteProxy="true" base-package="com.tb.service" /> <!-- 部署项目时, 请把debug设为false <dwr:controller id="dwrController" debug="true" /> --> <!--DWR初始化配置 --> <dwr:configuration></dwr:configuration> <!-- 配置数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass"> <value>${db.driver}</value> </property> <property name="jdbcUrl"> <value>${db.url}</value> </property> <property name="user"> <value>${db.user}</value> </property> <property name="password"> <value>${db.password}</value> </property> <property name="maxPoolSize"> <value>300</value> </property> <property name="minPoolSize"> <value>1</value> </property> <property name="initialPoolSize"> <value>1</value> </property> <property name="maxIdleTime"> <value>60</value> </property> <property name="acquireIncrement"> <value>5</value> </property> <property name="acquireRetryAttempts"> <value>10</value> </property> <property name="acquireRetryDelay"> <value>1000</value> </property> <property name="autoCommitOnClose"> <value>true</value> </property> <property name="breakAfterAcquireFailure"> <value>false</value> </property> <property name="checkoutTimeout"> <value>100</value> </property> <property name="idleConnectionTestPeriod"> <value>60</value> </property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 让spring帮你扫描这个包底下的所有类,主要作用扫描跟数据库对应的实体类 --> <!-- 设置hibernate的属性 --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.OracleDialect </prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.use_outer_join">true </prop> <prop key="hibernate.cglib.use_reflection_optimizer">true </prop> <prop key="hibernate.connection.useUnicode">true</prop> <prop key="hibernate.cache.use_query_cache">false</prop> <prop key="hibernate.default_batch_fetch_size">16</prop> <prop key="hibernate.c3p0.max_size">300</prop> <prop key="hibernate.c3p0.min_size">1</prop> <prop key="hibernate.c3p0.timeout">60</prop> <prop key="hibernate.c3p0.max_statements">100</prop> <prop key="hibernate.c3p0.idle_test_period">60</prop> <prop key="hibernate.c3p0.acquire_increment">5</prop> <prop key="hibernate.c3p0.validate">true</prop> <prop key="hibernate.current_session_context_class">thread</prop> </props> </property> <property name="packagesToScan" value="com.tb.model"/> </bean> <!--事务配置 --> <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 开启AOP监听 只对当前配置文件有效 --> <aop:aspectj-autoproxy expose-proxy="true" /> <!-- 开启注解事务 只对当前配置文件有效 --> <tx:annotation-driven transaction-manager="txManager"/> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="create*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="merge*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="put*" propagation="REQUIRED" /> <tx:method name="execute*" propagation="REQUIRED" rollback-for ="Exception.class" /> <tx:method name="tes*" propagation="REQUIRED" /> <tx:method name="use*" propagation="REQUIRED" /> <!--hibernate4必须配置为开启事务 否则 getCurrentSession()获取不到 --> <tx:method name="get*" propagation="REQUIRED" read-only="true" /> <tx:method name="count*" propagation="REQUIRED" read-only="true" /> <tx:method name="find*" propagation="REQUIRED" read-only="true" /> <tx:method name="list*" propagation="REQUIRED" read-only="true" /> <tx:method name="*" propagation="REQUIRED" rollback-for ="Exception.class"/> </tx:attributes> </tx:advice> <bean id="transactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true" lazy-init="true"> <property name="transactionManager" ref="txManager"></property> <property name="transactionAttributes"> <props> <prop key="add*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="save*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="tes*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="execute*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="modify*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="update*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="delete*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="remove*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="query*">PROPAGATION_REQUIRED, readOnly,-Exception</prop> <prop key="load*">PROPAGATION_REQUIRED, -Exception</prop> </props> </property> </bean> <!-- 只对业务逻辑层实施事务 --> <aop:config expose-proxy="true"> <aop:pointcut id="txPointcut" expression="execution(* com.tb.*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" /> </aop:config> <!-- --> <!--配置拦截器 在springmvc的控制器配置文件中,你就可以这么配置拦截器,具体你在拦截器里面做什么,自己去做 <mvc:interceptors> 多个拦截器,顺序执行 <mvc:interceptor> 这里的path符号有/*, /**, *, ? 等,对于student.do?param=1从?开始不作为path 如果不配置或/*,将拦截所有的Controller <mvc:mapping path="/student/save*" /> <bean class="spring.common.interceptor.FromDupInterceptor"></bean> </mvc:interceptor> </mvc:interceptors> --> </beans> controll-servlet.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" 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"> <context:component-scan base-package="com.tb"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <context:component-scan base-package="com.tb"/> <!-- json --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="jsonHttpMessageConverter"/> </list> </property> </bean> <bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </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="/WEB-INF/jsp/"/> <property name="suffix" valu-e=".jsp"/> </bean> </beans> 以上为配置文件:包路径分别为com.tb.action;com.tb.service;com.tb.model;com.tb.dao; 其中com.tb.service下面又分com.tb.service.impl;com.tb.dao包下又分com.tb.dao.impl; 但是现在测试事物一直控制不了,请大神帮忙原因。测试方法: Controller.java @RequestMapping(params = "executeSearch") @Transactional public String executeSearch(HttpServletRequest request) { //测试事物控制。 infoService.test(); return "info/search"; } ServiceImpl.java public void test(){ try { infoDAO.test(); } catch (Exception e) { e.printStackTrace(); } } Service.java @Transactional public void test(); DaoImpl.java @Transactional public void test() { try { String sql = "update operation_log set username='1' where id='1'"; List<Object> condition = new ArrayList<Object>(); this.executeUpdateBySql(sql, condition); String sql1 = "update operation_log set username=33, where id='1'"; this.executeUpdateBySql(sql1, condition); } catch (RuntimeException e) { e.printStackTrace(); } } DaoImpl.java继承HibernateDao HibernateDao.java /***************注入***********/ @Resource private SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public Session getSession() { //事务配置后,可通过getCurrentSession方法获得session return sessionFactory.getCurrentSession(); } public int executeUpdateBySql(final String sql,final List<Object> conditions){ try { Query query = getSession().createSQLQuery(sql); if(conditions!=null && conditions.size()>0){ for(int i=0;i<conditions.size();i++){ if(conditions.get(i)!=null && !conditions.get(i).equals("")){ query.setParameter(i, conditions.get(i)); } } } return query.executeUpdate(); } catch (RuntimeException e) { throw e; }finally{ System.out.println(getSessionFactory().getCurrentSession().beginTransaction().isActive()); } } 整体代码是这样的,在运行daoImpl.java中test()方法的时候执行第一条SQL时会提交事物,直接修改数据库中的值,执行第二条SQL时会报错,理论上应该都不提交事物。但实际上第一条执行了之后就提交事物了,不知道是我框架问题还是我写的问题,求大神帮忙指出问题所在。万分感谢! ```
Spring注入失败,但是getBean();却可以使用
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/context http://www.springframework.org/schema/context/spring-context-4.0.xsd "> <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="java:jboss/PostgresDS"/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="packagesToScan" value="com.cn.Jpa"> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <!-- 依赖注入上面定义的sessionFactory --> <property name="sessionFactory" ref="sessionFactory" /> </bean> <bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor"> <!-- 依赖注入上面定义的事务管理器transactionManager --> <property name="transactionManager" ref="transactionManager" /> <!-- 定义需要进行事务拦截的方法及所采用的事务控制类型 --> <property name="transactionAttributes"> <props> <!-- 以browse、list、load、get及is开头的所有方法采用只读型事务控制类型 --> <prop key="browse*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="list*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="load*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="is*">PROPAGATION_REQUIRED,readOnly</prop> <!-- 所有方法均进行事务控制,如果当前没有事务,则新建一个事务 --> <prop key="*">PROPAGATION_REQUIRED</prop> </props> </property> </bean> <!-- 定义BeanNameAutoProxyCreatorf进行Spring的事务处理 --> <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"> <!-- 针对指定的bean自动生成业务代理 --> <property name="beanNames"> <list> <value>HibernateManDao</value> <value>LoginResource</value> </list> </property> <!-- 这个属性为true时,表示被代理的是目标类本身而不是目标类的接口 --> <property name="proxyTargetClass"> <value>true</value> </property> <!-- 依赖注入上面定义的事务拦截器transactionInterceptor --> <property name="interceptorNames"> <list> <value>transactionInterceptor</value> </list> </property> </bean> <bean id="dao" class="com.cn.persistent.HibernateManDao"> <!-- <constructor-arg index="0" ref="sessionFactory" /> --> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property> <property name="session"><null/></property> </bean> <bean id="servlet" class="com.cn.servlet.LoginResource" scope="prototype"> <property name="md"> <ref bean="dao"/> </property> <!-- <constructor-arg index="0" ref= "dao"/> --> </bean> </beans>
Hibernate+SpringMvc+spring 事务不起效果(求大神帮忙看下)
appliactionContent.xml ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- 默认扫描的包路径 --> <context:component-scan base-package="zjl.website.*" /> <!-- 开启注解 --> <mvc:annotation-driven/> <!-- 属性文件读入 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath*:*.properties</value> </list> </property> </bean> <!-- 数据源定义,使用dbcp数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${jdbc.driverClassName}"></property> <property name="jdbcUrl" value="${jdbc.url}"></property> <property name="user" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!-- 配置hibernate的SessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <!-- 注入数据源 --> <property name="dataSource" ref="dataSource" /> <!-- 扫描hibernate注解配置的entity --> <property name="packagesToScan" value="zjl.website.entity" /> <!-- hibernate配置信息 --> <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> </props> </property> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </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="update*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="find*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="interceptorPointCuts" expression="execution(* zjl.website.service..*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="interceptorPointCuts" /> </aop:config> </beans> hibernate.cxg.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <!-- 连接数据库的操作 --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/microblog?useUnicode=true</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <!-- SQL dialect --> <!-- 数据库方言hql是hibernate官方的语言 --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 控制台打印sql语句 --> <property name="show_sql">true</property> <mapping class="zjl.website.entity.User"></mapping> </session-factory> </hibernate-configuration> spring-servlet.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <import resource="classpath*:applicationContext.xml" /> <mvc:default-servlet-handler/> <!-- 默认扫描的包路径 --> <context:component-scan base-package="zjl.website.*" /> <!-- 定义跳转的文件的前后缀 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 添加注解驱动 --> <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <constructor-arg value="utf-8" /> </bean> <bean 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> </mvc:message-converters> </mvc:annotation-driven> <!-- 上传文件拦截,设置最大上传文件大小 10M=10*1024*1024(B)=10485760 bytes --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="10485760" /> </bean> </beans> web.xml <?xml version="1.0" encoding="UTF-8"?> <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"> <listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener> <filter> <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 默认跳转到根目录下的页面,在这里为index.jsp --> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> ``` ![junit测试插入成功,但是可能事务没有提交在数据库中美有插入数据](https://img-ask.csdn.net/upload/201612/08/1481177671_274141.png) 第一次接触这东西,求大神帮忙看下,在线等
spring mvc与struts 整合报错
报错如下 求帮忙,谢谢 严重: Exception starting filter struts2 Unable to load configuration. - action - file:/E:/java/eclipse/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/bishe/WEB-INF/classes/struts.xml:11:74 at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:450) at org.apache.struts2.dispatcher.ng.InitOperations.initDispatcher(InitOperations.java:74) at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.init(StrutsPrepareAndExecuteFilter.java:51) at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:295) at org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:422) at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:115) at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4001) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4651) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045) at org.apache.catalina.core.StandardHost.start(StandardHost.java:785) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:445) at org.apache.catalina.core.StandardService.start(StandardService.java:519) at org.apache.catalina.core.StandardServer.start(StandardServer.java:710) at org.apache.catalina.startup.Catalina.start(Catalina.java:581) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414) Caused by: Unable to load configuration. - action - file:/E:/java/eclipse/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/bishe/WEB-INF/classes/struts.xml:11:74 at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:69) at org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:390) at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:437) ... 20 more Caused by: Error building results for action addProduct in namespace / - action - file:/E:/java/eclipse/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/bishe/WEB-INF/classes/struts.xml:11:74 at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addAction(XmlConfigurationProvider.java:389) at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addPackage(XmlConfigurationProvider.java:495) at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.loadPackages(XmlConfigurationProvider.java:286) at org.apache.struts2.config.StrutsXmlConfigurationProvider.loadPackages(StrutsXmlConfigurationProvider.java:112) at com.opensymphony.xwork2.config.impl.DefaultConfiguration.reloadContainer(DefaultConfiguration.java:234) at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:66) ... 22 more Caused by: There is no result type defined for type 'erro' mapped with name 'success'. Did you mean 'erro'? - result - file:/E:/java/eclipse/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/bishe/WEB-INF/classes/struts.xml:13:23 at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.buildResults(XmlConfigurationProvider.java:653) at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addAction(XmlConfigurationProvider.java:387) ... 27 more 四月 22, 2015 9:53:12 下午 org.apache.catalina.core.StandardContext start 严重: Error filterStart web.xml配置 <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> <!-- springMVC配置 --> <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*:/springMVC-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> struts2.xml配置 <struts> <constant name="struts.enable.DynamicMethodInvocation" value="true" /> <constant name="struts.devMode" value="false" /> <!--前台 /actionName localhost:8888/struts_1809/basic1 --> <package name="basic" namespace="/" extends="struts-default"> <action name="addProduct" class="com.fcz.action.product.ProductAction" > <result name="success">/jsp/admin/adminIndex.jsp</result> <result type="erro">/jsp/404.jsp</result> </action> </package> </struts> applicationContext.xml配置 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"> <bean id="productDao" class="com.fcz.dao.product.ProductDaoImpl"></bean> <bean id="addProduct" class="com.fcz.action.product.ProductAction" scope="prototype"> <property name="productDao" ref="productDao"></property> </bean> </beans>
请教:Spring + Hibernate 无法将数据写入数据库?
Spring + Hibernate 无法将数据写入数据 **请教: 通过Junit单元测试Service可以将数据写入数据库;但部署访问却无法向数据库写入数据。** 1 环境: Spring 3.1.2 Hibernate 4.1.4 Jdk1.6 2 配置: 2.1 Web.xml <!-- Spring ApplicationContext配置文件的路径,可使用通配符,多个路径用,号分隔 此参数用于后面的Spring Context Loader --> <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> <!--Dispathcer Servlet --> <servlet> <servlet-name>spring-mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- Spring MVC Servlet 拦截.do结尾的请求--> <servlet-mapping> <servlet-name>spring-mvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- Filter 定义 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--openSessionInView--> <filter> <filter-name>openSessionInView</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>sessionFactoryBeanName</param-name> <param-value>sessionFactory</param-value> </init-param> </filter> <filter-mapping> <filter-name>openSessionInView</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> 2.2 applicationContext.xml <!--扫描并自动装配 --> <context:annotation-config /> <context:component-scan base-package="com.sp" /> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <value>classpath:application.properties</value> </property> </bean> <!-- 数据源配置 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 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="${dbcp.maxActive}" /> <property name="maxIdle" value="${dbcp.maxIdle}" /> <property name="defaultAutoCommit" value="false" /> <!-- 连接Idle一个小时后超时 --> <property name="timeBetweenEvictionRunsMillis" value="3600000" /> <property name="minEvictableIdleTimeMillis" value="3600000" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.connection.autocommit">true</prop> <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> </props> </property> <property name="packagesToScan"> <list> <value>com.sp.dao</value> <value>com.sp.entity.dict</value> </list> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" abstract="false" lazy-init="default" autowire="default"> <property name="sessionFactory"><ref bean="sessionFactory" /></property> </bean> <!-- 事务管理配置 --> <!--<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="insert*" read-only="false" propagation="REQUIRED" /> <tx:method name="get*" read-only="false" propagation="REQUIRED" /> <tx:method name="add*" read-only="false" propagation="REQUIRED" /> <tx:method name="update*" read-only="false" propagation="REQUIRED" /> <tx:method name="delete*" read-only="false" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <aop:config> <aop:advisor pointcut="execution(* com.sp.service.*.*(..))" advice-ref="txAdvice"/> </aop:config> </beans> 2.3 spring-mvc.xml <!-- 启动注解驱动的SpringMVC功能,注册请求URL和注解POJO类方法的映射 --> <mvc:annotation-driven /> <!-- 自动扫描且只扫描@Controller --> <context:component-scan base-package="com.sp.web" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <context:component-scan base-package="com.sp.dao.impl"></context:component-scan> <context:component-scan base-package="com.sp.service.impl"></context:component-scan> <mvc:default-servlet-handler /> <!-- 对模型视图名称的解析,在请求时模型视图名称添加后缀。定义JSP --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 支持上传文件 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" /> 2.4 hibernate.cfg.xml <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/test</property> <property name="connection.username">root</property> <property name="connection.password">password</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect <property name="dialect">org.hibernate.dialect.MySQLDialect</property> --> <!-- Enable Hibernate's automatic session context management --> <!-- <property name="current_session_context_class">thread</property> --> <!-- Disable the second-level cache --> <!-- <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>--> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <property name="format_sql">true</property> <!-- Drop and re-create the database schema on startup--> <property name="hbm2ddl.auto">update</property> <property name="javax.persistence.validation.mode">none</property> 3 代码: 3.1 Service层: @Component("userService") public class UserServiceImpl implements UserService{ @Autowired private UserDao userDao; @Autowired private FormValidator validator; @Override public String userLogin(UserModel user) { String password = userDao.userLogin(user); if(password.equals(user.getPassword())){ return "sucess"; }else{ return "false"; } } @Override public List<ProjectType> getAllProjectTypes(){ List<ProjectType> projectType = userDao.getAllProjectTypes(); return projectType; } @Override public String addProjectType(@ModelAttribute("newProjectType")ProjectType projectType,BindingResult result,SessionStatus status){ validator.validate(projectType, result); if(result.hasErrors()){ return "newProjectType"; } userDao.save(projectType); //status.setComplete(); return "redirect:showProjectTypes.do"; } //添加《项目类型》 @Override public String addProjectType(ProjectType projectType) { userDao.save(projectType); return "redirect:showProjectTypes.do"; } } 3.2 Control层 @Controller @RequestMapping(value = "/user") public class UserController { @Autowired private UserService userService; @Autowired private FormValidator validator; @RequestMapping(value = "/login",method=RequestMethod.POST) protected String handle(UserModel user,BindingResult result, Model model){ String flag = userService.userLogin(user); System.out.println("flag:" + flag); if ("sucess".equals(flag)){ return "sucess"; } return "test1"; } @RequestMapping(value = "/showProjectTypes") protected ModelAndView getAllProjectTypes(){ ModelAndView mav = new ModelAndView("showProjectTypes"); List<ProjectType> projectTypes = userService.getAllProjectTypes(); mav.addObject("SEARCH_PROJECTTYPE_RESULTS_KEY", projectTypes); return mav; } @RequestMapping(value = "/addProjectType",method=RequestMethod.GET) protected ModelAndView newProjectTypeForm(){ ModelAndView mav = new ModelAndView("newProjectType"); ProjectType projectType = new ProjectType(); mav.getModelMap().put("newProjectType", projectType); return mav; } @RequestMapping(value = "/saveProjectType",method=RequestMethod.POST) protected String addProjectType(@ModelAttribute("newProjectType")ProjectType projectType,BindingResult result,SessionStatus status){ //return userService.addProjectType(projectType, result, status); return userService.addProjectType(projectType); } } 3.3 DAO层 @Component("userDao") public class UserDaoImpl implements UserDao{ @Autowired private SessionFactory sessionFactory; public ProjectType getById(int id) { return (ProjectType) sessionFactory.getCurrentSession().get(ProjectType.class, id); } @Override public String userLogin(UserModel user) { return "123456"; } //获取数据 @Override @SuppressWarnings("unchecked") public List<ProjectType> getAllProjectTypes() { Criteria ceriteria = sessionFactory.getCurrentSession().createCriteria(ProjectType.class); return ceriteria.list(); } //新增数据; @Override // @Transactional(readOnly = true, propagation = Propagation.REQUIRED) public int save(ProjectType projectType) { System.out.println("save:---"); System.out.println(projectType.getIndex()); System.out.println(projectType.getProjectType()); System.out.println(projectType.getProjectTypeAbbr()); return (Integer) sessionFactory.getCurrentSession().save(projectType); } }
Spring集成Hibernate,使用JPA注解方式,新增数据无法提交
<div class="iteye-blog-content-contain" style="font-size: 14px;"> <p>环境:</p> <p style="padding-left: 60px;">spring 3.1</p> <p style="padding-left: 60px;">hibernate 4.2.8 final </p> <p style="padding-left: 60px;">mysql 5.6</p> <p>问题描述:</p> <p style="padding-left: 30px;">调用controller的查询方法,可以正常返回数据</p> <p style="padding-left: 30px;">调用controller的创建方法,即:新增数据,控制台打印出了读取和修改序号表的sql,但是没有打印插入数据的sql,数据库表中也没有新增数据。</p> <p style="padding-left: 30px;">怀疑是spring控制的事务没有提交,但是排查了两三天,从网上找了各种方法,都没有解决问题。</p> <p style="padding-left: 30px;">请各位大侠拉小弟一把,实在是找不到事务为什么没有提交。</p> <p> </p> <p style="padding-left: 30px;">web.xml</p> <p style="padding-left: 30px;"> </p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"&gt; &lt;!-- 欢迎界面 --&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;index.html&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;!-- spring框架 --&gt; &lt;listener&gt; &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;!-- 上下文配置 --&gt; &lt;context-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt; /WEB-INF/applicationContext.xml, /WEB-INF/config/**/*.xml &lt;/param-value&gt; &lt;/context-param&gt; &lt;!-- spring mvc --&gt; &lt;servlet&gt; &lt;servlet-name&gt;dispatcher&lt;/servlet-name&gt; &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;dispatcher&lt;/servlet-name&gt; &lt;!-- 拦截所有url --&gt; &lt;url-pattern&gt;/&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;!-- 回话有效期30分钟 --&gt; &lt;session-config&gt; &lt;session-timeout&gt;30&lt;/session-timeout&gt; &lt;/session-config&gt; &lt;!-- log4j日志 --&gt; &lt;listener&gt; &lt;listener-class&gt;org.springframework.web.util.Log4jConfigListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;!-- log4j日志配置 --&gt; &lt;context-param&gt; &lt;param-name&gt;log4jConfigLocation&lt;/param-name&gt; &lt;param-value&gt;/WEB-INF/properties/log4j.properties&lt;/param-value&gt; &lt;/context-param&gt; &lt;/web-app&gt;</pre> <p> applicationContext.xml</p> <p> </p> <p style="padding-left: 30px;"> </p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" 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" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"&gt; &lt;!-- 注解配置 --&gt; &lt;context:annotation-config /&gt; &lt;!--允许使用注解方式配置事务 --&gt; &lt;tx:annotation-driven transaction-manager="transactionManager" /&gt; &lt;!-- 自动扫描的包名 --&gt; &lt;context:component-scan base-package="com.lxl" /&gt; &lt;!-- 对标注@PersistenceContext的类经行增强,引入代理后的EntityManager实例 --&gt; &lt;bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" /&gt; &lt;!-- 对标注@Repository的类经行增强,将EntityManager异常转换为SpringDAO体系的异常 --&gt; &lt;bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" /&gt; &lt;!-- 属性文件 --&gt; &lt;context:property-placeholder location="/WEB-INF/properties/**/*.properties" /&gt; &lt;!-- 数据源 --&gt; &lt;bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt; &lt;property name="driverClassName" value="${jdbc.driverClassName}" /&gt; &lt;property name="url" value="${jdbc.url}" /&gt; &lt;property name="username" value="${jdbc.username}" /&gt; &lt;property name="password" value="${jdbc.password}" /&gt; &lt;/bean&gt; &lt;!-- JPA 实体管理工厂 --&gt; &lt;bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"&gt; &lt;property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" /&gt; &lt;property name="dataSource" ref="dataSource" /&gt; &lt;property name="persistenceUnitName" value="ServicePlatform" /&gt; &lt;property name="jpaVendorAdapter"&gt; &lt;bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"&gt; &lt;property name="showSql" value="true" /&gt; &lt;property name="generateDdl" value="true" /&gt; &lt;property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" /&gt; &lt;/bean&gt; &lt;/property&gt; &lt;/bean&gt; &lt;!-- JPA 事务管理 --&gt; &lt;bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"&gt; &lt;property name="dataSource" ref="dataSource" /&gt; &lt;property name="entityManagerFactory" ref="entityManagerFactory" /&gt; &lt;/bean&gt; &lt;/beans&gt;</pre> <p> dispatcher-servlet.xml</p> <p> </p> <p style="padding-left: 30px;"> </p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" 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" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"&gt; &lt;!-- 默认的注解映射的支持 --&gt; &lt;mvc:annotation-driven /&gt; &lt;!-- 自动扫描的包名 --&gt; &lt;context:component-scan base-package="com.lxl" /&gt; &lt;!-- 配置一下对json数据的转换 &lt;bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"&gt; &lt;property name="messageConverters"&gt; &lt;list&gt; &lt;bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"&gt;&lt;/bean&gt; &lt;/list&gt; &lt;/property&gt; &lt;/bean&gt; --&gt; &lt;!-- 视图解析器 --&gt; &lt;bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt; &lt;property name="prefix" value="/view" /&gt; &lt;property name="suffix" value=".jsp" /&gt; &lt;/bean&gt; &lt;!-- 对静态资源文件的访问 方案一 (二选一) --&gt; &lt;mvc:default-servlet-handler /&gt; &lt;!-- 对静态资源文件的访问 方案二 (二选一) &lt;mvc:resources mapping="/images/**" location="/images/" cache-period="31556926"/&gt; &lt;mvc:resources mapping="/js/**" location="/js/" cache-period="31556926"/&gt; &lt;mvc:resources mapping="/css/**" location="/css/" cache-period="31556926"/&gt; --&gt; &lt;/beans&gt;</pre> <p> </p> <p> </p> <p style="padding-left: 30px;">persistence.xml</p> <p style="padding-left: 30px;"> </p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"&gt; &lt;persistence-unit name="ServicePlatform" transaction-type="RESOURCE_LOCAL"&gt; &lt;/persistence-unit&gt; &lt;/persistence&gt; </pre> <p> </p> <p> </p> <p style="padding-left: 30px;">实体bean</p> <p style="padding-left: 30px;"> </p> <pre name="code" class="java">package com.lxl.bsp.identity.entity; import java.io.Serializable; import java.sql.Timestamp; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "bd_id") public class Identity implements Serializable { private static final long serialVersionUID = -8763611811485844772L; @Id @GeneratedValue(strategy = GenerationType.TABLE) private Long id; @Column(length = 100) private String code; private Long value; @Column(length = 10) private String prefix; @Column(length = 10) private String suffix; @Column(length = 255) private String description; private Integer length; @Column(length = 30) private String creator; @Column(name = "create_date") private Timestamp createDate; @Column(length = 30) private String modifier; @Column(name = "modify_Date") private Timestamp modifyDate; private Boolean dr; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public Long getValue() { return value; } public void setValue(Long value) { this.value = value; } public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Integer getLength() { return length; } public void setLength(Integer length) { this.length = length; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public Timestamp getCreateDate() { return createDate; } public void setCreateDate(Timestamp createDate) { this.createDate = createDate; } public String getModifier() { return modifier; } public void setModifier(String modifier) { this.modifier = modifier; } public Timestamp getModifyDate() { return modifyDate; } public void setModifyDate(Timestamp modifyDate) { this.modifyDate = modifyDate; } public Boolean getDr() { return dr; } public void setDr(Boolean dr) { this.dr = dr; } @Override public String toString() { return "Identity [id=" + id + ", code=" + code + ", value=" + value + ", prefix=" + prefix + ", suffix=" + suffix + ", description=" + description + ", length=" + length + ", creator=" + creator + ", createDate=" + createDate + ", modifier=" + modifier + ", modifyDate=" + modifyDate + ", dr=" + dr + "]"; } } </pre> <p> </p> <p> </p> <p style="padding-left: 30px;">IdentityDaoImpl.java</p> <p style="padding-left: 30px;"> </p> <pre name="code" class="java">package com.lxl.bsp.identity.dao; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.lxl.bsp.api.exception.ServicePlatformException; import com.lxl.bsp.identity.entity.Identity; @Repository public class IdentityDaoImpl implements IIdentityDao { @PersistenceContext private EntityManager em; @Transactional(propagation = Propagation.REQUIRED) public Identity create(Identity data) { em.persist(data); return data; } @Override public Identity retriver(String id) throws ServicePlatformException { Long pk = Long.valueOf(id); return em.find(Identity.class, pk); } @Override public Identity update(Identity data) throws ServicePlatformException { em.persist(data); return data; } @Override public void delete(String id) throws ServicePlatformException { em.remove(retriver(id)); } } </pre> <p> IdentityController.java</p> <p> </p> <p style="padding-left: 30px;"> </p> <pre name="code" class="java">package com.lxl.bsp.identity.controller; import java.sql.Timestamp; import java.util.Calendar; import javax.annotation.Resource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.lxl.bsp.api.exception.ServicePlatformException; import com.lxl.bsp.identity.dao.IIdentityDao; import com.lxl.bsp.identity.entity.Identity; @Controller @RequestMapping("identity") public class IdentityController { private static Log log = LogFactory.getLog(IdentityController.class); @Resource private IIdentityDao dao; @RequestMapping("retriver") @ResponseBody public Identity retriver(@RequestParam String id) throws ServicePlatformException { return dao.retriver(id); } @RequestMapping("create") @ResponseBody public Identity create() throws ServicePlatformException { int i = 1; Identity data = new Identity(); data.setCode("code" + i); Calendar c = Calendar.getInstance(); data.setCreateDate(new Timestamp(c.getTime().getTime())); data.setCreator("creator" + i); data.setDescription("description" + i); data.setDr(false); // data.setId("id" + Integer.toString(i)); data.setLength(30); data.setModifier("modifier" + i); data.setModifyDate(new Timestamp(c.getTime().getTime())); data.setPrefix("prefix"); data.setSuffix("suffix"); data.setValue(0L); Identity returnData = dao.create(data); log.debug(returnData); return returnData; } @RequestMapping("update") @ResponseBody public Identity update() throws ServicePlatformException { int i = 1; Identity data = new Identity(); data.setCode("1"); Calendar c = Calendar.getInstance(); data.setCreateDate(new Timestamp(c.getTime().getTime())); data.setCreator("creator" + i); data.setDescription("description" + i); data.setDr(false); // data.setId("id" + Integer.toString(i)); data.setLength(30); data.setModifier("modifier" + i); data.setModifyDate(new Timestamp(c.getTime().getTime())); data.setPrefix("prefix"); data.setSuffix("suffix"); data.setValue(0L); Identity returnData = dao.update(data); log.debug(returnData); return returnData; } @RequestMapping("delete") public void delete(@RequestParam String id) throws ServicePlatformException { dao.delete(id); } } </pre> <p> </p> <p> </p> <p style="padding-left: 30px;">数据表结构DDL</p> <p style="padding-left: 30px;"> </p> <pre name="code" class="sql">-- ---------------------------- -- Table structure for bd_id -- ---------------------------- DROP TABLE IF EXISTS `bd_id`; CREATE TABLE `bd_id` ( `id` bigint(30) NOT NULL, `code` varchar(100) DEFAULT NULL, `create_date` datetime DEFAULT NULL, `creator` varchar(30) DEFAULT NULL, `description` varchar(255) DEFAULT NULL, `dr` tinyint(1) DEFAULT NULL, `length` int(11) DEFAULT NULL, `modifier` varchar(30) DEFAULT NULL, `modify_Date` datetime DEFAULT NULL, `prefix` varchar(10) DEFAULT NULL, `suffix` varchar(10) DEFAULT NULL, `value` bigint(20) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;</pre> <p> </p> <p> </p> <p style="padding-left: 30px;">附件中是项目压缩包,只要电脑上安装了数据库,解压即可运行,数据库名称是osd</p> <p> </p> </div>
spring mvc 事务失效问题
<div class="iteye-blog-content-contain" style="font-size: 14px;"> <p><span style="color: #000000;"><strong>同时向两个表插入数据,第一条成功,第二条数据插入失败,第一条未回滚,具体配置如下</strong></span></p> <p> </p> <p><span style="color: #000000; font-size: 18px;"><strong>applicationContext.xml 代码</strong></span></p> <p><span style="color: #000000;">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span><br><span style="color: #000000;">&lt;beans xmlns="<a href="http://www.springframework.org/schema/beans"><span style="color: #000000;">http://www.springframework.org/schema/beans</span></a>"</span><br><span style="color: #000000;"> xmlns:xsi="<a href="http://www.w3.org/2001/XMLSchema-instance"><span style="color: #000000;">http://www.w3.org/2001/XMLSchema-instance</span></a>" xmlns:tx="<a href="http://www.springframework.org/schema/tx"><span style="color: #000000;">http://www.springframework.org/schema/tx</span></a>"</span><br><span style="color: #000000;"> xmlns:context="<a href="http://www.springframework.org/schema/context"><span style="color: #000000;">http://www.springframework.org/schema/context</span></a>"</span><br><span style="color: #000000;"> xmlns:mvc="<a href="http://www.springframework.org/schema/mvc"><span style="color: #000000;">http://www.springframework.org/schema/mvc</span></a>" xmlns:util="<a href="http://www.springframework.org/schema/util"><span style="color: #000000;">http://www.springframework.org/schema/util</span></a>"</span><br><span style="color: #000000;"> xmlns:aop="<a href="http://www.springframework.org/schema/aop"><span style="color: #000000;">http://www.springframework.org/schema/aop</span></a>"</span><br><span style="color: #000000;"> xsi:schemaLocation="<a href="http://www.springframework.org/schema/aop"><span style="color: #000000;">http://www.springframework.org/schema/aop</span></a> <a href="http://www.springframework.org/schema/aop/spring-aop-3.1.xsd"><span style="color: #000000;">http://www.springframework.org/schema/aop/spring-aop-3.1.xsd</span></a></span><br><span style="color: #000000;">  <a href="http://www.springframework.org/schema/mvc"><span style="color: #000000;">http://www.springframework.org/schema/mvc</span></a> <a href="http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd"><span style="color: #000000;">http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd</span></a></span><br><span style="color: #000000;">  <a href="http://www.springframework.org/schema/beans"><span style="color: #000000;">http://www.springframework.org/schema/beans</span></a> <a href="http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"><span style="color: #000000;">http://www.springframework.org/schema/beans/spring-beans-3.1.xsd</span></a></span><br><span style="color: #000000;">  <a href="http://www.springframework.org/schema/util"><span style="color: #000000;">http://www.springframework.org/schema/util</span></a> <a href="http://www.springframework.org/schema/util/spring-util-3.1.xsd"><span style="color: #000000;">http://www.springframework.org/schema/util/spring-util-3.1.xsd</span></a></span><br><span style="color: #000000;">  <a href="http://www.springframework.org/schema/tx"><span style="color: #000000;">http://www.springframework.org/schema/tx</span></a> <a href="http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"><span style="color: #000000;">http://www.springframework.org/schema/tx/spring-tx-3.1.xsd</span></a></span><br><span style="color: #000000;">  <a href="http://www.springframework.org/schema/context"><span style="color: #000000;">http://www.springframework.org/schema/context</span></a> <a href="http://www.springframework.org/schema/context/spring-context-3.1.xsd"><span style="color: #000000;">http://www.springframework.org/schema/context/spring-context-3.1.xsd</span></a>"&gt;</span></p> <p><span style="color: #000000;"> &lt;!--将@Controller的注解排除掉 --&gt;</span><br><span style="color: #000000;"> &lt;context:component-scan base-package="com"&gt;</span><br><span style="color: #000000;">  &lt;context:exclude-filter type="annotation"</span><br><span style="color: #000000;">   expression="org.springframework.stereotype.Controller" /&gt;</span><br><span style="color: #000000;"> &lt;/context:component-scan&gt;</span></p> <p><span style="color: #000000;"> &lt;!-- 读取配置文件 --&gt;</span><br><span style="color: #000000;"> &lt;util:properties id="settings"</span><br><span style="color: #000000;">  location="classpath:config/global.properties" /&gt;</span></p> <p><span style="color: #000000;"> &lt;!-- 读取数据库配置文件 --&gt;</span><br><span style="color: #000000;"> &lt;bean id="configProperties"</span><br><span style="color: #000000;">  class="org.springframework.beans.factory.config.PropertiesFactoryBean"&gt;</span><br><span style="color: #000000;">  &lt;property name="locations"&gt;</span><br><span style="color: #000000;">   &lt;list&gt;</span><br><span style="color: #000000;">    &lt;value&gt;classpath:config/jdbc.properties&lt;/value&gt;</span><br><span style="color: #000000;">   &lt;/list&gt;</span><br><span style="color: #000000;">  &lt;/property&gt;</span><br><span style="color: #000000;"> &lt;/bean&gt;</span><br><span style="color: #000000;"> &lt;bean id="propertyConfigurer"</span><br><span style="color: #000000;">  class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"&gt;</span><br><span style="color: #000000;">  &lt;property name="properties" ref="configProperties" /&gt;</span><br><span style="color: #000000;"> &lt;/bean&gt;</span><br><span style="color: #000000;"> &lt;mvc:annotation-driven /&gt;</span></p> <p><span style="color: #000000;"> &lt;!-- 数据源 --&gt;</span><br><span style="color: #000000;"> &lt;bean id="dataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource"&gt;</span><br><span style="color: #000000;">  &lt;property name="driver" value="${driver}" /&gt;</span><br><span style="color: #000000;">  &lt;property name="driverUrl" value="${driverUrl}" /&gt;</span><br><span style="color: #000000;">  &lt;property name="user" value="${user}" /&gt;</span><br><span style="color: #000000;">  &lt;property name="password" value="${password}" /&gt;</span><br><span style="color: #000000;">  &lt;property name="alias" value="proxool.aidecenter" /&gt;</span><br><span style="color: #000000;">  &lt;property name="maximumActiveTime" value="300000" /&gt;</span><br><span style="color: #000000;">  &lt;property name="prototypeCount" value="0" /&gt;</span><br><span style="color: #000000;">  &lt;property name="maximumConnectionCount" value="${maximumConnectionCount}" /&gt;</span><br><span style="color: #000000;">  &lt;property name="minimumConnectionCount" value="${minimumConnectionCount}" /&gt;</span><br><span style="color: #000000;">  &lt;property name="simultaneousBuildThrottle" value="50" /&gt;</span><br><span style="color: #000000;">  &lt;property name="houseKeepingTestSql" value="select form CURRENT_DATE" /&gt;</span><br><span style="color: #000000;"> &lt;/bean&gt;</span><br><span style="color: #000000;"> &lt;!-- JDBC模版 --&gt;</span><br><span style="color: #000000;"> &lt;bean id="jdbc" class="org.springframework.jdbc.core.JdbcTemplate"&gt;</span><br><span style="color: #000000;">  &lt;property name="dataSource" ref="dataSource" /&gt;</span><br><span style="color: #000000;"> &lt;/bean&gt;</span><br><span style="color: #000000;"> &lt;bean</span><br><span style="color: #000000;">  class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"&gt;</span><br><span style="color: #000000;">  &lt;property name="staticMethod" value="com.common.database.SpringDB.setJdbcTemplate" /&gt;</span><br><span style="color: #000000;">  &lt;property name="arguments" ref="jdbc" /&gt;</span><br><span style="color: #000000;"> &lt;/bean&gt;</span><br><span style="color: #000000;"> &lt;!-- 事务管理器 --&gt;</span><br><span style="color: #000000;"> &lt;bean id="transactionManager"</span><br><span style="color: #000000;">  class="org.springframework.jdbc.datasource.DataSourceTransactionManager"&gt;</span><br><span style="color: #000000;">  &lt;property name="dataSource"&gt;</span><br><span style="color: #000000;">   &lt;ref local="dataSource" /&gt;</span><br><span style="color: #000000;">  &lt;/property&gt;</span><br><span style="color: #000000;"> &lt;/bean&gt;</span><br><span style="color: #000000;"> &lt;!-- 事务模板 --&gt;</span><br><span style="color: #000000;"> &lt;bean id="transactionTemplate"</span><br><span style="color: #000000;">  class="org.springframework.transaction.support.TransactionTemplate"&gt;</span><br><span style="color: #000000;">  &lt;property name="transactionManager"&gt;</span><br><span style="color: #000000;">   &lt;ref local="transactionManager" /&gt;</span><br><span style="color: #000000;">  &lt;/property&gt;</span><br><span style="color: #000000;"> &lt;/bean&gt;</span><br><span style="color: #000000;"> &lt;aop:config&gt;</span><br><span style="color: #000000;">  &lt;aop:pointcut id="transactionPointcut"</span><br><span style="color: #000000;">   expression="execution(* com.service..*.*(..))" /&gt;</span><br><span style="color: #000000;">  &lt;aop:advisor pointcut-ref="transactionPointcut"</span><br><span style="color: #000000;">   advice-ref="advice" /&gt;</span><br><span style="color: #000000;"> &lt;/aop:config&gt;</span><br><span style="color: #000000;"> &lt;tx:advice id="advice" transaction-manager="transactionManager"&gt;</span><br><span style="color: #000000;">  &lt;tx:attributes&gt;</span><br><span style="color: #000000;">   &lt;!-- 读取数据方法,一般采用只读事务 --&gt;</span><br><span style="color: #000000;">   &lt;tx:method name="find*" read-only="true" /&gt;</span><br><span style="color: #000000;">   &lt;!--以下方法,如save,update,delete等对数据库进行写入操作的方法,当产生Exception时进行回滚 --&gt;</span><br><span style="color: #000000;">   &lt;tx:method name="save*" propagation="REQUIRED" /&gt;</span><br><span style="color: #000000;">   &lt;tx:method name="update*" /&gt;</span><br><span style="color: #000000;">   &lt;tx:method name="delete*" /&gt;</span><br><span style="color: #000000;">  &lt;/tx:attributes&gt;</span><br><span style="color: #000000;"> &lt;/tx:advice&gt;</span><br><span style="color: #000000;"> &lt;tx:annotation-driven transaction-manager="transactionManager"</span><br><span style="color: #000000;">  proxy-target-class="true" /&gt;</span><br><span style="color: #000000;">&lt;/beans&gt;</span></p> <p> </p> <p><span style="color: #000000; font-size: 18px;"><strong>dispatcher-servlet.xml</strong></span></p> <p><span style="color: #000000;">&lt;?xml version="1.0" encoding="UTF-8"?&gt;<br>&lt;beans xmlns="<a href="http://www.springframework.org/schema/beans"><span style="color: #000000;">http://www.springframework.org/schema/beans</span></a>"<br> xmlns:xsi="<a href="http://www.w3.org/2001/XMLSchema-instance"><span style="color: #000000;">http://www.w3.org/2001/XMLSchema-instance</span></a>" xmlns:context="<a href="http://www.springframework.org/schema/context"><span style="color: #000000;">http://www.springframework.org/schema/context</span></a>"<br> xmlns:cache="<a href="http://www.springframework.org/schema/cache"><span style="color: #000000;">http://www.springframework.org/schema/cache</span></a>" xmlns:aop="<a href="http://www.springframework.org/schema/aop"><span style="color: #000000;">http://www.springframework.org/schema/aop</span></a>"<br> xmlns:tx="<a href="http://www.springframework.org/schema/tx"><span style="color: #000000;">http://www.springframework.org/schema/tx</span></a>" xmlns:jdbc="<a href="http://www.springframework.org/schema/jdbc"><span style="color: #000000;">http://www.springframework.org/schema/jdbc</span></a>"<br> xmlns:mvc="<a href="http://www.springframework.org/schema/mvc"><span style="color: #000000;">http://www.springframework.org/schema/mvc</span></a>"<br> xsi:schemaLocation="<br>      <a href="http://www.springframework.org/schema/beans"><span style="color: #000000;">http://www.springframework.org/schema/beans</span></a>  <br>            <a href="http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"><span style="color: #000000;">http://www.springframework.org/schema/beans/spring-beans-3.1.xsd</span></a>  <br>            <a href="http://www.springframework.org/schema/context"><span style="color: #000000;">http://www.springframework.org/schema/context</span></a>  <br>            <a href="http://www.springframework.org/schema/context/spring-context-3.1.xsd"><span style="color: #000000;">http://www.springframework.org/schema/context/spring-context-3.1.xsd</span></a>  <br>            <a href="http://www.springframework.org/schema/tx"><span style="color: #000000;">http://www.springframework.org/schema/tx</span></a>  <br>            <a href="http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"><span style="color: #000000;">http://www.springframework.org/schema/tx/spring-tx-3.1.xsd</span></a>  <br>            <a href="http://www.springframework.org/schema/jdbc"><span style="color: #000000;">http://www.springframework.org/schema/jdbc</span></a>  <br>            <a href="http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd"><span style="color: #000000;">http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd</span></a><br>            <a href="http://www.springframework.org/schema/cache"><span style="color: #000000;">http://www.springframework.org/schema/cache</span></a> <br>            <a href="http://www.springframework.org/schema/cache/spring-cache-3.1.xsd"><span style="color: #000000;">http://www.springframework.org/schema/cache/spring-cache-3.1.xsd</span></a><br>            <a href="http://www.springframework.org/schema/mvc"><span style="color: #000000;">http://www.springframework.org/schema/mvc</span></a> <br>      <a href="http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd"><span style="color: #000000;">http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd</span></a>"<br> default-autowire="byName"&gt;</span></p> <p><span style="color: #000000;"> &lt;!-- 将@Service注解给去掉 --&gt;<br> &lt;context:component-scan base-package="com.controller"&gt;<br>  &lt;context:include-filter type="annotation"<br>   expression="org.springframework.stereotype.Controller" /&gt;<br>  &lt;context:exclude-filter type="annotation"<br>   expression="org.springframework.stereotype.Service" /&gt;<br> &lt;/context:component-scan&gt;</span></p> <p><span style="color: #000000;"> &lt;bean<br>  class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"&gt;<br>  &lt;property name="useSuffixPatternMatch" value="true" /&gt;<br>  &lt;property name="interceptors"&gt;<br>   &lt;list&gt;<br>    &lt;ref bean="sessionInterceptor"&gt;&lt;/ref&gt;<br>   &lt;/list&gt;<br>  &lt;/property&gt;<br> &lt;/bean&gt;</span></p> <p><span style="color: #000000;"> &lt;!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --&gt;<br> &lt;bean<br>  class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"&gt;<br>  &lt;property name="messageConverters"&gt;<br>   &lt;list&gt;<br>    &lt;ref bean="mappingJacksonHttpMessageConverter" /&gt;<br>    &lt;ref bean="stringHttpMessageConverter" /&gt;<br>   &lt;/list&gt;<br>  &lt;/property&gt;<br> &lt;/bean&gt;<br> &lt;!-- 负责读写字符串格式的数据 --&gt;<br> &lt;bean id="stringHttpMessageConverter"<br>  class="org.springframework.http.converter.StringHttpMessageConverter"&gt;<br>  &lt;property name="supportedMediaTypes"&gt;<br>   &lt;list&gt;<br>    &lt;value&gt;text/plain;charset=UTF-8&lt;/value&gt;<br>   &lt;/list&gt;<br>  &lt;/property&gt;<br> &lt;/bean&gt;<br> &lt;!-- 负责读写入json格式的数据 --&gt;<br> &lt;bean id="mappingJacksonHttpMessageConverter"<br>  class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"&gt;<br>  &lt;property name="supportedMediaTypes"&gt;<br>   &lt;list&gt;<br>    &lt;value&gt;application/json;charset=UTF-8&lt;/value&gt;<br>   &lt;/list&gt;<br>  &lt;/property&gt;<br> &lt;/bean&gt;</span></p> <p><span style="color: #000000;"> &lt;!-- 拦截器 --&gt;<br> &lt;bean id="sessionInterceptor" class="com.interceptor.SessionInterceptor"&gt;&lt;/bean&gt;</span></p> <p><span style="color: #000000;"> &lt;!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 --&gt;<br> &lt;bean id="viewResolver"<br>  class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt;<br>  &lt;property name="viewClass"<br>   value="org.springframework.web.servlet.view.JstlView" /&gt;<br>  &lt;property name="prefix" value="" /&gt;<br>  &lt;property name="suffix" value=".jsp" /&gt;<br> &lt;/bean&gt;</span></p> <p><span style="color: #000000;"> &lt;!-- 启用缓存注解功能,该注解一定要声明在Spring主配置文件中才会生效 --&gt;<br> &lt;cache:annotation-driven cache-manager="cacheManager" /&gt;<br> &lt;bean id="cacheManager"<br>  class="org.springframework.cache.concurrent.ConcurrentMapCacheManager" /&gt;</span></p> <p><span style="color: #000000;"> &lt;!-- 资源文件加载 --&gt;<br> &lt;mvc:resources mapping="/upload/**" location="/upload/"<br>  cache-period="31556926" /&gt;<br> &lt;mvc:resources mapping="/libs/**" location="/libs/"<br>  cache-period="31556926" /&gt;<br>&lt;/beans&gt;<strong><br>上传的图片为包结构</strong></span></p> <p> </p> <p><span style="color: #000000;"><strong>Service的注解在接口实现类中</strong></span></p> <p><span style="color: #000000;"><strong>@Service<br>@Transactional<br>public class SiteServiceImpl implements SiteService {</strong></span></p> <p><span style="color: #000000;"><strong>.......</strong></span></p> <p><span style="color: #000000;"><strong>}</strong></span></p> <p> </p> <p><span style="color: #000000;">请问是哪里配置错了么</span></p> </div>
IDEA做SSM框架整合时,出现无法加载mapper,导致无法注入。
今日学习SSM框架整合,整合以后,单独用测试类可以连接成功连接数据库,可是一加入MVC用TOMCAT启动,项目就会报错,错误内容为:Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 以下为项目各部分截图,有没有大佬帮我分析下,问题到底出在哪? ========================================================================================================================================== ![项目报错详细情况](https://img-ask.csdn.net/upload/201908/15/1565880941_652575.png) ## 项目报错详细情况 ![spring配置文件已经配置了mapper.xml路径和齐对应的接口扫描包](https://img-ask.csdn.net/upload/201908/15/1565880955_958792.png) ## spring配置文件已经配置了mapper.xml路径和齐对应的接口扫描包 ![编译文件夹target里已经编译出了mapper相关配置文件及接口类](https://img-ask.csdn.net/upload/201908/15/1565881099_526884.png) ## 编译文件夹target里已经编译出了mapper相关配置文件及接口类 ![mapper.xml里的namespace已经指明了接口路径](https://img-ask.csdn.net/upload/201908/15/1565881139_161198.png) ## mapper.xml里的namespace已经指明了接口路径 ![pom文件里也配置了resource源](https://img-ask.csdn.net/upload/201908/15/1565881159_416309.png) ## pom文件里也配置了resource源 ========================================================================================================================================== # 详细代码已经贴在下方,只选了几个配置文件及mapper接口类,service及controller应该没关系就没传! ============================================= # mybatis-config.xml ``` <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!--添加缓存 引入第三方二级缓存 --> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> <setting name="cacheEnabled" value="false"/> </settings> <!-- 配置数据源 default默认使用的数据源 --> <environments default="mysql"> <environment id="mysql"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql:///orderuser"/> <property name="username" value="zhijia3278"/> <property name="password" value="0528"/> </dataSource> </environment> </environments> <!-- 映射文件 --> <mappers> <mapper resource="OrderUserMapper.xml"/> </mappers> </configuration> ``` # OrderUserMapper.java ``` package cn.tedu.mapper; import cn.tedu.domain.Order; import cn.tedu.domain.User; public interface OrderUserMapper { public User queryUser(String userId); public Order queryOrder(String orderId); public void updateUserPoints(User user); } ``` # OrderUserMapper.xml ``` <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="cn.tedu.mapper.OrderUserMapper"> <select id="queryUser" parameterType="String" resultType="User"> select * from t_user where user_id=#{userId} </select> <select id="queryOrder" parameterType="String" resultType="Order"> select * from t_order where order_id=#{orderId} </select> <update id="updateUserPoints" parameterType="User"> update t_user set points=#{points} where user_id=#{userId} </update> </mapper> ``` # spring.xml ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 配置内容 --> <context:component-scan base-package="cn.tedu"> </context:component-scan> <context:annotation-config></context:annotation-config> <!-- 持久层数据源 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <!-- 4个属性 --> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql:///orderuser"/> <property name="username" value="zhijia3278"/> <property name="password" value="0528"/> </bean> <!-- sqlSession --> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 数据源注入 --> <property name="dataSource" ref="dataSource"/> <!-- 扫描mybatis的独立配置文件 关闭二级缓存,驼峰命名 --> <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/> <!-- 映射文件扫描 --> <property name="mapperLocations" value="classpath:mapper/OrderUserMapper.xml" /> <!-- 别名包 --> <property name="typeAliasesPackage" value="cn.tedu.domain"></property> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 扫描的接口包 cn.tedu.mapper --> <property name="basePackage" value="cn.tedu.mapper"/> </bean> <!-- 注解驱动开启,@RequestMapping @RequestParam等 --> <mvc:annotation-driven/> <!-- 防止静态文件js css html访问被dispacherServlet拦截 --> <!-- localhost静态文件根目录 /static /js /css --> <!-- mapping 满足什么样子的访问地址 http://localhost:8080/js//1.js --> <mvc:resources location="/" mapping="/**"></mvc:resources> </beans> ``` # springmvc-servlet ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 配置内容 --> <context:component-scan base-package="cn.tedu"/> <!-- 注解驱动开启,@RequestMapping @RequestParam等 --> <mvc:annotation-driven/> <!-- 防止静态文件js css html访问被dispacherServlet拦截 --> <!-- localhost静态文件根目录 /static /js /css --> <!-- mapping 满足什么样子的访问地址 http://localhost:8080/js//1.js --> <mvc:resources location="/" mapping="/**"></mvc:resources> </beans> ``` # web.xml ``` <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- tomcat启动加载spring.xml --> <!-- <init-param>--> <!-- <param-name>contextConfigLocation</param-name>--> <!-- <param-value>classpath:springmvc/springmvc-servlet.xml</param-value>--> <!-- </init-param>--> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> ``` # pom.xml ``` <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>cn.tedu</groupId> <artifactId>SSMDemo</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>SSM-DEMO01 Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <!-- <dependency>--> <!-- <groupId>junit</groupId>--> <!-- <artifactId>junit</artifactId>--> <!-- <version>4.12</version>--> <!-- <scope>compile</scope>--> <!-- </dependency>--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.13.RELEASE</version> </dependency> <!-- datasource --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.14</version> </dependency> <!-- spring mysql --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.13.RELEASE</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.0.8</version> </dependency> <!-- mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <!-- spring mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <!-- springmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.3.13.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.13.RELEASE</version> </dependency> <!-- jackson --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.8.8</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.8.8</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.8</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> </dependencies> <build> <finalName>SSM-DEMO01</finalName> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <!-- 插件属性配置 --> <configuration> <!-- 端口 --> <port>8080</port> <!-- 项目访问路径 --> <path>/</path> <!-- 编解码 --> <uriEncoding>utf-8</uriEncoding> <useBodyEncodingForURI>true</useBodyEncodingForURI> </configuration> </plugin> </plugins> <resources> <resource> <directory>resource</directory> <includes> <include>**/*.xml</include> <include>mapper/*.xml</include> <include>mybatis/*.xml</include> <include>spring/*.xml</include> </includes> <!-- <filtering>true</filtering>--> </resource> </resources> </build> </project> ```
ibatis+spring mvc事务不能回滚
<div class="iteye-blog-content-contain" style="font-size: 14px;"> <p>最近才接触spring MVC和ibates,现在我需要配置事务回滚,但是倒腾了一天还是不行,熟悉的朋友帮忙看看: applicationContext.xml文件配置:</p> <p> </p> <pre name="code" class="java">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;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: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 http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd" default-autowire="byName"&gt; &lt;context:component-scan base-package="com.suneee"&gt; &lt;context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/&gt; &lt;/context:component-scan&gt; &lt;bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&gt; &lt;property name="location"&gt; &lt;value&gt;classpath:com/suneee/config/mysql/jdbc.properties&lt;/value&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"&gt; &lt;property name="driverClassName" value="${db.driverClassName}"/&gt; &lt;property name="url" value="${db.url}"/&gt; &lt;property name="username" value="${db.username}"/&gt; &lt;property name="password" value="${db.password}"/&gt; &lt;/bean&gt; &lt;!-- 配置数据源 --&gt; &lt;bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"&gt; &lt;property name="dataSource" ref="dataSource"/&gt; &lt;property name="configLocation"&gt; &lt;value&gt;classpath:com/suneee/config/ibatis/SqlMapConfig.xml&lt;/value&gt; &lt;/property&gt; &lt;/bean&gt; &lt;!-- 配置事务管理器 --&gt; &lt;bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"&gt; &lt;property name="dataSource" ref="dataSource" /&gt; &lt;/bean&gt; &lt;!-- 配置哪些类的方法需要进行事务管理 proxy-target-class="true" --&gt; &lt;aop:config &gt; &lt;aop:pointcut id="crudMethos" expression="execution(* com.suneee.service.*.*(..))"/&gt; &lt;aop:advisor advice-ref="txAdvice" pointcut-ref="crudMethos" /&gt; &lt;/aop:config&gt; &lt;!--配置哪些方法,什么情况下需要回滚--&gt; &lt;tx:advice id="txAdvice" transaction-manager="transactionManager"&gt; &lt;tx:attributes&gt; &lt;tx:method name="insert*" propagation="REQUIRED" rollback-for="java.lang.Exception"/&gt; &lt;tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Exception"/&gt; &lt;tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Exception"/&gt; &lt;!-- &lt;tx:method name="*" propagation="REQUIRED" read-only="true"/&gt; --&gt; &lt;!-- 除了上面标识的方法,其他方法全是只读方法 --&gt; &lt;/tx:attributes&gt; &lt;/tx:advice&gt; &lt;/beans&gt;</pre> <p> </p> <p> </p> <p>springMVC.XML文件内容如下:</p> <p> </p> <pre name="code" class="java">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;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" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 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" default-autowire="byName"&gt; &lt;!-- 自动扫描的包名 --&gt; &lt;context:component-scan base-package="com.suneee"&gt; &lt;context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/&gt; &lt;/context:component-scan&gt; &lt;!-- 视图解释类 --&gt; &lt;bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt; &lt;property name="prefix" value="/WEB-INF/jsp/"&gt;&lt;/property&gt; &lt;property name="suffix" value=".jsp"&gt;&lt;/property&gt; &lt;/bean&gt; &lt;bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"&gt; &lt;/bean&gt; &lt;!-- 拦截器 &lt;mvc:interceptors&gt; &lt;mvc:interceptor&gt; &lt;mvc:mapping path="/*.do"/&gt; &lt;bean class="com.suneee.interceptor.MyInterceptor"&gt;&lt;/bean&gt; &lt;/mvc:interceptor&gt; &lt;/mvc:interceptors&gt; --&gt; &lt;/beans&gt;</pre> <p> </p> <p> </p> <p>UserService.java内容如下:</p> <p> </p> <pre name="code" class="java">package com.suneee.service.impl; import java.util.List; import org.springframework.stereotype.Service; import com.suneee.bean.User; import com.suneee.service.IUserService; import com.suneee.service.base.BaseService; @Service("userService") public class UserService extends BaseService&lt;User&gt; implements IUserService{ @Override public List&lt;User&gt; findUser(User user) { return queryForList("user_queryAll",user); } @Override public User insert(User user){ insert("user_insert",user); user = null;//故意设置为null,抛出异常 insert("user_inserts",user); return user; } } </pre> <p> </p> <p> </p> <p>BaseService.java文件如下:</p> <pre name="code" class="java">package com.suneee.service.base; import java.sql.SQLException; import java.util.List; import org.springframework.orm.ibatis.SqlMapClientTemplate; public class BaseService&lt;T&gt; extends SqlMapClientTemplate{ public static final int PAGE_SIZE = 15; public Object insert(String sqlId,Object baseClass){ Object baseClassResult = null; try { baseClassResult = (Object) super.getSqlMapClient().insert(sqlId,baseClass); } catch (SQLException e) { e.printStackTrace(); } return baseClassResult; } public Object queryForObject(String sqlId,Object baseClass){ Object baseClassResult = null; try { baseClassResult = (Object) super.getSqlMapClient().queryForObject(sqlId,baseClass); } catch (SQLException e) { e.printStackTrace(); } return baseClassResult; } public Integer delete(String sqlId,Integer id){ Integer number = null; try { number = super.getSqlMapClient().delete(sqlId, id); } catch (SQLException e) { e.printStackTrace(); } return number; } public Integer deleteByObject(String sqlId,Object obj){ Integer number = null; try { number = super.getSqlMapClient().delete(sqlId, obj); } catch (SQLException e) { e.printStackTrace(); } return number; } public Object queryById(String sqlId,Integer id){ Object baseClassResult = null; try { baseClassResult = (Object) super.getSqlMapClient().queryForObject(sqlId,id); } catch (SQLException e) { e.printStackTrace(); } return baseClassResult; } public List&lt;Object&gt; queryListByPage(String sqlId,Object obj){ List&lt;Object&gt; list = null; try { list = (List&lt;Object&gt;) super.getSqlMapClient().queryForList(sqlId, obj); } catch (SQLException e) { e.printStackTrace(); } return list; } public List&lt;Object&gt; queryListNoPage(String sqlId,Object obj){ List&lt;Object&gt; list = null; try { list = (List&lt;Object&gt;) super.getSqlMapClient().queryForList(sqlId, obj); } catch (SQLException e) { e.printStackTrace(); } return list; } public int update(String sqlId,Object obj){ Integer number = null; try { number = super.getSqlMapClient().update(sqlId, obj); } catch (SQLException e) { e.printStackTrace(); } return number; } //批量入库 public boolean insertBatch(String sqlId,List list){ Object obj = null; try { super.getSqlMapClient().startBatch(); for(int i=0; i&lt;list.size(); i++){ obj = list.get(i); super.getSqlMapClient().insert(sqlId,obj); } super.getSqlMapClient().executeBatch(); return true; } catch (SQLException e) { e.printStackTrace(); return false; } } public int getCount(String sqlId){ Integer i = null; try { i = (Integer) super.getSqlMapClient().queryForObject(sqlId); } catch (SQLException e) { e.printStackTrace(); } return i; } }</pre> <p> </p> <p> </p> <p>以上就是我项目各个地方的代码,第二个插入数据方法我故意设置为null,执行报错,但是第一个插入数据方法执行了数据插入,没有回滚,怎样才能回滚啊,声明式的事务配置有错还是什么原因,熟悉的兄弟看看,困扰了我一天多了</p> </div>
spring mybatis集成,出错不回滚
配置文件,spring-servelt.xml <!-- 加载Controller --> <context:component-scan base-package="com"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/> </context:component-scan> <!-- 启动对@AspectJ注解的支持 --> <aop:aspectj-autoproxy /> <!-- 手动注册AnnotationMethodHandlerAdapter,可以手动设置编码,解决使用ResponseBody返回数据时的中文乱码问题 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value> </list> </property> </bean> <!-- 这个配置需要spring 3.1支持,并增加 jackson-all-1.9.11.jar 解决springmvc返回json问题 --> <!-- jackson2 如果升级jackson为2.x版本,哪么需要更改下面的配置。MappingJackson2HttpMessageConverter --> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value> </list> </property> </bean> </list> </property> </bean> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/page/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 下面这一行必须加,如果不加静态资源访问是正确,动态的访问就出错了 --> <mvc:annotation-driven /> <!-- 静态资源访问控制 --> <!-- <mvc:resources mapping="/WEB-INF/**" location="/WEB-INF/" /> --> <mvc:resources mapping="/images/**" location="/images/" /> <mvc:resources mapping="/control/**" location="/control/" /> 配置文件spring-config.xml <!-- 加载service --> <context:component-scan base-package="com"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Service" /> </context:component-scan> <!-- 数据源 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- 基本属性 url、user、password --> <property name="connectionProperties" value="oracle.jdbc.driver.OracleDriver" /> <property name="url" value="jdbc:oracle:thin:@192.168.0.222:1521:orcl" /> <property name="username" value="framedb" /> <property name="password" value="qaz123" /> <!-- 配置初始化大小、最小、最大 --> <property name="initialSize" value="1" /> <property name="minIdle" value="1" /> <property name="maxActive" value="20" /> <!-- 配置获取连接等待超时的时间 --> <property name="maxWait" value="60000" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="300000" /> <property name="validationQuery" value=" SELECT 1 FROM DUAL" /> <property name="testWhileIdle" value="true" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <!-- 打开PSCache,并且指定每个连接上PSCache的大小 --> <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> <!-- 配置监控统计拦截的filters --> <property name="filters" value="stat" /> </bean> <!-- define the SqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="typeAliasesPackage" value="com.common.frame.login.model, com.common.frame.authorize.model, com.common.frame.organization.model, com.common.frame.security.model, com.common.frame.resourec.model" /> <!-- 此处不可以使用*号做通配符,如果想引入多个包,必须多次引入,使用“,”号分割 --> <!-- Pagehelper分页插件 开始 2015-3-31 ssx--> <property name="plugins"> <array> <bean class="com.github.pagehelper.PageHelper"> <property name="properties"> <value> dialect=oracle reasonable=true params=count=countSql;pageSizeZero=zero </value> </property> </bean> </array> </property> <!-- Pagehelper分页插件 结束 --> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> <property name="basePackage" value="com.common.frame.*.mapper" /> <!-- 此处可以使用*号做通配符 --> </bean> <!-- transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> <qualifier value="user" /> </bean> service方法 @Transactional(rollbackFor=Exception.class) public void getTest() { try { OrganModel organ = new OrganModel(); organ.setOrganId("11hh"); organ.setOrganCode("11hh"); organ.setOrganName("11hh"); organ.setOrganAbb("11hh"); organ.setIsUse("1"); organ.setCreateBy("111"); organ.setCreateTime("bbbb"); organMapper.insert(organ); OrganTypeModel organType = new OrganTypeModel(); organTypeMapper.insert(organType); } catch (RuntimeException e) { e.printStackTrace(); } } 执行到这个方法,本方法实现了两个插入,第一个插入没有问题通过,第二个插入报错,但第一个插入在报错之后未回滚。不知道为什么,请告知。谢谢
求帮忙看下springmvc框架中注解事务失效问题
# web.xml配置文件 ``` <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" 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"> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/applicationContext*.xml</param-value> </context-param> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>zhihuiyi</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:config/drf-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet> <servlet-name>InitServlet</servlet-name> <servlet-class>com.developerForDrf.frame.init.InitServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet> <servlet-name>WeixinServlet</servlet-name> <servlet-class>com.developerForDrf.wechat.servlet.WeixinServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>zhihuiyi</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>InitServlet</servlet-name> <url-pattern>/servlet/InitServlet.do</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>WeixinServlet</servlet-name> <url-pattern>/WeixinServlet.do</url-pattern> </servlet-mapping> </web-app> ``` # applicationContext.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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" 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/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 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 "> <context:component-scan base-package="com.developerForDrf,com.developerForDrf.frame,com.developerForDrf.wechat,com.developerForDrf.business" > <!-- <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> --> </context:component-scan> <context:property-placeholder location="classpath:config/db.properties" /> <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName" value="${driverClassName}" /> <property name="url" value="${jdbc_url}" /> <property name="username" value="${jdbc_username}" /> <property name="password" value="${jdbc_password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="1" /> <!-- 连接池最大使用连接数量 --> <property name="maxActive" value="5" /> <!-- 连接池最大空闲 <property name="maxIdle" value="10" />--> <!-- 连接池最小空闲 --> <property name="minIdle" value="1" /> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="60000" /> <property name="validationQuery" value="SELECT 1 FROM DUAL" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <property name="testWhileIdle" value="true" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="25200000" /> <!-- 打开removeAbandoned功能 --> <property name="removeAbandoned" value="true" /> <!-- 1800秒,也就是30分钟 --> <property name="removeAbandonedTimeout" value="1800" /> <!-- 关闭abanded连接时输出错误日志 --> <property name="logAbandoned" value="true" /> <!-- 开启Druid的监控统计功能 <property name="filters" value="stat" />--> </bean> <!-- 国际化的消息资源文件 --> <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basenames"> <list> <value>classpath:config/validator</value> </list> </property> <property name="defaultEncoding" value="UTF-8"/> <property name="cacheSeconds" value="60"/> </bean> <!-- 处理事务 --> <!-- 生成一个事务管理对象 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 生成默认事务定义对象 --> <bean id="def" class="org.springframework.transaction.support.DefaultTransactionDefinition"></bean> <!-- 声明使用注解式事务 <tx:annotation-driven transaction-manager="transactionManager"/> --> <bean id= "namedParameterJdbcDaoSupport" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcDaoSupport"> <property name="dataSource" ref="dataSource"></property> </bean> </beans> ``` # 对应的servlet的配置文件 ``` <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" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.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-4.0.xsd"> <!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 ,多个可以用逗号隔开--> <context:component-scan base-package="com.developerForDrf,com.developerForDrf.frame,com.developerForDrf.wechat,com.developerForDrf.business" > <!--<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" /> --> </context:component-scan> <mvc:annotation-driven /> <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:order="100" p:viewClass="org.springframework.web.servlet.view.JstlView" p:prefix="/" p:suffix=".jsp" /> <!-- 处理Mutipart文件上传的bean --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding"> <value>UTF-8</value> </property> <property name="maxUploadSize"> <value>32505856</value><!-- 上传文件大小限制为31M,31*1024*1024 --> </property> <property name="maxInMemorySize"> <value>4096</value> </property> </bean> <!-- 基于注释的事务,当注释中发现@Transactional时,使用id为“transactionManager”的事务管理器 --> <!-- 如果没有设置transaction-manager的值,则spring以缺省默认的事务管理器来处理事务,默认事务管理器为第一个加载的事务管理器 --> <tx:annotation-driven transaction-manager="transactionManager" /> <!-- 拦截器 --> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**" /> <bean class="com.developerForDrf.frame.interceptors.AuthInterceptor" /> </mvc:interceptor> </mvc:interceptors> <mvc:resources location="/resources/" mapping="resources/**" /> </beans> ``` # 事务是在service层中做的,代码段: ``` @Transactional(readOnly=false,propagation=Propagation.REQUIRED,rollbackFor=Exception.class) public String test(String openid,int account)throws Exception{ String flag = "0"; int f = 0; f = memberDao.updateUserAccount(openid, account); memberDao.updateSubscribe(openid, 1); //抛异常 if(f==0){ throw new Exception("测试异常"); } return flag; } ``` ## test()方法中的两个调用dao层的动作,第一个是正常的,第二个是有意弄错的,但是执行的时候并没有回滚。 请各位路过的大神帮忙卡看!!!
No bean named 'shiroFilter' is defined
要把shiro整合进入spring,出现了这个错误,'shiroFilter' 这个bean已经定义过了的,着急在线等。。 严重: Exception starting filter shiroFilter org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'shiroFilter' is defined 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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <context-param> <param-name>contextClass</param-name> <param-value> org.springframework.web.context.support.AnnotationConfigWebApplicationContext </param-value> </context-param> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml,spring-shiro.xml</param-value> </context-param> <!-- apache shiro权限 --> <filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <init-param> <param-name>targetFilterLifecycle</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping> <filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class> cn.edu.bzu.group4.stockplus.common.base.controller.ApplicationConfigurationFilter </listener-class> </listener> <servlet> <servlet-name>springservlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext-servlet.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springservlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <error-page> <error-code>404</error-code> <location>/404</location> </error-page> </web-app> ``` spring-shiro.xml ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <description>Shiro</description> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager" /> <property name="loginUrl" value="/login" /> <property name="successUrl" value="/login" /> <property name="unauthorizedUrl" value="/404" /> <property name="filterChainDefinitions"> <value> /login.jsp* = anon /login.do* = anon /index.jsp*= anon /error/noperms.jsp*= anon /*.jsp* = authc /*.do* = authc </value> </property> </bean> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="SampleRealm" /> </bean> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" /> <bean id="SampleRealm" class="com.shiro.service.MonitorRealm"></bean> <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager" /> <property name="arguments" ref="securityManager" /> </bean> <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor" /> <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> <property name="securityManager" ref="securityManager" /> </bean> </beans> ``` applicationContext.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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 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 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd "> <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="root"/> <property name="password" value="root"/> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://10.2.7.121:3306/stockplus?characterEncoding=utf-8"/> <property name="maxPoolSize" value="30"/> <property name="minPoolSize" value="10"/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="packagesToScan"> <list> <value>cn.edu.bzu.group4.stockplus.*</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.show_sql">true</prop> </props> </property> <property name="eventListeners"> <map> <entry key="merge"> <bean class="org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener"/> </entry> </map> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" /> <!-- 拦截器方式配置事物 --> <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="edit*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="modify*" propagation="REQUIRED" /> <tx:method name="repair" propagation="REQUIRED" /> <tx:method name="append*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="get*" propagation="SUPPORTS" /> <tx:method name="load*" propagation="SUPPORTS" /> <tx:method name="datagrid*" propagation="SUPPORTS" /> <tx:method name="*" propagation="SUPPORTS" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="transactionPointcut" expression="execution(* cn.edu.bzu.group4stockplus.dao..*Dao.*(..))" /> <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" /> </aop:config> <context:annotation-config/> <context:component-scan base-package="cn.edu.bzu.group4.stockplus.*"/> </beans> ```
动态规划入门到熟悉,看不懂来打我啊
持续更新。。。。。。 2.1斐波那契系列问题 2.2矩阵系列问题 2.3跳跃系列问题 3.1 01背包 3.2 完全背包 3.3多重背包 3.4 一些变形选讲 2.1斐波那契系列问题 在数学上,斐波纳契数列以如下被以递归的方法定义:F(0)=0,F(1)=1, F(n)=F(n-1)+F(n-2)(n&gt;=2,n∈N*)根据定义,前十项为1, 1, 2, 3...
130 个相见恨晚的超实用网站,一次性分享出来
相见恨晚的超实用网站 持续更新中。。。
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它是一个过程,是一个不断累积、不断沉淀、不断总结、善于传达自己的个人见解以及乐于分享的过程。
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过...
Python——画一棵漂亮的樱花树(不同种樱花+玫瑰+圣诞树喔)
最近翻到一篇知乎,上面有不少用Python(大多是turtle库)绘制的树图,感觉很漂亮,我整理了一下,挑了一些我觉得不错的代码分享给大家(这些我都测试过,确实可以生成) one 樱花树 动态生成樱花 效果图(这个是动态的): 实现代码 import turtle as T import random import time # 画樱花的躯干(60,t) def Tree(branch, ...
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...
为啥国人偏爱Mybatis,而老外喜欢Hibernate/JPA呢?
关于SQL和ORM的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行了一番讨论,感触还是有一些,于是就有了今天这篇文。 声明:本文不会下关于Mybatis和JPA两个持久层框架哪个更好这样的结论。只是摆事实,讲道理,所以,请各位看官勿喷。 一、事件起因 关于Mybatis和JPA孰优孰劣的问题,争论已经很多年了。一直也没有结论,毕竟每个人的喜好和习惯是大不相同的。我也看...
我在支付宝花了1分钟,查到了女朋友的开房记录!
在大数据时代下,不管你做什么都会留下蛛丝马迹,只要学会把各种软件运用到极致,捉奸简直轻而易举。今天就来给大家分享一下,什么叫大数据抓出轨。据史料证明,马爸爸年轻时曾被...
shell脚本:备份数据库、代码上线
备份MySQL数据库 场景: 一台MySQL服务器,跑着5个数据库,在没有做主从的情况下,需要对这5个库进行备份 需求: 1)每天备份一次,需要备份所有的库 2)把备份数据存放到/data/backup/下 3)备份文件名称格式示例:dbname-2019-11-23.sql 4)需要对1天以前的所有sql文件压缩,格式为gzip 5)本地数据保留1周 6)需要把备份的数据同步到远程备份中心,假如...
聊聊C语言和指针的本质
坐着绿皮车上海到杭州,24块钱,很宽敞,在火车上非正式地聊几句。 很多编程语言都以 “没有指针” 作为自己的优势来宣传,然而,对于C语言,指针却是与生俱来的。 那么,什么是指针,为什么大家都想避开指针。 很简单, 指针就是地址,当一个地址作为一个变量存在时,它就被叫做指针,该变量的类型,自然就是指针类型。 指针的作用就是,给出一个指针,取出该指针指向地址处的值。为了理解本质,我们从计算机模型说起...
为什么你学不过动态规划?告别动态规划,谈谈我的经验
动态规划难吗?说实话,我觉得很难,特别是对于初学者来说,我当时入门动态规划的时候,是看 0-1 背包问题,当时真的是一脸懵逼。后来,我遇到动态规划的题,看的懂答案,但就是自己不会做,不知道怎么下手。就像做递归的题,看的懂答案,但下不了手,关于递归的,我之前也写过一篇套路的文章,如果对递归不大懂的,强烈建议看一看:为什么你学不会递归,告别递归,谈谈我的经验 对于动态规划,春招秋招时好多题都会用到动态...
程序员一般通过什么途径接私活?
二哥,你好,我想知道一般程序猿都如何接私活,我也想接,能告诉我一些方法吗? 上面是一个读者“烦不烦”问我的一个问题。其实不止是“烦不烦”,还有很多读者问过我类似这样的问题。 我接的私活不算多,挣到的钱也没有多少,加起来不到 20W。说实话,这个数目说出来我是有点心虚的,毕竟太少了,大家轻喷。但我想,恰好配得上“一般程序员”这个称号啊。毕竟苍蝇再小也是肉,我也算是有经验的人了。 唾弃接私活、做外...
字节跳动面试官这样问消息队列:分布式事务、重复消费、顺序消费,我整理了一下
你知道的越多,你不知道的越多 点赞再看,养成习惯 GitHub上已经开源 https://github.com/JavaFamily 有一线大厂面试点脑图、个人联系方式和人才交流群,欢迎Star和完善 前言 消息队列在互联网技术存储方面使用如此广泛,几乎所有的后端技术面试官都要在消息队列的使用和原理方面对小伙伴们进行360°的刁难。 作为一个在互联网公司面一次拿一次Offer的面霸...
2020年大前端发展趋势
迅速发展的前端开发,在每⼀年,都为开发者带来了新的关键词。2019 年已步⼊尾声,2020 年前端发展的关键词⼜将有哪些呢?发展的方向又会是什么呢?参考2019年大前端的发展,不出意外,前端依旧会围绕⼩程序、超级APP、跨端开发、前端⼯程化以及新技术运用等几个方面进行展开(可以参考2019年大前端技术趋势深度解读)。 小程序 在⼩程序⽅⾯,今年仍然是⼩程序突⻜猛进的⼀年,各⼤主流的 App 都上线...
如何安装 IntelliJ IDEA 最新版本——详细教程
IntelliJ IDEA 简称 IDEA,被业界公认为最好的 Java 集成开发工具,尤其在智能代码助手、代码自动提示、代码重构、代码版本管理(Git、SVN、Maven)、单元测试、代码分析等方面有着亮眼的发挥。IDEA 产于捷克,开发人员以严谨著称的东欧程序员为主。IDEA 分为社区版和付费版两个版本。 我呢,一直是 Eclipse 的忠实粉丝,差不多十年的老用户了。很早就接触到了 IDEA...
1个月时间整理了2019年上千道Java面试题,近500页文档!
Spring 面试题 1、一般问题 1.1、不同版本的 spring Framework 有哪些主要功能? 1.2、什么是 spring Framework? 1.3、列举 spring Framework 的优点。 1.4、spring Framework 有哪些不同的功能? 1.5、spring Framework 中有多少个模块,它们分别是什么? 1.6、什么是 spring ...
面试还搞不懂redis,快看看这40道面试题(含答案和思维导图)
Redis 面试题 1、什么是 Redis?. 2、Redis 的数据类型? 3、使用 Redis 有哪些好处? 4、Redis 相比 Memcached 有哪些优势? 5、Memcache 与 Redis 的区别都有哪些? 6、Redis 是单进程单线程的? 7、一个字符串类型的值能存储最大容量是多少? 8、Redis 的持久化机制是什么?各自的优缺点? 9、Redis 常见性...
为什么要推荐大家学习字节码?
配套视频: 为什么推荐大家学习Java字节码 https://www.bilibili.com/video/av77600176/ 一、背景 本文主要探讨:为什么要学习 JVM 字节码? 可能很多人会觉得没必要,因为平时开发用不到,而且不学这个也没耽误学习。 但是这里分享一点感悟,即人总是根据自己已经掌握的知识和技能来解决问题的。 这里有个悖论,有时候你觉得有些技术没用恰恰是...
在阿里,40岁的奋斗姿势
在阿里,40岁的奋斗姿势 在阿里,什么样的年纪可以称为老呢?35岁? 在云网络,有这样一群人,他们的平均年龄接近40,却刚刚开辟职业生涯的第二战场。 他们的奋斗姿势是什么样的呢? 洛神赋 “翩若惊鸿,婉若游龙。荣曜秋菊,华茂春松。髣髴兮若轻云之蔽月,飘飖兮若流风之回雪。远而望之,皎若太阳升朝霞;迫而察之,灼若芙蕖出渌波。” 爱洛神,爱阿里云 2018年,阿里云网络产品部门启动洛神2.0升...
【超详细分析】关于三次握手与四次挥手面试官想考我们什么?
在面试中,三次握手和四次挥手可以说是问的最频繁的一个知识点了,我相信大家也都看过很多关于三次握手与四次挥手的文章,今天的这篇文章,重点是围绕着面试,我们应该掌握哪些比较重要的点,哪些是比较被面试官给问到的,我觉得如果你能把我下面列举的一些点都记住、理解,我想就差不多了。 三次握手 当面试官问你为什么需要有三次握手、三次握手的作用、讲讲三次三次握手的时候,我想很多人会这样回答: 首先很多人会先讲下握...
压测学习总结(1)——高并发性能指标:QPS、TPS、RT、吞吐量详解
一、QPS,每秒查询 QPS:Queries Per Second意思是“每秒查询率”,是一台服务器每秒能够相应的查询次数,是对一个特定的查询服务器在规定时间内所处理流量多少的衡量标准。互联网中,作为域名系统服务器的机器的性能经常用每秒查询率来衡量。 二、TPS,每秒事务 TPS:是TransactionsPerSecond的缩写,也就是事务数/秒。它是软件测试结果的测量单位。一个事务是指一...
新程序员七宗罪
当我发表这篇文章《为什么每个工程师都应该开始考虑开发中的分析和编程技能呢?》时,我从未想到它会对读者产生如此积极的影响。那些想要开始探索编程和数据科学领域的人向我寻求建议;还有一些人问我下一篇文章的发布日期;还有许多人询问如何顺利过渡到这个职业。我非常鼓励大家继续分享我在这个旅程的经验,学习,成功和失败,以帮助尽可能多的人过渡到一个充满无数好处和机会的职业生涯。亲爱的读者,谢谢你。 -罗伯特。 ...
活到老,学到老,程序员也该如此
全文共2763字,预计学习时长8分钟 图片来源:Pixabay 此前,“网传阿里巴巴要求尽快实现P8全员35周岁以内”的消息闹得沸沸扬扬。虽然很快被阿里辟谣,但苍蝇不叮无缝的蛋,无蜜不招彩蝶蜂。消息从何而来?真相究竟怎样?我们无从而知。我们只知道一个事实:不知从何时开始,程序猿也被划在了“吃青春饭”行业之列。 饱受“996ICU”摧残后,好不容易“头秃了变强了”,即将步入为“高...
Vue快速实现通用表单验证
本文开篇第一句话,想引用鲁迅先生《祝福》里的一句话,那便是:“我真傻,真的,我单单知道后端整天都是CRUD,我没想到前端整天都是Form表单”。这句话要从哪里说起呢?大概要从最近半个月的“全栈工程师”说起。项目上需要做一个城市配载的功能,顾名思义,就是通过框选和拖拽的方式在地图上完成配载。博主选择了前后端分离的方式,在这个过程中发现:首先,只要有依赖jQuery的组件,譬如Kendoui,即使使用...
2019年Spring Boot面试都问了什么?快看看这22道面试题!
Spring Boot 面试题 1、什么是 Spring Boot? 2、Spring Boot 有哪些优点? 3、什么是 JavaConfig? 4、如何重新加载 Spring Boot 上的更改,而无需重新启动服务器? 5、Spring Boot 中的监视器是什么? 6、如何在 Spring Boot 中禁用 Actuator 端点安全性? 7、如何在自定义端口上运行 Sprin...
Unity项目在pc和ios设备上黑屏的原因探究
0x00 由于项目上线了windows平台的项目(别问我为什么,咱也不敢说,咱也不敢问),由Unity5.4.6升级到Unity2018的过程中,遇到了各种各样的坑,本文为避坑指南1。本项目没有使用HDR和抗锯齿,由于查这几个问题查到吐血,前后用了3天的时间,本文充满了怨气,行文非常啰嗦,需要快速解决问题的,可以直接拉到最后看结论。 0x01 法线贴图 项目在unity2018出了新的androi...
关于裁员几点看法及建议
最近网易裁员事件引起广泛关注,昨天网易针对此事,也发了声明,到底谁对谁错,孰是孰非?我们作为吃瓜观众实在是知之甚少,所以不敢妄下定论。身处软件开发这个行业,近一两年来,对...
面试官:关于Java性能优化,你有什么技巧
通过使用一些辅助性工具来找到程序中的瓶颈,然后就可以对瓶颈部分的代码进行优化。 一般有两种方案:即优化代码或更改设计方法。我们一般会选择后者,因为不去调用以下代码要比调用一些优化的代码更能提高程序的性能。而一个设计良好的程序能够精简代码,从而提高性能。 下面将提供一些在JAVA程序的设计和编码中,为了能够提高JAVA程序的性能,而经常采用的一些方法和技巧。 1.对象的生成和大小的调整。 J...
【图解算法面试】记一次面试:说说游戏中的敏感词过滤是如何实现的?
版权声明:本文为苦逼的码农原创。未经同意禁止任何形式转载,特别是那些复制粘贴到别的平台的,否则,必定追究。欢迎大家多多转发,谢谢。 小秋今天去面试了,面试官问了一个与敏感词过滤算法相关的问题,然而小秋对敏感词过滤算法一点也没听说过。于是,有了下下事情的发生… 面试官开怼 面试官:玩过王者荣耀吧?了解过敏感词过滤吗?,例如在游戏里,如果我们发送“你在干嘛?麻痹演员啊你?”,由于“麻痹”是一个敏感词,...
相关热词 c# 数组类型 泛型约束 c#的赛狗日程序 c# 传递数组 可变参数 c# 生成存储过程 c# list 补集 c#获得所有窗体 c# 当前秒数转成年月日 c#中的枚举 c# 计算校验和 连续随机数不重复c#
立即提问