spring mvc 配置

一个简单的spring mvc配置实例步骤:

1.添加相关的jar包,spring.jar,jstl.jar,standard.jar

2.在com.demo1.web.controller下,新建,HelloController.java

package com.demo1.web.controller;

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 {
 private String name;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public ModelAndView handleRequest(HttpServletRequest arg0,
   HttpServletResponse arg1) throws Exception {
  // TODO Auto-generated method stub
  return new ModelAndView("hello", "name", name);
 }

}

3.配置web.xml文件,代码如下:

<!-- 配置DispatcherServlet -->
 <servlet>
  <servlet-name>demo1</servlet-name>
  <servlet-class>
   org.springframework.web.servlet.DispatcherServlet
  </servlet-class>
 </servlet>
 <!-- 配置DispatcherServlet的映射 -->
 <servlet-mapping>
  <servlet-name>demo1</servlet-name>
  <url-pattern>*.html</url-pattern>
 </servlet-mapping>
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
 
 <jsp-config>
  <jsp-property-group>
   <description>demo 1</description>
   <url-pattern>*.jsp</url-pattern>
   <el-ignored>false</el-ignored>
   <scripting-invalid>false</scripting-invalid>
  
  </jsp-property-group>
 </jsp-config>

4.在web-inf下,建立spring 的配置文件,demo1-servlet.xml,这里,demo1与web.xml中servlet-name的名字对应。代码如下:

<!-- 处理器映射器,使用处理器名字作为URL -->
 <bean
  class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
 <!-- 处理器,名字为/hello.html -->
 <bean name="/hello.html"
  class="com.demo1.web.controller.HelloController">
  <property name="name" value="Rod Johnson" />
 </bean>
 <!-- 视图解析器 -->
 <bean
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/WEB-INF/jsp/" />
  <property name="suffix" value=".jsp" />
 </bean>

5.在web-inf下建立一个jsp目录,新建hello.jsp文件,即,spring 调用mvc控制器后,view所返回的页面,代码如下:
 <body>
  Hello,${name }
 </body>

部署到tomcat下,一个helloworld版的spring mvc就OK了。

你可能感兴趣的:(spring,jsp,mvc,Web,servlet)