对于想了解未配置CurrentSessionContext的读者,本文将提供新的信息,我们将详细介绍域名未配置,并且为您提供关于.NETCore中WebOperationContext.Current
对于想了解未配置CurrentSessionContext的读者,本文将提供新的信息,我们将详细介绍域名未配置,并且为您提供关于.NET Core 中 WebOperationContext.Current.OutgoingResponse.ContentType 的替代方法是什么、asp.net – “HttpContext.Current.Session”vs Global.asax“this.Session”、asp.net – 可以从Web API访问HttpContext.Current.Session、asp.net – 在什么情况下HttpContext.Current.Session可以为null?的有价值信息。
本文目录一览:- 未配置CurrentSessionContext(域名未配置)
- .NET Core 中 WebOperationContext.Current.OutgoingResponse.ContentType 的替代方法是什么
- asp.net – “HttpContext.Current.Session”vs Global.asax“this.Session”
- asp.net – 可以从Web API访问HttpContext.Current.Session
- asp.net – 在什么情况下HttpContext.Current.Session可以为null?
未配置CurrentSessionContext(域名未配置)
对不起,英语不好。我以spring-boot 1.1.8
Encountered Exception 开始我的项目NoCurrentSessionContext configured
,然后进行了一些搜索,添加属性<propertyname="hibernate.current_session_context_class">org.hibernate.context.ThreadLocalSessionContext</property>
可以解决此问题,但是
如何使用Java类配置此属性?
更新:我改为使用 Hibernate4.x 定义SessionFactory的 方式 ,但仍然遇到相同的错误,请帮忙!
使用java 1.8
和speing boot 1.1.8
这是我的pom.xml
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> <main.basedir>${basedir}/../..</main.basedir> <m2eclipse.wtp.contextRoot>../</m2eclipse.wtp.contextRoot> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>1.1.8.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency>
这是我的服务和控制器
@AutoWriedSessionFactory sessionFactory;@Service@Transactionalpublic class UserServiceImpl implements UserService { public boolean isEmailExist(String email) { Session session = sessionFactory.openSession(); // if I use getCurrentSession(), I will got the No Session found for current thread //Session session = sessionFactory.getCurrentSession(); Criteria c = UserCriteria.isEmailExisting(session, email); List<UserInfo> usrs = c.list(); session.close(); if (0 == usrs.size() || usrs.isEmpty()) return false; return true; }}@Controllerpublic class UserRegisterController { @Autowired UserService userService; @RequestMapping("/doRegist") public void doRegister(HttpServletRequest request, HttpServletResponse response) { String usrEmail = request.getParameter("email"); boolean exist = userService.isEmailExist(session, usrEmail); //todo }}
WebApplicatoinStarter.java
@Configuration@EnableAutoConfiguration@ComponentScan("com.mytest")public class WebApplicationStarter extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure( SpringApplicationBuilder application) { return application.sources(WebApplicationStarter.class); } public static void main(String[] args) throws Exception { ApplicationContext context = SpringApplication.run(WebApplicationStarter.class, args); } @Bean public SessionFactory sessionFactory(HibernateEntityManagerFactory hemf) { return hemf.getSessionFactory(); }}
更新:这是我的完整堆栈跟踪:
2014-11-01 08:41:11.736 INFO 3312 --- [ main] com.hotsoft.WebApplicationStarter : Starting WebApplicationStarter on zblqmc with PID 3312 (D:\x51\p2\target\classes started by lzzafll in D:\x51\p2)2014-11-01 08:41:11.814 INFO 3312 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@442675e1: startup date [Sat Nov 01 08:41:11 CST 2014]; root of context hierarchy2014-11-01 08:41:13.047 INFO 3312 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean ''beanNameViewResolver'': replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]2014-11-01 08:41:14.009 INFO 3312 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean ''org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration'' of type [class org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$dd4f2c7a] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)2014-11-01 08:41:14.041 INFO 3312 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean ''transactionAttributeSource'' of type [class org.springframework.transaction.annotation.AnnotationTransactionAttributeSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)2014-11-01 08:41:14.056 INFO 3312 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean ''transactionInterceptor'' of type [class org.springframework.transaction.interceptor.TransactionInterceptor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)2014-11-01 08:41:14.072 INFO 3312 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean ''org.springframework.transaction.config.internalTransactionAdvisor'' of type [class org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)2014-11-01 08:41:14.647 INFO 3312 --- [ main] .t.TomcatEmbeddedServletContainerFactory : Server initialized with port: 80802014-11-01 08:41:14.928 INFO 3312 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat2014-11-01 08:41:14.928 INFO 3312 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/7.0.552014-11-01 08:41:15.755 INFO 3312 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext2014-11-01 08:41:15.771 INFO 3312 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3957 ms2014-11-01 08:41:16.427 INFO 3312 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: ''dispatcherServlet'' to [/]2014-11-01 08:41:16.427 INFO 3312 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: ''hiddenHttpMethodFilter'' to: [/*]2014-11-01 08:41:17.534 INFO 3312 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit ''default''2014-11-01 08:41:17.550 INFO 3312 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default...]2014-11-01 08:41:17.660 INFO 3312 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {4.3.6.Final}2014-11-01 08:41:17.660 INFO 3312 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found2014-11-01 08:41:17.660 INFO 3312 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist2014-11-01 08:41:17.910 INFO 3312 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {4.0.5.Final}2014-11-01 08:41:18.050 INFO 3312 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect2014-11-01 08:41:18.206 INFO 3312 --- [ main] o.h.h.i.ast.ASTQueryTranslatorFactory : HHH000397: Using ASTQueryTranslatorFactory2014-11-01 08:41:18.861 INFO 3312 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2014-11-01 08:41:19.047 INFO 3312 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hello],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String com.hotsoft.web.UserRegisterController.hello(java.util.Map<java.lang.String, java.lang.Object>)2014-11-01 08:41:19.047 INFO 3312 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/doRegist],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public void com.hotsoft.web.UserRegisterController.doRegister(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)2014-11-01 08:41:19.063 INFO 3312 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)2014-11-01 08:41:19.063 INFO 3312 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],methods=[],params=[],headers=[],consumes=[],produces=[text/html],custom=[]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest)2014-11-01 08:41:19.078 INFO 3312 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2014-11-01 08:41:19.078 INFO 3312 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2014-11-01 08:41:19.413 INFO 3312 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup2014-11-01 08:41:19.554 INFO 3312 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080/http2014-11-01 08:41:19.569 INFO 3312 --- [ main] com.hotsoft.WebApplicationStarter : Started WebApplicationStarter in 8.551 seconds (JVM running for 9.276)2014-11-01 08:41:32.754 INFO 3312 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet ''dispatcherServlet''2014-11-01 08:41:32.754 INFO 3312 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet ''dispatcherServlet'': initialization started2014-11-01 08:41:32.786 INFO 3312 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet ''dispatcherServlet'': initialization completed in 32 ms2014-11-01 08:41:39.988 ERROR 3312 --- [nio-8080-exec-6] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.hibernate.HibernateException: No CurrentSessionContext configured!] with root causeorg.hibernate.HibernateException: No CurrentSessionContext configured! at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1012) at com.hotsoft.web.UserRegisterController.doRegister(UserRegisterController.java:41) 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.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852) at javax.servlet.http.HttpServlet.service(HttpServlet.java:620) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837) at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1736) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1695) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Unknown Source)
答案1
小编典典您的hibernate配置和使用是错误的。您正在使用Spring甚至更好的Spring
Boot,但是您发布的内容非常努力地不使用这些框架,并尝试解决这些框架。我强烈建议使用Spring Boot并让它为您配置。
首先删除您的文件HibernateUtils
,将其埋入深处,再也不要再看了。您还可以删除它,AppConfig
因为Spring
Boot可以并且将会处理DataSource
。
接下来application.properties
,在src/main/resources
目录中创建一个名为的文件,并将以下内容放入其中。
spring.datasource.url=jdbc:mysql://localhost/mysqlspring.datasource.username=rootspring.datasource.password=
这将自动DataSource
为您配置一个。您不需要驱动程序,因为该驱动程序是根据您提供的网址推导出来的。接下来,添加以下属性以配置JPA。
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialectspring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
有关更多设置和属性,我建议阅读《Spring Boot参考指南》以获取有关属性的信息,请检查此综合列表。
接下来,在中WebApplicationStarter
添加HibernateJpaSessionFactoryBean
将创建的JPA公开EntityManagerFactory
为SessionFactory
。
@Configuration@EnableAutoConfiguration@ComponentScan("com.mytest")public class WebApplicationStarter extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(WebApplicationStarter.class); } public static void main(String[] args) throws Exception { ApplicationContext context = SpringApplication.run(WebApplicationStarter.class, args); } @Bean public SessionFactory sessionFactory(HibernateEntityManagerFactory hemf) { return hemf.getSessionFactory(); }}
然后,只需@Autowire
将SessionFactory
到您UserServiceImpl
。
@Service@Transactionalpublic class UserServiceImpl implements UserService { @Autowired private SessionFactory sessionFactory;}
现在您可以使用了SessionFactory
。
.NET Core 中 WebOperationContext.Current.OutgoingResponse.ContentType 的替代方法是什么
如何解决.NET Core 中 WebOperationContext.Current.OutgoingResponse.ContentType 的替代方法是什么?
.NET Core 中以下代码片段的替代方法是什么?
WebOperationContext webContext = WebOperationContext.Current;
webContext.OutgoingResponse.ContentType = "text/html";
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)
asp.net – “HttpContext.Current.Session”vs Global.asax“this.Session”
Session
中跟踪它们,然后通过
Global.asax
的Session_End将数据保存到DB中.
我开始黑客走了,初始代码工作正常,更新每个页面上的DB加载.我想删除每个请求上的这个DB命中,只需依靠Session_End来存储所有的数据.
所有跟踪代码都封装在Tracker类中,包括基本上包装Session变量的属性.
问题是当我在Session_End方法中执行Tracker.Log()时,跟踪代码中的HttpContext.Current.Session
与NullReferenceException
失败.现在,这是有道理的,因为HttpContext
始终与当前请求相关,当然在Session_End中没有要求
我知道Global.asax有一个Session属性,返回一个HttpSessionState,实际上似乎工作正常(我最终将其注入到跟踪器中)..
但是我很好奇,可以从Global.asax外面获得与Global.asax使用的HttpSessionState对象相同的引用吗?
先谢谢你们,我很感激你的意见.
总结
以上是小编为你收集整理的asp.net – “HttpContext.Current.Session”vs Global.asax“this.Session”全部内容。
如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。
asp.net – 可以从Web API访问HttpContext.Current.Session
我有一个通用处理程序在我要删除的API调用之后执行会话集。
public void AccountController : ApiController,IRequiresSessionState { public void Login() { setsession(){} } }
解决方法
如果你绝对必须这样做,你可以像这样抓住HTTP上下文:
var context = Request.Properties["MS_HttpContext"] as HttpContext;
此时您只需使用其Session属性来获取会话。
请注意,这会破坏System.Net.Http承担的某些合同 – 具体来说,这意味着您的API控制器永远不能被自我托管,因为它们与ASP.NET相连。如果您确定这一点,并且事实上,您的API控制器可能无法从Web场正常工作,除非您重新构建所有要使用分布式会话的内容 – 那么请继续。
美国也可以使用IRequiresSessionState,但是您不能在控制器本身上使用它,您需要在HttpControllerHandler上使用它,并将其设置为RouteHandler。这个方法在07年1月被讨论。同样,我不能强烈地推荐这个想法,它违反了Web API的基本原理 – 但是,如果你有一个非常好的理由,那么这是另一种选择多一点可重用。
asp.net – 在什么情况下HttpContext.Current.Session可以为null?
我有一些asp.net页面.
我只是想知道为什么我应该一直检查对象的Session对象?
例如
public static object GetSession(string key) { if (HttpContext.Current.Session != null) { return HttpContext.Current.Session[key]; } return null; }
解决方法
编辑
如果Session对象可用并且您想要从中访问值,那么您很少会遇到这样的情况.在大多数情况下,包括其他答案提到的那些,HttpContext.Current.Session [key]将为null,但不是HttpContext.Current.Session本身.
在大多数日常编码场景中,Session对象不会为null,并且您的问题中的代码将是过度的.同样,如果您提前知道Session对象为null,则您甚至不应尝试访问它.
如果您的应用程序在异常情况下访问Session对象时可能会或可能不为null,那么您的代码将是处理它的好方法,例如上面引用的问题中描述的那些.
今天关于未配置CurrentSessionContext和域名未配置的分享就到这里,希望大家有所收获,若想了解更多关于.NET Core 中 WebOperationContext.Current.OutgoingResponse.ContentType 的替代方法是什么、asp.net – “HttpContext.Current.Session”vs Global.asax“this.Session”、asp.net – 可以从Web API访问HttpContext.Current.Session、asp.net – 在什么情况下HttpContext.Current.Session可以为null?等相关知识,可以在本站进行查询。
本文标签: