spring-mvc基于注解的配置
将配置文件修改为:
<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"> <!-- 1.配置注解扫描位置 --> <context:component-scan base-package="com.royal.backoffice.web.controller"/> <!-- 2. 配置处理器映射,通过注解来查找 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean> <!-- 3.配置注解处理适配器来执行控制器的方法 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <!--配置一个json转换器,需要导入jackson与jackson-mapper两个jar包--> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean> </property> </bean> <!-- 4.配置springmvc视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
然后创建一个controller包用于放置控制器在类里面添加注解,如:
@Controller
@RequestMapping("/user")
其他注解:
@ResponseBody:把后台pojo转换json对象,返回到页面。
@RequestBody:接受前台json数据,把json数据自动封装javaBean
需要导入jackson与jackson-mapper两个jar包