spring mvc请求controller访问方式

1.一个Controller里含有不同的请求url

@Controller  //类似Struts的Action
public class TestController {
    @RequestMapping("test/login.do")  // 请求url地址映射,类似Struts的action-mapping
    public String testLogin(@RequestParam(value="username")String username, String password, HttpServletRequest request) {
        // @RequestParam是指请求url地址映射中必须含有的参数(除非属性required=false)
        // @RequestParam可简写为:@RequestParam("username")

        if (!"admin".equals(username) || !"admin".equals(password)) {
            return "loginError"; // 跳转页面路径(默认为转发),该路径不需要包含spring-servlet配置文件中配置的前缀和后缀
        }
        return "loginSuccess";
    }
}

2.采用一个url访问,通过url参数来区分访问不同的方法

@Controller
@RequestMapping("/test2/login.do")  // 指定唯一一个*.do请求关联到该Controller
public class TestController2 {
    
    @RequestMapping
    public String testLogin(String username, String password, int age) {
        // 如果不加任何参数,则在请求/test2/login.do时,便默认执行该方法
        
        if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {
            return "loginError";
        }
        return "loginSuccess";
    }

    @RequestMapping(params = "method=1", method=RequestMethod.POST)
    public String testLogin2(String username, String password) {
        // 依据params的参数method的值来区分不同的调用方法
        // 可以指定页面请求方式的类型,默认为get请求
        
        if (!"admin".equals(username) || !"admin".equals(password)) {
            return "loginError";
        }
        return "loginSuccess";
    }
    
    @RequestMapping(params = "method=2")
    public String testLogin3(String username, String password, int age) {
        if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {
            return "loginError";
        }
        return "loginSuccess";
    }
}

3.RequestMapping在Class上,可看做是父Request请求url,而RequestMapping在方法上的可看做是子Request请求url,父子请求url最终会拼起来与页面请求url进行匹配

@Controller
@RequestMapping("/test3/*")  // 父request请求url
public class TestController3 {

    @RequestMapping("login.do")  // 子request请求url,拼接后等价于/test3/login.do
    public String testLogin(String username, String password, int age) {
        if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {
            return "loginError";
        }
        return "loginSuccess";
    }
}

4.在SpringMVC中常用的注解还有@PathVariable,@RequestParam,@PathVariable标记在方法的参数上,利用它标记的参数可以利用请求路径传值

@Controller  //类似Struts的Action
public class TestController {

	@RequestMapping(value="/comment/{blogId}", method=RequestMethod.POST)
	public void comment(Comment comment,@PathVariable int blogId) throws IOException {
    
	}
}

你可能感兴趣的:(spring,MVC)