springMvc-03 基于注解的例子

在非注解的方式中,springmvc.xml文件中需要自己配置处理器映射器,处理器适配器,配置每一个控制器,并且每一个请求就要对应一个控制器类,开发很不方便。

注解方式的主要区别在于springmvc.xml文件的配置和处理器的开发代码。

1、springmvc.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: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-4.1.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.1.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

    <!--设置处理器扫包范围-->
    <context:component-scan base-package="rui.web"/>

    <!--让SpringMvc不处理静态资源-->
    <mvc:default-servlet-handler />

    <!--开启自动注册处理器映射器和处理器适配器-->
    <mvc:annotation-driven />

    <!--配置视图解析器,视图解析器用来解析处理器返回的ModelAndView对象-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp"></property>
        <property name="suffix" value=".jsp" ></property>
    </bean>

</beans>

2、处理器开发

在一个控制器内的增加了两个请求方法,请求地址分别是:

/test/index

/test/indexJson

package rui.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.jetbrains.annotations.NotNull;
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 rui.db.Model.ex_Order;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/*测试控制器*/
@Controller
@RequestMapping(value = "/test")
public class TestController  {

    @RequestMapping(value ="/index/{id}",method = RequestMethod.GET)
    public ModelAndView index() throws Exception {
        System.out.println("执行TestController");
        List<ex_Order> orderList = new ArrayList<ex_Order>();
        ex_Order item = new ex_Order();
        item.setOrderId("T006");
        item.setOrderDate(null);
        orderList.add(item);

        //创建返回的视图对象
        ModelAndView viewResult = new ModelAndView();
        //添加返回的数据和视图,视图映射到/WEB-INF/jsp/test/index.jsp视图
        viewResult.addObject("orderList",orderList);
        viewResult.setViewName("/test/index");
        return  viewResult;
    }

    @RequestMapping(value = "indexJson")
    public void indexJson(HttpServletRequest request, @NotNull HttpServletResponse response) throws  Exception{
        System.out.println("执行TestController");
        List<ex_Order> orderList = new ArrayList<ex_Order>();
        ex_Order item = new ex_Order();
        item.setOrderId("T006");
        item.setOrderDate(null);
        orderList.add(item);

        response.setContentType("text/html;charset=utf-8");
        ObjectMapper jsonTool = new ObjectMapper();
        response.getWriter().write(jsonTool.writeValueAsString(orderList));
    }
}

3、RequestMapping注解

可以标注在方法上,也可以标注在类上方。

RequestMapping主要包括如下的属性:

public interface RequestMapping extends Annotation {
      // 指定映射的名称
    public abstract String name();
      // 指定请求路径的地址
    public abstract String[] value();
      // 指定请求的方式,是一个RequsetMethod数组,可以配置多个方法
    public abstract RequestMethod[] method();
      // 指定所需要的参数及值
    public abstract String[] params();
      // 指定需要包含的请求头及值
    public abstract String[] headers();
      // 指定数据请求的格式
    public abstract String[] consumes();
      // 指定返回的内容类型
    public abstract String[] produces();
}

复杂的例子:

@RequestMapping(value = {"/modifyGet.do","/modifyGet1.do"}, method={RequestMethod.POST, RequestMethod.GET},
          consumes={"application/json"}, produces={"application/json"}, params={"name=mike","pwd=123456"},headers={"a=1"}) 
public Object addEmpGet()throws Exception {
     
    JSONObject responseObj = new JSONObject();
    responseObj.put("id", 1);
    return responseObj ;
} 

value

请求的的地址,允许配置多个地址。地址内部可以包含参数:例如:"/update/{userId}",会接受userId参数。

method

接受的Http方式,允许配置多个方式

params和headers

这两个属性的作用是类似的,可以对请求进一步过滤,如果输入的参数不包含对应的属性或者属性的值有错误,那么就会报HTTP Status [404] – [Not Found]的错误。

consumes

限定请求提交数据的类型方式,如果方式不匹配,则不尽兴响应

produces

限定请求接受的类型,当request请求头中的(Accept)类型中包含该指定类型才会返回响应。

 

 

 

 

 

 

 

 

posted @ 2022-02-12 17:44  草莓爸  阅读(26)  评论(0编辑  收藏  举报