SpringMVC

02、SpringMVC

一、响应数据
一、响应数据JSON
方法返回JavaBean对象,使用@ResponseBody注解Springmvc从而把数据转化为json格式。
注:
	1.导入jackson-databind依赖
	2.开启mvc的注解驱动

1、对象

	//使用@ResponseBody返回JSON字符串
    @ResponseBody
    @RequestMapping("/returnJson")
    public User returnJson(){
        System.out.println("returnJson...");
        return new User("颤三", "123456","123445578920",18);
    }

2、List集合

	//使用@ResponseBody返回JSON字符串
	@ResponseBody
    @RequestMapping("/returnJson02")
    public List<User> returnJson02(){
        ArrayList<User> list = new ArrayList<>();
        list.add(new User("张三", "123456","123445578920",18));
        list.add(new User("张三1", "124456","123445578921",17));
        list.add(new User("张三2", "125456","123445578922",16));
        list.add(new User("张三3", "126456","123445578923",15));
        list.add(new User("张三4", "127456","123445578925",14));
        return list;
    }
二、表现层数据封装
1、前端接收数据格式-创建结果模型类,把数据封装到data属性中;
2、前端接收数据格式-把操作结果封装到code属性中;
3、前端接受数据格式-把特殊消息封装到message(msg)属性中

1、设置统一的数据返回结果类(属性个数不定,看需求)

public class R{
	private int code;
	private Object data;
	private String name;
}
/**
 * @Restcontroller = @Controller + @ResponseBody
 */
//@Controller
//@ResponseBody
@RestController
public class BookController {
    //@ResponseBody
    @RequestMapping("/add")
    public R add(int number){
        if (number == 1){
            return new R(1, null, "添加成功");
        }
        return new R(0, null, "添加失败");
    }
}

2、设置统一的数据返回结果编码(属性个数不定,看需求)

public class Code {
    public static final Integer SAVE_OK = 20011;
    public static final Integer DELETE_OK = 20021;
    public static final Integer UPDATE_OK = 20031;
    public static final Integer GET_OK = 20041;
    public static final Integer SAVE_ERR = 20010;
    public static final Integer DELETE_ERR = 20020;
    public static final Integer UPDATE_ERR = 20030;
    public static final Integer GET_ERR = 20040;
}
三、异常处理

1、项目异常分类

1.业务异常(BusinessException)
	1.1 规范用户行为产生的异常。
	1.2 不规范的用户行为操作产生的异常
2.系统异常(SystemException)
	项目运行过程中可预计且无法避免的异常
3.其他异常(Exception)
	编程人员未预期到的异常

2、项目异常处理方案

1.业务异常(BusinessException)
	发送对应的消息传递给用户,提醒规范操作。
2.系统异常(SystemException)
	2.1 发送固定消息给用户,安抚用户。
	2.2 发送特定消息给运维人员,提醒运维。
	2.3 记录日记。
3.其他异常(Exception)
	3.1 发送固定消息给用户,安抚用户。
	3.2 发送特定消息给运维人员,提醒运维(纳入于其范围内)3.3 记录日记。

设置统一的数据返回结果编码(属性个数不定,看需求)

public class Code {
    public static final Integer SYSTEM_UNKNOW_ERROR = 50001;
    public static final Integer SYSTEM_TIMEOUT_ERROR = 50002;
    public static final Integer PROJECT_VALIDATE_ERROR = 60001;
	public static final Integer PROJECT_BUSINESS_ERROR = 60002;
}
四、拦截器
一、拦截器概念
1.拦截器(Interceptor):是一种动态拦截方法调用的机制,在springmvc中动态
					 拦截控制器方法的执行。
2.作用:
	2.1 在指定的方法调用前后执行预先设定的代码。
	2.2 阻止原始方法的执行。

1、配置拦截器springmvc.xml

<!--配置拦截器-->
<mvc:interceptors>
	<!--使用myIntercetpor 拦截器来拦截:test01请求-->
    <mvc:interceptor>
        <mvc:mapping path="/test01"/>
        <bean class="com.cwl.interceptor.MyInterceptor01"/>
    </mvc:interceptor>
</beans>
/*
 1. 自定义类,实现接口。HandlerInterceptor
 2. 实现3个方法
    preHandle
    postHandle
    afterCompletion
 3. 在springmvc.xml中登记这个拦截器
 */
