在JavaWeb中我们用的是request.getParam()来获取前端传递的参数。
而在SpringMVC中接收来自前端传递的参数名,如果有在对应的路由方法中的形参设置相同名称的参数,则匹配成功直接使用。
如果传入的是个实例化对象则去匹配该实例化对象的字段名(属性)如果一致也可以直接使用,如果某一项没匹配到则会使用该属性的默认值。
在SpringMVC中有以下几种获取前端传递的参数的方式:
当前端传递来的参数名与我们在controller定义的参数名一致时,可直接获取
@RequestMapping("/m1/t4") public String sayTest4(String name, Model model){ model.addAttribute("msg", name); return "test"; }
当前端传递来的参数名与我们在controller定义的参数名不一致时
可通过注解@RequestParam处理,类似于Alias起别名
@RequestMapping("/m1/t5") public String sayTest4(@RequestParam("username") String name, Model model){ model.addAttribute("msg", name); return "test"; }
也可以获取一个实例化对象
User
@Data @AllArgsConstructor @NoArgsConstructor public class User { private int id; private String name; private int age; }
Controller
@GetMapping("/m1/t5") public String sayTest5(User user, Model model){ System.out.println(user); model.addAttribute("msg", user); return "test"; }
通过ModelAndView
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { //ModelAndView 模型和视图 ModelAndView mv = new ModelAndView(); //封装对象,放在ModelAndView中。Model mv.addObject("msg","HelloSpringMVC!"); //封装要跳转的视图,放在ModelAndView中 mv.setViewName("hello"); return mv; }
通过Model
public String sayTest5(User user, Model model){ System.out.println(user); model.addAttribute("msg", user); return "test"; }
通过ModelMap
public String sayTest5(User user, ModelMap map){ System.out.println(user); map.addAttribute("msg", user); return "test"; }
其实ModelMap与Model使用起来没什么区别,只是继承关系和方法上有些区别,ModelMap直接继承自LinkedHashMap而Model是继承自ModelMap,所以ModelMap的功能更多些,但是平常更多还是会用Model去存储回显数据。而ModelAndView一般用在实现Controller接口时才会用它去做数据的存储处理和视图转发等。
JSON(JavaScript Object Notation,JS对象标记)是一种轻量级的数据交换格式。
整个格式大致为:对象表示为健值对,花括号保存对象,中括号保存数组,数据之间用逗号分隔。
JSON是JavaScript对象的字符串表示法,使用字符串保存一个JS对象的信息,而JS对象也可以转换成JSON字符串格式。
比如在JS中可以如下实现JS对象与JSON字符串之间的互相转换
<script type="text/javascript"> //编写一个对象 var user = { name:"CoLoo", age:18, area:"BeiJing" } //将js对象转换为Json var json = JSON.stringify(user); console.log(json); console.log("===========================") //将json转换为js对象 var object = JSON.parse(json); console.log(object); </script>
Pom.xml,导入依赖
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.10.0</version> </dependency>
web.xml,配置DispatcherServlet和Filter
<?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"> <!--1.注册DispatcherServlet--> <servlet> <servlet-name>springmvc</servlet-name> <!-- SpringMVC写好的DispatcherServlet--> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--关联一个springmvc的配置文件:【servlet-name】-servlet.xml--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-servlet.xml</param-value> </init-param> <!--启动级别-1--> <load-on-startup>1</load-on-startup> </servlet> <!--/ 匹配所有的请求;(不包括.jsp)--> <!--/* 匹配所有的请求;(包括.jsp)--> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <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> </web-app>
Springmvc-config.xml,SpringMVC配置文件
<?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"> <!-- 自动扫描包,让指定包下的注解生效,由IOC容器统一管理 --> <context:component-scan base-package="com.zh1z3ven.controller"/> <!-- 视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <!-- 前缀 --> <property name="prefix" value="/WEB-INF/jsp/" /> <!-- 后缀 --> <property name="suffix" value=".jsp" /> </bean> </beans>
新建Controller包、pojo包及User类、WEB-INF/jsp目录
pojo.User
@Data @NoArgsConstructor @AllArgsConstructor public class User { private String name; private int age; private String sex; }
使用Jackson将User对象转换为JSON字符串返回给前端
@ResponseBody注解不会让该方法走视图解析器而是直接返回一个字符串(配合@Controller使用)
如果使用@RestController则不需要在方法上添加@ResponseBody注解
Jackson中有一个ObjectMapper对象,可以使用它将对象转换为json字符串
示例:普通对象转json字符串
@Controller public class JsonController { @RequestMapping("/j1") @ResponseBody //不走视图解析器而是直接返回一个字符串 public String json1() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); User user = new User("zh1z3ven", 18, "boy"); String str = objectMapper.writeValueAsString(user); return str; } }
解决JSON乱码配置
<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>
示例:集合对象转json字符串
@RequestMapping("/j2") public String json2() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); List<User> userList = new ArrayList<User>(); //创建一个对象 User user1 = new User("zh1z3ven1", 18, "boy"); User user2 = new User("zh1z3ven2", 18, "boy"); User user3 = new User("zh1z3ven3", 18, "boy"); User user4 = new User("zh1z3ven4", 18, "boy"); userList.add(user1); userList.add(user2); userList.add(user3); userList.add(user4); String str = objectMapper.writeValueAsString(userList); return str; }
示例:时间戳Json
@RequestMapping("/j3") public String json3() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String str = objectMapper.writeValueAsString(sdf.format(date)); return str; }
JsonUtils
这里注意第一个重载方法,写的时候直接return第二个方法就行,不用再一行一行的造轮子。(太妙了,这就是Java的魅力吧[doge:手动狗头])。多构思整个代码的逻辑和框架,挑出重复写好多次的部分,写成utils类去降藕。
public class JsonUtil { public static String getJson(Object o){ return getJson(o,"yyyy-MM-dd HH:mm:ss"); } public static String getJson(Object o, String dateFormat){ ObjectMapper mapper = new ObjectMapper(); //不使用时间戳的方式 mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); mapper.setDateFormat(sdf); try { return mapper.writeValueAsString(o); } catch (JsonProcessingException e) { e.printStackTrace(); } return null; } }
fastjon中主要有3个类
JSONObject:代表JSON对象
JSONArray:代表JSON对象数组
JSON:代表JSONObject和JSONArray转化
示例
@RequestMapping("/j4") public String json4() throws JsonProcessingException { List<User> userList = new ArrayList<User>(); User user1 = new User("zh1z3ven1", 18, "boy"); User user2 = new User("zh1z3ven2", 18, "boy"); User user3 = new User("zh1z3ven3", 18, "boy"); User user4 = new User("zh1z3ven4", 18, "boy"); userList.add(user1); userList.add(user2); userList.add(user3); userList.add(user4); String str = JSON.toJSONString(userList); return str; }