1. 程式人生 > >Spring MVC 配置及應用(1)

Spring MVC 配置及應用(1)

一,分析

目的:通過控制器呼叫hello.jsp 

/hello.do

-->DispatcherServlet(配置)

-->HanlderMapping(配置)

-->HelloController(編寫+配置)

-->ViewResolver

-->/WEB-INF/hello.jsp(編寫)

二,搭建Spring Web MVC 開發環境

-->引入IOC,webmvc開發包

-->src下新增applicationContext.xml

      


三,編寫hello.jsp, HelloController (方便之後統一配置檔案)

1.在WEB-INF下建立hello.jsp(與web.xml同級),使其不能直接通過網址訪問

2.HelloControllerX需要繼承介面Controller,實現父類的方法handleRequest( HttpServletRequest request,HttpSeverletReponse response)

package Package1;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class HelloController implements Controller{

	public ModelAndView handleRequest(HttpServletRequest arg0,
			HttpServletResponse arg1) throws Exception {
		// TODO Auto-generated method stub
		ModelAndView mav=new ModelAndView();
		mav.setViewName("hello"); //設定檢視名字XXX.jsp  ("XXX")
		mav.getModel().put("msg", "模型資料");//模型資料可以是字元和列
		//等價於request.setAttribute("msg", "模型資料");
		return mav;
	}

}

四,配置DispatcherServlet(在web.xml中)

<servlet>
	<servlet-name>springmvc</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet.class</servlet-class>
	
	<init-param>
	<!-- contextConfigLocation需要記住 -->
	<param-name>contextConfigLocation</param-name>
	<param-value>classpath:applicationContext.xml</param-value>
	</init-param>
	<!-- 優先順序  1高-->
	<load-on-startup>1</load-on-startup>
	</servlet>
	
	<servlet-mapping>
	<servlet-name>springmvc</servlet-name>
	<url-pattern>*.do</url-pattern>
	</servlet-mapping>

五、配置HanlderMapping(applicationContext.xml中)

<!-- 配置handlerMapping -->
<bean id="handlermapping" 
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<!-- 指定請求和controller對應關係     一組一個set注入以集合注入 -->
<property name="mappings">
  <props>
  <prop key="/hello.do">helloController</prop>
  </props>
</property>
</bean>

六 、配置HelloController(applicationContext.xml中)

<!-- 配置controller  獲得hello 名字 這裡的id 是上面的key對應的資料--> 
<bean id="helloController" class="Package1.HelloController">
</bean>

七、配置ViewResolver

<!-- 配置viewResolver  加上字首字尾-->	
<bean id="viewresolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/">
</property>
<property name="suffix" value=".jsp">
</property >
</bean>
    八、啟動Tomcat伺服器,佈置web project 執行