springmvc学习02-使用注解开发-RestFul-Json

1 篇文章 0 订阅
1 篇文章 0 订阅

springmvc学习02

  • 出现了个大大大无语问题

1.问题内容:idea里面maven项目变成灰色,web.xml直接不提示了

2.原因分析:会出现这种情况的原因是不小心忽略了 maven 项目的模块,需要把忽略的 ignore files 取消选中,不再忽略

3.解决办法:settings → maven → ignoreed files,把 Maven Projects 里灰色项目对应的 ignore files 取消选中就OK了

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-W6mDrEpK-1634717834306)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20211019201144510.png)]

  • 又出现了个大无语问题

问题:源服务器未能找到目标资源的表示或者是不愿公开一个已经存在的资源表示、

问题解决:这个名字必须为 lib,写错了就会报资源找不到

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-13bIm6pK-1634717834311)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20211020154307519.png)]

使用注解开发springmvc程序

步骤:

  1. 导包,将项目配置成web项目,在artifact打包路径下创建lib目录,导入包
  2. 编写jsp文件
  3. 编写web.xml,在里面配置上DispatcherServlet
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.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>


</web-app>
  1. 编写springmvc-servlet.xml
  • 配置注解扫描的路径
  • 配置mvc的适配器mvc:annotation-driven
<?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.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--注解扫描包-->
    <context:component-scan base-package="com.xu.controller"/>
    <!--过滤静态资源-->
    <mvc:default-servlet-handler/>
    <mvc:annotation-driven/>

    <!--视图解析器:DispatcherServlet给他的ModelAndView-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!--后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>
  1. 直接使用注解开发Controller类
package com.xu.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
//代表这个类会被spring 接管
//并且加上这个之后这个类中的所有方法如果返回值为string,并且有具体页面可以跳转就会被视图解析器解析
public class MyController {

    @RequestMapping("/hello")
    public String controller1(Model model) {
        model.addAttribute("msg", "你好,注解开发springmvc");
        //返回路径
        return "hello";
    }
}
  1. 在controller类里面就可以直接配置好了路径映射@RequestMapping

Restful

  • url请求形式的变化
  1. 传统请求
//传统的url: http://localhost:8080/hello?a=1&b=2
@RequestMapping("/hello")
public String controller1(int a,int b,Model model) {
    int res = a+b;
    model.addAttribute("msg", "结果为:"+res);
    return "hello";
}
  1. RestFul风格的请求
    • 方式一:
//RestFul风格的url: http://localhost:8080/hello1/1/2
@GetMapping("/hello1/{a}/{b}")
public String controller2(@PathVariable int a,@PathVariable int b,Model model) {
    int res = a+b;
    model.addAttribute("msg", "结果1为:"+res);
    return "hello";
}

//RestFul风格的url: http://localhost:8080/hello1/1/2
@PostMapping("/hello1/{a}/{b}")
public String controller3(@PathVariable int a,@PathVariable int b,Model model) {
    int res = a+b;
    model.addAttribute("msg", "结果2为:"+res);
    return "hello";
}
@PutMapping("/hello1/{a}/{b}")
    public String controller2(@PathVariable int a,@PathVariable int b,Model model) {
        int res = a+b;
        model.addAttribute("msg", "结果1为:"+res);
        return "hello";
}
@DeleteMapping("/hello1/{a}/{b}")
    public String controller2(@PathVariable int a,@PathVariable int b,Model model) {
        int res = a+b;
        model.addAttribute("msg", "结果1为:"+res);
        return "hello";
}

​ -方式2:

//RestFul风格的url: http://localhost:8080/hello1/1/2
// @RequestMapping(path="/hello1/{a}/{b}",method = {RequestMethod.POST})
// @RequestMapping(path="/hello1/{a}/{b}",method = {RequestMethod.PUT})
// @RequestMapping(path="/hello1/{a}/{b}",method = {RequestMethod.DELETE})
@RequestMapping(path="/hello1/{a}/{b}",method = {RequestMethod.GET})
public String controller4(@PathVariable int a,@PathVariable int b,Model model) {
    int res = a+b;
    model.addAttribute("msg", "结果1为:"+res);
    return "hello";
}

接收前端请求的数据和回显数据

接收请求数据

  1. 请求数据为普通参数
    • 只页面请求过来的参数,不管和代码的方法里面的参数一致不一致,使用@RequestParam(“参数名”)
@RequestMapping("/test1")
//页面请求过来的参数和代码的参数 一致
// http://localhost:8080/test1?name=xpc
public String getRequest(String name, Model model) {
    model.addAttribute("msg", name);
    return "hello";
}
@RequestMapping("/test2")
//页面请求过来的参数和代码的参数 不一致 就需要用到@RequestParam
//http://localhost:8080/test2?username=xpc
public String getRequest1(@RequestParam("username") String name, Model model) {
    model.addAttribute("msg", name);
    return "hello";
}
  1. 请求过来的是一个对象的完整字段(并且字段名一致),可以直接用对象接收
//http://localhost:8080/test3?id=1&name=xpc&sex=男
//这里请求的参数名必须和user属性字段名一致才能用对象接收
@RequestMapping("/test3")
public String getRequest2(User user) {
    System.out.println(user);
    return "hello";
}

回显数据

  1. Model
public String getRequest(String name, Model model) {
    model.addAttribute("msg", name);
    return "hello";
}
  1. ModelView
public class servlet implements Controller {
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        //ModelAndView 模型和视图
        ModelAndView mv = new ModelAndView();

        //封装对象,放在ModelAndView中。Model
        mv.addObject("msg","HelloSpringMVC!");
        //封装要跳转的视图,放在ModelAndView中
        mv.setViewName("hello"); //: /WEB-INF/jsp/hello.jsp
        return mv;
    }
}

