ウェブプロジェクトを統合

2618 ワード

まず私達の需要式の前置きです.webプロジェクトではspringをどうやって開発しますか?使うなら new Class PathXml Apple Conteet 毎回xmlをロードして、毎回スプリング容器を作るのに相当します.実際の開発では、容器は一つしかない.その後、繰り返しスプリング容器からコンテンツを取得します.
設定ファイルを自動的にロードして、spring容器を生成し、Servlet Contectの機能領域に保存します.SpringはモニタープログラムConttext Loader Listenerを提供します. (Servlet Contactext Listener実現)、tomcat起動時に実行します.起動時にプロファイルを読み込みます.
段栗のデモンストレーションをお願いします.
service層(便宜のために直接来ます):
public class UserService 
{
	public void addUser()
	{
		System.out.println("add user");
	}
}
その後、appication Contect.xml配置beanに行きます.
<bean id="userService" class="com.canyugan.service.UserService">
       </bean>
index.jspに私達のテストを書いて、直接ページをクリックして、servletはaddUser方法を処理して、そしてサーバーで出力します.
<body>
    <a href="${pageContext.request.contextPath}/HelloServlet">  </a>
  </body>
servletは急いで書かないで、先にweb.xmlの配置に行きます.
<!-- 
      web                   
    name    	class      
  -->
  <context-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  
  <!--         spring     -->
  <listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
ここで注意したいのですが、モニターだけを設置した場合、Bugに出会えたのは幸運です.Bugの長さはどうですか?
Caused by: java.io.FileNotFoundException: Could not open Servlet Context resource [/WEB-INF/appication Contect.xml]はどういう意味ですか?ファイルの場所が見つかりません.私たちはファイルの位置を設定する必要があります.上に私達が配置したあのxmlがあります.
spring容器がすでにあり、servlet Contectに入れられている以上、私達はservletで取り出して、私達の業務を実現することができます.
public class HelloServlet extends HttpServlet 
{
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException 
	{
		//  1:   servletcontext       
		/*WebApplicationContext webApplicationContext=
				(WebApplicationContext) this.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);*/
		//  2:     
		WebApplicationContext webApplicationContext=WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
		
		UserService userService=(UserService) webApplicationContext.getBean("userService");
		userService.addUser();
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException 
	{
		doGet(request, response);
	}
}
これで大成功となる.