1.配置web.xml,代码如下:
<!--配置Sring MVC的核心控制器DispatcherServlet -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!--为DispatcherServlet建立映射 -->
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
2.编写HelloWorldAction.java,主要代码:
1. public ModelAndView handleRequest(HttpServletRequest req,
2. HttpServletResponse res)
3. throws ServletException, IOException {
4. // 在该方法中处理用户请求
5. Mapmodel = new HashMap();
6.
7. // 将helloWorld属性存入model中
8. model.put("helloWorld", getHelloWorld());
9.
10. // 调用getViewPage获取要返回的页面
11. return new ModelAndView(getViewPage(), model);
12. }
3.编写index.jsp,主要代码:
<body>
<h1>您输入的欢迎语是<%=str%></h1>
</body>
4.编写applicationContext.xml,主要代码:
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver">
</bean>
<!--配置控制器的映射-->
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="helloWorld.do">helloWorldAction</prop>
</props>
</property>
</bean>
<!--配置视图-->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.InternalResourceView
</value>
</property>
</bean>
<!--指定控制器的实现类,并且配置其参数的值-->
<bean id="helloWorldAction"
class="com.wangsy.spring.action.HelloWorldAction">
<property name="helloWorld">
<value>Hello Spring World!</value>
</property>
<property name="viewPage">
<value>index.jsp</value>
</property>
</bean>
网友评论