在web开发中使用spring框架(基础)

在web开发中使用spring框架

按照之前学习,编写在servlet中使用spring

新建day02项目,导入spring核心开发jar包

在web开发中使用spring框架(基础)_第1张图片

业务层

在web开发中使用spring框架(基础)_第2张图片

package com.qst.service;
public class HelloService {
   
public void sayHello(){
        System.
out.println("我是一个快乐的Spring!");
    }
}

表现层(Web层) 从spring工厂获取对象

在web开发中使用spring框架(基础)_第3张图片

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 Applicationdisplay-name>
  <servlet>
    <servlet-name>HelloServletservlet-name>
    <servlet-class>com.qst.web.HelloServletservlet-class>
  servlet>
  <servlet-mapping>
    <servlet-name>HelloServletservlet-name>
    <url-pattern>/helloServleturl-pattern>
  servlet-mapping>
web-app>

HelloServlet.java

在web开发中使用spring框架(基础)_第4张图片

public class HelloServlet extends HttpServlet {
   
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
    }

   
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ApplicationContext ac =
new ClassPathXmlApplicationContext("applicationContext.xml");
        HelloService helloService = ac.getBean(
"helloService", HelloService.class);
        helloService.sayHello();
    }
}

xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      
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">
    <bean id="helloService" class="com.qst.service.HelloService">bean>
beans>

测试:

http://localhost:9898/helloServlet

在web开发中使用spring框架(基础)_第5张图片

你可能感兴趣的:(JAVAEE,javaee)