伙计们我知道这是一个虚拟问题但它在编写myThreadLocal.set(str)时给了我null ointer异常..这是我的完整代码
threadLocalController.java
package threadLocalWeb;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class threadLocalController {
@RequestMapping(value = "/index")
public void doPost() {
threadLocal.setMyThreadLocal("name1");
threadLocal.getMyThreadLocal();
threadLocal.setMyThreadLocal("name2");
threadLocal.getMyThreadLocal();
}
}
threadLocal.java
package threadLocalWeb;
public class threadLocal {
private static ThreadLocal<String> myThreadLocal;
public threadLocal(){
myThreadLocal = new ThreadLocal<String>();
}
public static String getMyThreadLocal() {
return myThreadLocal.get();
}
public static void setMyThreadLocal(String str) {
myThreadLocal.set(str);
}
}
的web.xml
<web-app version="2.5" 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">
<servlet>
<servlet-name>sdnext</servlet-name>
<servlet-
class>org.springframework.web.servlet.DispatcherServlet</servlet-
class>
<init-param>
<param-name>contextConfigLocation</param-name><param-value>/WEB-
INF/config/sdnext-servlet.xml</param-value></init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>sdnext</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
sdnext-servlet.xml中
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/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/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">
<mvc:annotation-driven/>
<context:annotation-config />
<context:component-scan base-package="threadLocalWeb"/>
</beans>
任何帮助将不胜感激..谢谢
答案 0 :(得分:0)
你永远不会初始化你的对象......请改用它。
$_SERVER[REQUEST_URI]
答案 1 :(得分:0)
您需要调用threadLocal
构造函数来初始化myThreadLocal
,或者您必须直接在变量声明或静态初始化程序块中进行初始化。