SpringMVC (二)springMVC的常用注解

237 阅读6分钟

1.@RequestMapping

(一)作用:建立请求URL和处理方法之间的对应关系

(二)作用范围:可以作用于类名之上或是方法之上

  • 作用在类上:第一级的访问目录
  • 作用在方法上:第二级的访问目录
  • 细节:路径可以不编写 / 表示应用的根目录开始

(三)属性

  • path 指定请求路径的url
@Controller
@RequestMapping(path = "/test")
@ResponseBody
public class HelloController {
    @RequestMapping(path="/hello")
    public String sayHello(){
        System.out.println("hello springMVC");
        return "success";
    }
}
  • value 和path属性是一样的,当只有一个参数时可以省略
@Controller
@RequestMapping(value = "/test")
@ResponseBody
public class HelloController {
    @RequestMapping(value="/hello")
    public String sayHello(){
        System.out.println("hello springMVC");
        return "success";
    }
}
  • mthod 指定该方法的请求方式
@Controller
@RequestMapping(path = "/test",method = RequestMethod.GET)
@ResponseBody
public class HelloController {
    @RequestMapping(path="/hello")
    public String sayHello(){
        System.out.println("hello springMVC");
        return "success";
    }
}    
  • params:用于指定请求参数

要求请求的参数的key和value必须和配置一模一样

//请求参数中必须有参数username
@RequestMapping(path = "/testRequestMapping",params={"username"})
    public String testRequestMapping(){
        System.out.println("测试RequeMapping注解");
        return "success";
    }

//请求参数中必须有参数username,且参数名为heihei
@RequestMapping(path = "/testRequestMapping",params={"username=heihei"})
    public String testRequestMapping(){
        System.out.println("测试RequeMapping注解");
        return "success";
    }
  • headers 发送的请求中请求头 必须包涵指定的内容
//请求参数中必须有参数username,且请求头中必须包含Accpet
@RequestMapping(path = "/testRequestMapping",params={"username"},headers={"Accept"})
	public String testRequestMapping(){
        System.out.println("测试RequeMapping注解");
        return "success";
    }

(四)请求参数的绑定

  • 1.String数据类型

当网页传入的参数与controller的方法参数相同时,会自动的对参数进行绑定

<a href="param/testParam?username=hehe">请求参数</a>  //请求参数必须与方法的参数相同

@RequestMapping(path="/testParam")
    public String testParam(String username){
        System.out.println(username);
        return "success";
    }
  • 2.javaBean

实体类型(JavaBean),前端的参数名必须与javabean中的属性名相同

//简单的javaBean,该javaBean只包涵基本类型的属性
姓名:<input type="text" name="username" /><br/>
密码:<input type="text" name="password" /><br/>
金额:<input type="text" name="money" /><br/>

@RequestMapping(path ="/saveAccount")
public String testsaveAccount(Account account){
    System.out.println("测试saveAccount");
    System.out.println(account.getUsername());
    return "success";
}

//复杂的javaBean,该javaBean中包涵引用数据类型

姓名:<input type="text" name="username" /><br/>
密码:<input type="text" name="password" /><br/>
金额:<input type="text" name="money" /><br/>
用户名:<input type="text" name="user.name" /><br/>
用户密码:<input type="text" name="user.password" /><br/>

@RequestMapping(path ="/saveAccount")
public String testsaveAccount(Account account){
    System.out.println("测试saveAccount");
    System.out.println(account.getUsername());
    return "success";
}

2.自定义编写类型转换器

有时需要将传入的String参数转化为Date数据类型,可以通过自定义转换器实现,该类必须实现Converter接口

使用方法:

  • 第一步:定义转换类,实现Converter接口
public class Stringtodate implements Converter<String, Date> {
    @Override
    public Date convert(String source) {
        Date parse=null;
        if(source==null) {
            throw new RuntimeException("请您传入参数");
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            parse = simpleDateFormat.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return parse;
    }
}
  • 第二步:在spring容器中加入转化器
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.qunar.controller.Stringtodate"/>
            </set>
        </property>
 </bean>

 <!-- 开启SpringMVC框架注解的支持 加入转换器的位置-->
<mvc:annotation-driven conversion-service="conversionService"/>

3.使用servlet对象

spring支持原生的ServletAPI对象,作为控制器方法的参数

HttpServletRequest
HttpServletResponse
HttpSession
@RequestMapping("/testServletAPI")
public String testServletAPI(HttpServletRequest request,HttpServletResponse response,HttpSession session) {
	System.out.println(request);
	System.out.println(response);
	System.out.println(session);
	return "success";
}

4.@RequestParam

(一)作用

把请求中指定名称的参数给控制器中的形参复制

(二)属性

value:请求参数中的名称。

required:请求参数中是否必须提供此参数。默认值:true。表示必须提供,如果不提供将报错。

@RequestMapping(path = "/testDate")
    public String testDate(@RequestParam(value = "date")Date date){
        System.out.println("测试类型转换器");
        System.out.println(date);
        return "success";
}

5.@RequestBody

(一)作用

用于获取请求体内容。直接使用得到是 key=value&key=value...结构的数据。 get 请求方式不适用。get请求返回结果直接为null

(二)属性

required:是否必须有请求体。默认值是:true。当取值为 true 时,get 请求方式会报错。如果取值为 false,get 请求得到是 null。