解决乱码问题(测试)

步骤:

  1. 写一个form表单
<form action="/encode" method="post">
        <input type="text" name="username">
        <input type="submit">
</form>
  1. 写对应的controller
@Controller
public class EncodingController {
    //此处因为form表单提交的是post方法,所以此处用的是PostMapping
    //当然RequestMapping是什么类型的提交方式都可以
    @PostMapping("/encode")
    public String enCoding(@RequestParam("username") String name, Model model) {
        model.addAttribute("msg", name);
        //重定向到hello.jsp展示数据
        return "hello";
    }
}
  1. 解决乱码问题—使用自定义Filter

    //编写filter类实现filter接口
    public class MyFilter implements Filter {
        public void init(FilterConfig filterConfig) throws ServletException {
    
        }
    
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            servletRequest.setCharacterEncoding("utf-8");
            servletResponse.setCharacterEncoding("utf-8");
    
            filterChain.doFilter(servletRequest,servletResponse);
        }
    
        public void destroy() {
    
        }
    }
    
    //在web.xml里面注册<filter>        <filter-name>encodingFilter</filter-name>        <filter-class>com.xu.Filter.MyFilter</filter-class></filter><filter-mapping>        <filter-name>encodingFilter</filter-name>        <!--注意此处写/*-->        <url-pattern>/*</url-pattern></filter-mapping>
    
  2. 解决乱码问题–使用mvc的过滤器

    • 直接在web.xml里面配置即可
    <filter>
       <filter-name>encoding</filter-name>
       <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
       <init-param>
           <param-name>encoding</param-name>
           <param-value>utf-8</param-value>
       </init-param>
    </filter>
    <filter-mapping>
       <filter-name>encoding</filter-name>
       <url-pattern>/*</url-pattern>
    </filter-mapping>
    

Json

  • 只是一种数据格式

  • 后端给前端返回数据,不可能直接返回对象,所以一般是返回json

  • 因为js可以直接解析json字符串为js对象,也可以将js对象转换成json字符串

测试:用Jackson工具包和fastJson工具包给网页返回一个json字符串

  1. 测试jackson
//导包
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.12.3</version>
</dependency>
//json乱码问题,在spring-servlet.xml里面加上如下配置即可解决
<mvc:annotation-driven>
   <mvc:message-converters register-defaults="true">
       <bean class="org.springframework.http.converter.StringHttpMessageConverter">
           <constructor-arg value="UTF-8"/>
       </bean>
       <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
           <property name="objectMapper">
               <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                   <property name="failOnEmptyBeans" value="false"/>
               </bean>
           </property>
       </bean>
   </mvc:message-converters>
</mvc:annotation-driven>
//用jackson返回json字符串代码

//@Controller 会走视图解析器,用于视图跳转
//@RestController 默认这个类下面的所有方法都只会返回字符串,真实开发中也是只需要写接口给前端返回json字符串
@RestController
public class TestJson {

    //返回一个普通对象
    @RequestMapping("/j1")
    public String json1() throws JsonProcessingException {

        System.out.println("-------------");
        User user = new User(1, 18, "许鹏程");
        return JsonUtils.getJson(user);
    }
    //返回集合
    @RequestMapping("/j2")
    public String json2() throws JsonProcessingException {
        User user1 = new User(1, 18, "许鹏程1");
        User user2 = new User(2, 16, "许鹏程2");
        User user3 = new User(3, 17, "许鹏程2");
        User user4 = new User(4, 18, "许鹏程4");

        List<User> list = new ArrayList<User>();
        list.add(user1);
        list.add(user2);
        list.add(user3);
        list.add(user4);
        return JsonUtils.getJson(list);
    }
    //返回一个日期,按照格式返回
    @RequestMapping("/j3")
    public String json3() throws JsonProcessingException {

        Date date = new Date();
        //因为jackson默认返回时间戳,要返回日期格式需要改代码,直接写个接口完成
        //方式一:
        return JsonUtils.getDateJson(date,"yyyy-MM-dd:HH-mm-ss");
    }
}
//JsonUtils工具类
import java.text.DateFormat;
import java.text.SimpleDateFormat;

public class JsonUtils {
    public static String getJson(Object object) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(object);
    }
    public static String getDateJson(Object object,String dateFormat) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        SimpleDateFormat format = new SimpleDateFormat(dateFormat);
        mapper.setDateFormat(format);
        return mapper.writeValueAsString(object);
    }
}
  1. 测试fastjson【不用写jackson工具类】
//简单,不用写工具类
@RestController
public class TestJson {

    //fastJson返回一个普通对象
    @RequestMapping("/j1")
    public String json1() throws JsonProcessingException {
        User user = new User(1, 18, "许鹏程");
        return JSON.toJSONString(user);
    }
    //fastJson返回集合
    @RequestMapping("/j2")
    public String json2() throws JsonProcessingException {
        User user1 = new User(1, 18, "许鹏程1");
        User user2 = new User(2, 16, "许鹏程2");
        User user3 = new User(3, 17, "许鹏程2");
        User user4 = new User(4, 18, "许鹏程4");

        List<User> list = new ArrayList<User>();
        list.add(user1);
        list.add(user2);
        list.add(user3);
        list.add(user4);
        return JSON.toJSONString(list);
    }
    //fastJson返回一个日期,按照格式返回
    @RequestMapping("/j3")
    public String json3() throws JsonProcessingException {

        Date date = new Date();

        return JSON.toJSONStringWithDateFormat(date, "yyyy-MM-dd:HH-mm-ss");

    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值