spring mvc配置

来源:互联网 发布:保卫萝卜3炮台数据 编辑:程序博客网 时间:2024/06/02 06:31

1、引入jar包: (spring3)----spring3引入的jar包与spring2存在很大的差别,spring2是引入一个万能的spring.jar,而一般是这几个,不过根据功能还可以自己定制。
org.springframework.web.servlet-3.1.1.RELEASE.jar
org.springframework.asm-3.1.1.RELEASE.jar
org.springframework.beans-3.1.1.RELEASE.jar
org.springframework.context-3.1.1.RELEASE.jar
org.springframework.core-3.1.1.RELEASE.jar
org.springframework.expression-3.1.1.RELEASE.jar
org.springframework.web-3.1.1.RELEASE.jar
commons-logging-1.1.1.jar   spring依赖的jar包
配置log4j:log4j-1.2.15.jar
一般还需要jstl-1.2.jar包(新版eclipse自带)

2、配置web.xml文件:增加spring处理servlet
   <servlet>
   <servlet-name>springMvc</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
   <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
   <servlet-name>springMvc</servlet-name>
   <url-pattern>*.do</url-pattern>
  </servlet-mapping>

3、新建配置文件<servlet-name>-serlvet.xml文件:此处为springMvc-servlet.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"
 xmlns:p="http://www.springframework.org/schema/p"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

 <context:component-scan base-package="net.spring.controller" />

 <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
  <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
  <property name="prefix" value="/WEB-INF/jsp/" />
  <property name="suffix" value=".jsp" />
 </bean>
</beans>

<context:component-scan base-package="net.spring.controller" /> 初始化路径下类
3、处理请求的控制类(此类由@Controller注解,方法中有处理某个请求的注解@RequestMapping("helloWorld.do"))
@Controller注解表明这是一个控制类,@RequestMapping后面的参数表明处理的具体的请求。
package net.spring.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.sun.org.apache.commons.logging.Log;
import com.sun.org.apache.commons.logging.LogFactory;

@Controller
public class HelloWorldController {
 protected final Log log = LogFactory.getLog(getClass());
 @RequestMapping("helloWorld.do")
 public ModelAndView helloWorld(){
  log.debug("this is the debug");
  log.info("this is the info");
  log.error("this is the error");
  return new ModelAndView("helloworld","message","message");
 }
}
return new ModelAndView("helloworld","message","message");表明返回的是helloworld路径,增加上配置文件中的前缀和后缀表明是跳转到/WEB-INF/jsp/helloworld.jsp页面。
第三个“message”可以是需要在页面进行解析的其他模型。
log是日志类。
4、log4j.properties配置略。

5、index.jsp

<a href="helloworld.do">hello</a>

原创粉丝点击