SpringMvc自定义消息转换器

xiaoxiao2021-02-27  160

SpringMvc配置文件代码

对于定义的消息转换器 必须通过 mvc:annotation-driven进行注册 消息转换器  会对请求的mini类型进行匹配 如果无法匹配 不会进行消息转换

[html]  view plain  copy <?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:p="http://www.springframework.org/schema/p"       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-3.0.xsd       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd       ">       <!-- 配置扫描 -->       <context:component-scan base-package="cn.et"></context:component-scan>      <!--配置自己定义的消息转换器 -->      <mvc:annotation-driven>           <mvc:message-converters>               <bean id="myMessageConventor" class="cn.et.day20170601.MyMessageConventor">                   <property name="supportedMediaTypes">                       <list>                       <!--                       设置响应的支持的响应类型                           -->                           <value>text/html;charset=utf-8</value>                           <!-- 设置请求body的支持类型-->                           <value>application/x-www-form-urlencoded</value>                       </list>                   </property>               </bean>           </mvc:message-converters>      </mvc:annotation-driven>   </beans>  

定义一个消息转换器处理类,该类必须继承AbstractHttpMessageConverter<?>

action代码

[java]  view plain  copy public class MyMessageConventor extends AbstractHttpMessageConverter<Phone>{       /**       *解析请求的参数       */       @Override       protected Phone readInternal(Class arg0, HttpInputMessage httpInputMessage)               throws IOException, HttpMessageNotReadableException {            InputStream is=httpInputMessage.getBody();            BufferedReader br=new BufferedReader(new InputStreamReader(is));            String str=br.readLine();            String string=str.split("=")[1];            Phone phone=new Phone();            phone.setCode(string.split("-")[0]);            phone.setNumber(string.split("-")[1]);           return phone;       }       /**       * 如果支持 true支持  会调用 readInternal 将http消息 转换成方法中被@RequestBody注解的参数       *         会调用writeInternal 将被@ResponseBody注解的返回对象转换成数据字节响应给浏览器       */       @Override       protected boolean supports(Class arg0) {           if(arg0==Phone.class){               return true;           }           return false;       }       /**       * 响应给对象的参数       * 将方法被@ResponseBody注解的返回对象转换成数据字节响应给浏览器       */       @Override       protected void writeInternal(Phone phone, HttpOutputMessage httpOutputMessage)               throws IOException, HttpMessageNotWritableException {               OutputStream os=httpOutputMessage.getBody();               String str=phone.getCode()+"-"+phone.getNumber();               os.write(str.getBytes());       }      }  

Action类的需要用到@RequestBody和@ResponseBody注解关联到MyMessageConvertor

[java]  view plain  copy @Controller   @RequestMapping(value="/day0601")   public class MyMessageAction {       @RequestMapping(value="/myMessage.action")       //告诉他响应的内容       @ResponseBody       //用@RequestBody这个接收自定义的请求体消息       public Phone myMessage(@RequestBody Phone phone){           System.out.println(phone.getCode()+"-"+phone.getNumber());           return phone;       }   }  

编写jsp文件跳转的动作只能是form表单,并且添加属性enctype="application/x-www-form-urlencoded" 必需要是post提交

jsp代码

[html]  view plain  copy <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>   <%   String path = request.getContextPath();   String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";   %>      <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">   <html>     <head>       <base href="<%=basePath%>">              <title>My JSP 'phone.jsp' starting page</title>              <meta http-equiv="pragma" content="no-cache">       <meta http-equiv="cache-control" content="no-cache">       <meta http-equiv="expires" content="0">           <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">       <meta http-equiv="description" content="This is my page">       <!--      <link rel="stylesheet" type="text/css" href="styles.css">      -->        </head>          <body>        <form action="${pageContext.request.contextPath}/day0601/myMessage.action" method="post" enctype="application/x-www-form-urlencoded">           <input type="hidden" name="phone" value="0755-123456"/>           <input type="submit" value="提交"/>       </form>     </body>   </html>  

web.xml配置

[html]  view plain  copy <?xml version="1.0" encoding="UTF-8"?>   <web-app version="2.5"        xmlns="http://java.sun.com/xml/ns/javaee"        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">       <!-- spring自带的解决乱码的过滤器 -->           <filter>           <filter-name>utf</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>utf</filter-name>           <url-pattern>/*</url-pattern>       </filter-mapping>       <filter>       <!-- 配置这个selevlet来加载sprinmvc的配置文件 -->       <filter-name>hidden</filter-name>       <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>     </filter>         <filter-mapping>       <filter-name>hidden</filter-name>       <url-pattern>/*</url-pattern>     </filter-mapping>       <servlet>           <servlet-name>springmvc</servlet-name>           <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>           <!-- 通过这个参数去找配置文件 不加这个参数默认在 /WEB-INF/找spservlet-name-servlet.xml这个文件-->           <init-param>               <param-name>contextConfigLocation</param-name>               <param-value>classpath:/springmvc.xml</param-value>           </init-param>           <!-- 启动tomcat的时候就加载 -->           <load-on-startup>0</load-on-startup>       </servlet>       <servlet-mapping>           <servlet-name>springmvc</servlet-name>           <!-- /拦截所有以.action -->           <url-pattern>*.action</url-pattern>           <!-- /拦截所有servlet -->           <url-pattern>/</url-pattern>       </servlet-mapping>     <welcome-file-list>       <welcome-file>index.jsp</welcome-file>     </welcome-file-list>   </web-app> 
转载请注明原文地址: https://www.6miu.com/read-14327.html

最新回复(0)