基于注解的控制器
在控制器中使用注解,可以在一个控制器中处理多个请求
工程目录
注意的是这里把spring的配置文件放到了config中,所以在注册dispatcher的时候要注明位置
配置文件
web.xml:
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/springmvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
springmvc-config.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="app03a.controller"/>
<mvc:annotation-driven/>
<mvc:resources mapping="/css/**" location="/css/"/>
<mvc:resources mapping="/.*html" location="/"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
1. 配置文件中最重要的是<context:component-scan base-package="app03a.controller"/>
的配置,指的是指示Spring MVC 扫描目标包中的类
2. <mvc:annotation-driven/>
注册用于支持基于注解的控制器的请求处理方法的bean对象
3. <mvc:resources>
指示哪些静态资源需要单独处理,不通过dispatcher servlet
Controller
@org.springframework.stereotype.Controller
public class ProductController {
private static final Log logger = LogFactory.getLog("ProductController.class");
@RequestMapping("/product_input")
public String inputProduct(){
logger.info("inputProduct calles");
return "ProductForm";
}
@RequestMapping("/product_save")
public String saveProduct(ProductForm productForm, Model model){
logger.info("saveProduct called");
//不在需要new Form对象
Product product = new Product();
product.setName(productForm.getName());
product.setDescription(productForm.getDescription());
try{
product.setPrice(Float.parseFloat(productForm.getPrice()));
}catch (NumberFormatException e){
e.printStackTrace();
}
//添加到实体类
model.addAttribute("product", product);
return "ProductDetails";
}
}
1. 注意的是在每个方法中返回字符串的时候,因为我们已经配置了视图解析器,所以返回的时候视图解析器会根据我们制定的路径去寻找对应的jsp给我们返回视图
2. Spring MVC在每一个请求处理方法被调用时创建一个Model实例,用于增加需要显示在视图中的属性。调用model.addAttribute("product", product)
就可以像HttpServletRequest中那样访问了(EL表达式)