java web开发学习手册_Java开发:ssm系列之Spring开发Web项目

Spring开发Web项目

38186c4e015f33cef0b143e13039eba7.png

Web项目初始化SpringIoc容器

先新建一个Web项目,然后再导入开发项目必须的jar包,需要的jar包有:spring-java的6个jar和spring-web.jar。

导入jar包后我们要在项目的web.xml文件中配置spring-web.jar提供的监听器,该监听器可以在服务器启动时初始化Ioc容器。

org.springframework.web.context.ContextLoaderListener

然后再用context-param告诉监听器Ioc容器的位置,在 param-value里面通过classpath可指出要用哪些SpringIoc容器

contextConfigLocation classpath:applicationContext.xml, classpath:applicationContext-* 

通过"*"可引入星号前面名称相同,但后面名称不同的所有SpringIoc容器。

 classpath:applicationContext-*  classpath:applicationContext-Controller, classpath:applicationContext-Dao, classpath:applicationContext-Service 

拆分Spring配置文件

有两种拆分方法,一种是根据三层结构拆分,另一种是根据功能结构拆分。例如

 classpath:applicationContext-Controller,  classpath:applicationContext-Service,  classpath:applicationContext-Dao 

就是根据三层结构,在一个xml配置文件中配置所有Servlet文件,在一个xml配置文件中配置所有Service文件,在一个xml配置文件中配置所有Dao文件。有时候还需要在一个xml配置文件中配置所有数据库文件。

从SpringIoc容器中获取数据

先建好各个层的文件,然后在SpringIoc容器中通过bean实例化每个层的对象。

在web.xml配置文件中定义好运行Servlet文件所需的代码后,然后在Servlet文件通过重写init方法来获取bean,最后运行服务器即可。

@WebServlet(name = "QueryStudentByIdServlet")public class QueryStudentByIdServlet extends HttpServlet { IStudentService studentService; //通过springioc容器的set注入将studentService 注入给Servlet public void setStudentService(IStudentService studentService) { this.studentService = studentService; }  //servlet初始化方法:在初始化时,获取SpringIoc容器中的bean对象 @Override public void init() throws ServletException { //在Web项目中用此方法获取Spring上下文对象,需要spring-web.jar ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext()); //在Servlet容器中,通过getBean获取Ioc容器中的Bean studentService = (IStudentService) context.getBean("studentService"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = studentService.queryStudentById(); request.setAttribute("name
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值