spring可以通过@Controller注解自动发现你的控制器类以及@RequestMapping注解中的请求映射,这样就免去了在Bean配置文件中配置它们的麻烦。
这里写了一个简单例子:
springmvc配置文件如下:
<?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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 扫描注解的驱动 -->
<mvc:annotation-driven />
<!-- 设置扫描包 -->
<context:component-scan base-package="com.springmvc.controllers" />
<!-- 视图解析器 -->
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 后缀 -->
<property name="suffix" value=".jsp" />
</bean>
</beans>
下面时
C
ontroller控制器的代码:
package com.springmvc.controllers;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.springmvc.pojo.User;
@Controller
@RequestMapping("/annotation/") //设置请求路径
public class AnnotationController {
//url=====>>>>>/annotation/index 执行该方法
@RequestMapping("index")
public ModelAndView index(HttpServletRequest request,HttpServletResponse response) {
System.out.println("**********annotation——index***********");
return new ModelAndView("index");
}
//url=====>>>>>/annotation/multi 执行该方法
@RequestMapping(value="multi",method=RequestMethod.POST)
public String multi(HttpServletRequest request) {
System.out.println("**********annotation——multi***********");
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
User user = new User();
user.setName(name);
user.setAge(age);
System.out.println(user);
request.setAttribute("user", user);
return "annotation"; //返回视图名称
}
}
前端 annotation . jsp页面:
表单:
提交表单后的jsp页面:
<h1>Hello annotation!</h1>
<h1>user:${user.name }</h1>
<h1>age:${user.age }</h1>
提交表单后的执行的效果: