HVT*_*VT7 6 java spring jsp hibernate spring-mvc
我正在使用spring和hibernate构建一个Web应用程序.我想构建服务器端表,我需要一个用Service类编写的方法.但是为了成功执行它,我需要将它自动装入到受尊重的类中,因为现在它正在访问表中给出一个Null Pointer Exception.
Ami*_*rma 13
不,你不能@autowired
在JSP中使用.如果在JSP中需要bean,则可以使用以下命令:
ApplicationContext ac = RequestContextUtils.getWebApplicationContext(request);
ac.getBean("yourBeanName");
Run Code Online (Sandbox Code Playgroud)
编辑: -
示例Bean:
@Component("abcBean")
public Abc{
public void sysout(){
System.out.printn("Hello world");
}
}
Run Code Online (Sandbox Code Playgroud)
在JSP中:
您可以将此spring管理的单例bean用作:
ApplicationContext ac = RequestContextUtils.getWebApplicationContext(request);
Abc abc = (Abc) ac.getBean("abcBean");
abc.sysout();
Run Code Online (Sandbox Code Playgroud)
如果需要其他任何内容,请发布.
如果您使用的是Spring MVC,可以通过ModelAndView将您的服务传递给JSP.
假设你有:控制器
@Controller
public void MyController {
@Autowired
private MyServiceInterface myService;
@RequestMapping(value="myUrl")
public ModelAndView displayPage() {
//do some stuff
return new ModelAndView("myView").addObject("myService", myService);
}
}
Run Code Online (Sandbox Code Playgroud)
JSP:
<html>
.
${myService.myMethodIWantToUse}
.
</html>
Run Code Online (Sandbox Code Playgroud)
但就像Slava Semushin说的那样,这是一种不好的做法.如果除了方法的结果并在JSP中打印它们,请将它们放在模型中(ModelAndView)
归档时间: |
|
查看次数: |
7951 次 |
最近记录: |