    @RequestMapping(path = "/testRequestMapping")
    public String testRequestMapping(@RequestBody(required = false)String body){
        System.out.println("测试RequeMapping注解");
        System.out.println(body);
        return "success";
    }

6@PathVariable

用于将请求中的占位符按照指定的名称赋值给处理函数的形参

//请求url:http://localhost:8080/test/testVariable/100/aaa?a=100

@RequestMapping(path = "/testVariable/{id}/{path}")
    public String testVariable(@PathVariable("id")Integer id, @PathVariable("path") String path){
        System.out.println(id);
        System.out.println(path);
        return "success";
}

7.@ModelAttribute

(一)作用

  • 出现在方法上,表示当前方法会在控制器的方法执行之前,先执行。它可以修饰没有返回值的方法,也可以修饰有具体返回值的方法。

  • 出现在参数上,获取指定的数据给参数赋值。

(二)属性:

value:用于获取数据的 key。key 可以是 POJO 的属性名称,也可以是 map 结构的 key。

(三)基本使用

@ModelAttribute
    public void testModelAttribute(String name) {
        System.out.println(name);
    }

    @RequestMapping(path="/hello")
    public String sayHello(String name){
        System.out.println("hello springMVC");
        System.out.println("name:"+ name);
        return "success";
    }

(四)ModelAttribute 修饰方法带返回值

@ModelAttribute
    public User returnUser(String name){
        System.out.println(name);
        User user = new User();
        user.setName("zhangsan");
        user.setAge(13);
        System.out.println(user);

        return user;
    }

    @RequestMapping(path="/user")
    public String getUser(User user) {
        System.out.println(user);
        return "success";
    }

(五)ModelAttribute 修饰方法不带返回值

@ModelAttribute
public void showModel(String username,Map<String,User> map) {
	//模拟去数据库查询
	User user = findUserByName(username);
	System.out.println("执行了 showModel 方法"+user);
	map.put("abc",user);
}


@RequestMapping("/updateUser")
public String testModelAttribute(@ModelAttribute("abc")User user) {
	System.out.println("控制器中处理请求的方法:修改用户:"+user);
	return "success";
}

8.@ResponseBody

(一)作用

该注解用于将 Controller 的方法返回的对象,通过 HttpMessageConverter 接口转换为指定格式的 数据如:json,xml 等,通过 Response 响应给客户端,默认情况只能返回String数据

使用方式:倒入jackson依赖即可

<dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.8.7</version>
    </dependency>
@RequestMapping(path="/user")
    public User getUser(User user) {
        System.out.println(user);
        return user;
    }

9.异常处理器

系统中异常包括两类:预期异常和运行时异常 RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。 系统的 dao、service、controller 出现都通过 throws Exception 向上抛出,最后由 springmvc 前端 控制器交由异常处理器进行异常处理

SpringMVC的自定义异常处理器实现HandlerExceptionResolver接口

public class CustomExceptionResolver implements HandlerExceptionResolver {
	@Override
	public ModelAndView resolveException(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex) { 
    ex.printStackTrace();
    CustomException customException = null;
    //如果抛出的是系统自定义异常则直接转换
    if(ex instanceof CustomException){
    customException = (CustomException)ex;
    }else{
    //如果抛出的不是系统自定义异常则重新构造一个系统错误异常。
    customException = new CustomException("系统错误,请与系统管理 员联系!");
    }
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("message", customException.getMessage());
    modelAndView.setViewName("error");
    return modelAndView;
	}
}

将异常处理器配置进spring容器

<!-- 配置自定义异常处理器 -->
<bean id="handlerExceptionResolver" class="com.itheima.exception.CustomExceptionResolver"/>

10.拦截器

Spring MVC 的处理器拦截器类似于 Servlet 开发中的过滤器 Filter,用于对处理器进行预处理和后处理。用户可以自己定义一些拦截器来实现特定的功能。

springMVC的拦截器实现了HandleInterceptor接口

public class HandlerInterceptorDemo1 implements HandlerInterceptor {
	@Override
	public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
	System.out.println("preHandle 拦截器拦截了");
	return true;
	}
    
    //在拦截器链内所有拦截器返成功调用,是 DispatcherServlet 向客户端返回响应前被调用
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response,Object handler,ModelAndView modelAndView) throws Exception {
	System.out.println("postHandle 方法执行了");
	}
    //在 DispatcherServlet 完全处理完请求后被调用, 可以在该方法中进行一些资源清理的操作。
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception {
	System.out.println("afterCompletion 方法执行了");
	}
}

spring容器中配置拦截器

<!-- 配置拦截器 -->
<mvc:interceptors>
	<mvc:interceptor>
		<mvc:mapping path="/**"/>
		<bean id="handlerInterceptorDemo1"class="com.web.interceptor.HandlerInterceptorDemo1">	</bean>
	</mvc:interceptor>
</mvc:interceptors>

配置多个拦截器

<!-- 配置拦截器 -->
<mvc:interceptors>
	<mvc:interceptor>
		<mvc:mapping path="/**" /><!-- 用于指定对拦截的 url -->
		<mvc:exclude-mapping path=""/><!-- 用于指定排除的 url-->
		<bean id="handlerInterceptorDemo1"class="com.web.interceptor.HandlerInterceptorDemo1">	</bean>
	</mvc:interceptor>
    <mvc:interceptor>
    		<mvc:mapping path="/**" />
			<bean id="handlerInterceptorDemo2" class="com.web.interceptor.HandlerInterceptorDemo2"></bean>
	</mvc:interceptor>
</mvc:interceptors>