public class MyInterceptor implements HandlerInterceptor {
	/*
     在controller方法执行之前,执行
       1. 返回true,即表示放行。 返回false 即表示拦截
       2. 如果拦截了请求,那么拦截器需要对这次请求进行回应,否则页面会出现一片空白
          2.1 跳转页面
          2.2 写一句话返回
    */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
   		System.out.println("preHandle...");
		return false;
    }
    
    // 在controller方法执行之后,视图渲染之前执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle...");
    }
    
    // 在页面渲染之后 执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...");
    }
二、拦截器与过滤器区别
1.归属不同:Filter属于servlet技术,Interceptor属于springmvc技术。
2.拦截内容不同:Filter对所有访问进行增强,Interceptor仅针对springmvc的
             访问进行增强。
三、多拦截器执行顺序
1.当配置多个拦截器时,形成拦截器链。
2.拦截器链的运行顺序参考拦截器添加顺序为准。
3.当拦截器中出现对原始处理器的拦截,后面的拦截器均终止运行。
4.当拦截器运行中断,仅运行配置在前面的拦截器的afterCompletion操作。

1、配置拦截器springmvc.xml

<!-- 配置拦截器-->
<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/test01"/>
         <bean class="com.cwl.interceptor.MyInterceptor02"/>
    </mvc:interceptor>
    <mvc:interceptor>
        <mvc:mapping path="/test01"/>
        <bean class="com.cwl.interceptor.MyInterceptor03"/>
    </mvc:interceptor>
    <mvc:interceptor>
        <mvc:mapping path="/test01"/>
        <bean class="com.cwl.interceptor.MyInterceptor04"/>
    </mvc:interceptor>
    </mvc:interceptors>
</beans>
五、REST风格
一、REST简介
1.REST(Representational State Transfer), 表现形式状态转换。
	1.1 传统风格资源描述形式:
		http://localhost/user/getById?id=1
		http://localhost/user/saveUser
	1.2 REST风格描述形式:
		http://localhost/user/1
		http://localhost/user
2.优点:
	2.1 隐藏资源的访问行为,无法通过地址得知对资源是何种操作。
	2.2 书写简化。
二、REST风格简介
1.按照REST风格访问资源是使用行为动作区分对资源进行了何种操作
	http://localhost/users		    查询全部用户信息    GET  
	http://localhost/users/1		查询指定用户信息    GET 
	http://localhost/users		    添加用户信息       POST
	http://localhost/users		    修改用户信息       PUT
	http://localhost/users/1		删除用户信息       DELETE
2.根据REST风格对资源进行访问称为RESTful

实例

	/*
	 添加用户:
       以前: localhost/addUser          post
       restFul: localhost/users         post
    */
    //@RequestMapping(value = "/users" , method = RequestMethod.POST)
    @PostMapping
    public R add(User user){
        System.out.println("add..." + user);
        return new R(1, null , "添加成功!");
    }
	/*
     删除用户:
        以前: localhost/deleteUser?id=3       get
         restFul: localhost/users/3           delete
     */
    @DeleteMapping("/{id}")
    public R delete(@PathVariable int id){
        System.out.println("delete..." + id);
        return new R(1, null , "删除成功!");
    }
	/*
     更新用户:
        以前:localhost/updateUser           post
        restFul: localhost/users            put
    */
    @PutMapping
    public R update(User user){
        System.out.println("update..." + user);
        return new R(1, null , "更新成功!");
    }
	/*
     查询所有:
        以前: localhost/findAll             get
        restFul: localhost/users            get
    */
    @GetMapping
    public R findAll(){
        System.out.println("findAll..." );
        return new R(1, null , "查询所有成功!");
    }
	  //ajax 发起 put 请求,携带过来 json数据
   	 /*
      根据id查询用户:
       以前:localhost/findById?id=3       get
       restFul: localhost/users/3         get
    */
    @GetMapping("/{id}")
    public R findById(@PathVariable int id){
        System.out.println("findById..." + id);
        return new R(1, null , "根据id查询成功!");
    }
<!--在web.xml配置过滤器,解决PUT请求,携带表单数据的问题-->
<filter>
	<filter-name>put</filter-name>
	<filter-class>org.springframework.web.filter.FormContentFilter</filter-class>
</filter>
<filter-mapping>
	<filter-name>put</filter-name>
	<url-pattern>/*</url-pattern>
</filter-mapping>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值