1.首先是环境的搭建
导入jar包,就把spring的所有jar导进去就好,再加上commons-logging.jar包导入
注意:这里仅仅导入还不行,还需要把jar包拖动到项目的lib目录中
2.下面就是xml文件的配置了
由于我们是跟随潮流的人,所以就采用注解配置了,以前的那种bean name的那种配置就不用了
首先是DispatcherServlet的配置,我们配置在web.xml中
类图如图所示
我们在web.xml中这样写
testDynamicRule
myServlet
org.springframework.web.servlet.DispatcherServlet
1
myServlet
/
CharacterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
utf-8
CharacterEncodingFilter
/*
这里主要写两个配置
下面的是用来设置编码的,防止中文乱码
web.xml设置好了,我们再设置一下myServlet-servlet.xml
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
3.我们再在com.rf.controller中写一个controller类
package com.rf.controller;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.sun.xml.internal.bind.CycleRecoverable.Context;
@Controller
public class controller1 {
@RequestMapping("/addRule.do")
public String result(String username,Map context){
System.out.println("username is:"+username);
context.put("username", username);
System.out.println("hello");
return "hello";
}
@RequestMapping("/welcome")
public String welcome(){
System.out.println("welcome");
return "welcome";
}
}
这里采用注解的方式,现在类上面注解一个@Controller来 表明这是一个控制器
再在方法上面写上@RequestMapping(“/add”) 表示当访问/add时,就会返回hello.jsp
这里要注意一个问题,就是访问页面的时候把值怎么样传给控制器,控制器怎么把值传给视图
这里就是两个参数
函数中第一个参数就是访问时传过来的值
函数中第二个参数就是传给视图的值,以map的方式存在
但是呢,map是java的东西,spring本身有一个东西叫Model,所以应该这样做
@RequestMapping("/addRule.do")
public String result(String username,Model model){
System.out.println("username is:"+username);
model.addAttribute("username", username);
System.out.println("hello");
return "hello";
}
很多很详细的教程,我这里就不详细写了。
像爱酷网的孔浩的教程 还有跟我学spring mvc都是不错的教程
主要还是实际写应用吧。