Spring整合Servlet

在實際開發中我們需要用到Spring和Servlet這樣的組合(比如寫一個小項目啥的)下面我來整理一下我我的整合:

第一步:在web.xml中註冊Spring的監聽器

這時我們在Web項目中添加Spring的第一步(當然肯定要添加Spring所需要的Jar包啦)

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	
	<!-- Spring -->
	<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/classes/applicationContext.xml
        </param-value>
    </context-param>
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
 
  </servlet-mapping>
	
   <welcome-file-list>
     <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>
</web-app>

第二步:編寫一個管理Servlet的類

這個類主要是將Servlet和Spring中的Bean結合起來,方便Spring對Servlet進行管理,起到一箇中轉的作用

package com.xwl.estore.servlet;

import java.io.IOException;

import javax.servlet.GenericServlet;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

@SuppressWarnings("serial")
/**
 * 我們自己實現的一個代理類用於將Servlet轉爲Spring管理的Servlet Bean
 */
public class ServletToBeanProxy extends GenericServlet {

	private String targetBean;//當前客戶端請求的Servlet名字
    private Servlet proxy;//代理Servlet
	
	@Override
	public void init() throws ServletException {
		super.init();
		WebApplicationContext wac = 
			WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()); //初始化Spring容器
        this.targetBean = getServletName();
        this.proxy = (Servlet) wac.getBean(targetBean);//調用ServletBean
        proxy.init(getServletConfig());//調用初始化方法將ServletConfig傳給Bean
	}

	@Override
	public void service(ServletRequest arg0, ServletResponse arg1)
			throws ServletException, IOException {
		proxy.service(arg0, arg1);//在service方法中調用bean的service方法,servlet會根據客戶的請求去調用相應的請求方法(Get/Post)
	}
}

第二步:在web.xml中註冊Servlet

注意這裏的Servlet是有規範的一定要遵循

 1、<servlet-name>的名字必須是Spring容器中ServletBean的id

 2、<servlet-class>必須是上面寫的代理類的全路徑com.xwl.estore.servlet.ServletToBeanProxy

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	
	<!-- Spring -->
	<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/classes/applicationContext.xml
        </param-value>
    </context-param>
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
	
	<!-- Servlet -->
  <servlet>
    <servlet-name>helloServlet</servlet-name>
    <servlet-class>com.xwl.estore.servlet.ServletToBeanProxy</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>helloServlet</servlet-name>
    <url-pattern>/HelloServlet</url-pattern>
  </servlet-mapping>
	
   <welcome-file-list>
     <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>
</web-app>

第三步:編寫ServletBean(這也是一個Servlet要繼承HttpServlet)

package com.xwl.estore.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.xwl.estore.service.UserService;

@SuppressWarnings("serial")
@Controller
@Scope("prototype")
public class HelloServlet extends HttpServlet {

	private UserService userService;
	
	@Resource
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("Get");
		PrintWriter out = response.getWriter();
        out.println(userService.sayHello("Hello,Spring.Servlet"));	
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("Post");
		PrintWriter out = response.getWriter();
        out.println(userService.sayHello("Hello,Spring.Servlet"));		
	}

}

第四步:編寫Spring配置文件(applicationContext.xml)

這裏我用的是annotation的方式
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="
	http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
	http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-2.5.xsd
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
    http://www.springframework.org/schema/aop 
	http://www.springframework.org/schema/aop/spring-aop-2.5.xsd   
	">
   <context:annotation-config></context:annotation-config>
   <context:component-scan base-package="com.xwl.estore"></context:component-scan>

</beans>
第五步:進行測試

爲了測試我編寫了一個Service類(一個接口和一個實現)

下面是Service接口

package com.xwl.estore.service;

public interface UserService {

	public String sayHello(String hello);
}
下面是Service接口的實現

package com.xwl.estore.service.impl;

import org.springframework.stereotype.Service;

import com.xwl.estore.service.UserService;

@Service
public class UserServiceImpl implements UserService {

	public String sayHello(String hello) {
		return hello;
	}
}
在瀏覽器中輸入Url http://localhost:8080/EStore/HelloServlet 進行訪問結果如下:

Hello,Spring.Servlet


說明:Spring整合了Servlet之後我們就可以整合Hibernate,JDBC,和事務管理等,這裏只是搭建搭建一個HelloWorld。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章