1. 程式人生 > >Spring 之在Web專案中使用

Spring 之在Web專案中使用

Spring 在Web中的第一次應用

1、配置Web環境,或者下載有Web外掛的eclipse
2、建立Web專案,選擇Dynamic Web Project(動態Web專案,對應的靜態Web專案 Static Web Project)
3、匯入jar包
commons-logging-1.1.1.jar
servlet-api.jar
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
spring-web-4.0.0.RELEASE.jar
spring-webmvc-4.0.0.RELEASE.jar
4、建立bean

public class Data {
    private String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "Data [id=" + id + "]";
    }

}

5、建立Spring配置檔案

檔名:ApplicationContext.xml

<?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="data" class = "com.led.htkj.Data">
<property name="id" value = "1111111111" /> </bean> </beans>

6、IOC容器在非Web應用中的main方法中直接建立,而在Web應用中,應該在伺服器載入時就建立IOC容器

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

@WebListener
public class SpringServletContextListener implements ServletContextListener {


    public SpringServletContextListener() {

    }

    public void contextInitialized(ServletContextEvent arg0) {

        ServletContext sct = arg0.getServletContext();
        String config = sct.getInitParameter("configLocation");
        System.out.println(config);
        ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
        sct.setAttribute("ApplicationContext", ctx);
    }

    public void contextDestroyed(ServletContextEvent arg0) {

    }

}

如上程式碼,實現ServletContextListener 介面,在contextInitialized中建立IOC容器,並儲存在ServletContext 中。

然後要在web.xml配置檔案中做如下配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_3_0.xsd" version="3.0">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <!-- 配置Spring配置檔案的名稱和位置 -->
  <context-param>
    <param-name>configLocation</param-name>
     <param-value>classpath:ApplicationContext.xml</param-value>
  </context-param>
  <!-- 啟動IOC容器的listener -->
  <listener>
    <listener-class>com.led.htkj.servlets.listener.SpringServletContextListener</listener-class>
  </listener>
</web-app>

7、編寫servlet

@WebServlet("/CollectingData")
public class CollectingData extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public CollectingData() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext  servletContext = getServletContext();
        ApplicationContext ctx = (ApplicationContext) servletContext.getAttribute("ApplicationContext");
        Data data = (Data) ctx.getBean(Data.class);
        System.out.println(data.toString());;
    }
}

8、建立jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href = "CollectingData"> here</a>
</body>
</html>

啟動後在頁面中點選here結果在控制檯輸出:

Data [id=1111111111]

總結

錯誤1:class path resource [applicationContext.xml] cannot be opened because it does not exist
錯誤2:No qualifying bean of type [com.led.htkj.Data] is defined
都是因為:

`
<context-param>
<param-name>configLocation</param-name>
<param-value>classpath:ApplicationContext.xml</param-value>
</context-param>

中ApplicationContext.xml首字母A被小寫,報錯誤1,百度後在classpath後加了*,結果報錯誤2,最終發現原來是大字母被小寫,解決問題`