• SpringMVC 学习笔记(四)


    41. 尚硅谷_佟刚_SpringMVC_返回JSON.avi

    SpringMVC中使用@ResponseBody注解标注业务方法,将业务方法的返回值做成json输出给页面

    导包:

    除了一些spring的包之外,还需要jackson-annotations.jar , jackson-core.jar , jackson-databind.jar 这三个包

    开启@ResponseBody注解:

    在 spring-mvc.xml 中通过<mvc:annotation-driven />开启@ResponseBody注解

    使用@ResponseBody标注业务方法

    package com.loger.controller;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import com.loger.entity.User;
    
    /**
     * ResponseBody 注解,可以将如下类型的数据做成json:
     * 1)基本数据类型,如 boolean , String , int 等
     * 2) Map 类型数据
     * 3)集合或数组
     * 4)实体对象
     * 5)实体对象集合
     *
     */
    
    @Controller
    @RequestMapping("/test")
    public class JsonController {
    
        @RequestMapping("test1.do")
        @ResponseBody
        public boolean test1(){
            return true;
        }
        
        @RequestMapping("/test2.do")
        @ResponseBody
        public Map<String, Object> test2(){
            Map<String , Object> map = new HashMap<String ,Object>();
            map.put("id", "s20070");
            map.put("name", "郑城斌");
            return map;
        }
        
        @RequestMapping("/test3.do")
        @ResponseBody
        public List<String> test3(){
            List<String> list = new ArrayList<>();
            list.add("aaa");
            list.add("bbb");
            list.add("ccc");
            return list;
        }
        
        @RequestMapping("/test4.do")
        @ResponseBody
        public User test4(){
            User user = new User();
            user.setId("s20068");
            user.setName("余清波");
            user.setAge(21);
            return user;
        }
        
        @RequestMapping("/test5.do")
        @ResponseBody
        public List<User> test5(){
            List<User> list = new ArrayList<>();
            
            User user1 = new User();
            user1.setId("s200681");
            user1.setName("余清波1");
            user1.setAge(21);
            list.add(user1);
            
            User user2 = new User();
            user2.setId("s200682");
            user2.setName("余清波2");
            user2.setAge(21);
            list.add(user2);
            
            User user3 = new User();
            user3.setId("s200683");
            user3.setName("余清波3");
            user3.setAge(21);
            list.add(user3);
            
            return list;
        }
    }

    输出结果:

    @reponseBoby内部使用了httpMessageconvert对象

    42. 尚硅谷_佟刚_SpringMVC_HttpMessageConverter原理.avi

     43. 尚硅谷_佟刚_SpringMVC_使用HttpMessageConverter实现文件下载

    需求:

    点击页面上的超链接,然后下载服务器端的文件:

    <a href="testResponseEntity" id="testJson">Test 下载</a>

    需要传入3个参数,分别是:请求体、请求头和状态码

    handler层具体的代码如下:

     @RequestMapping("/testResponseEntity")
            public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {
                byte[] body=null;
                ServletContext sc=session.getServletContext();
                InputStream in=sc.getResourceAsStream("/files/test3");
                body=new byte[in.available()];
                in.read(body);
    
                HttpHeaders headers=new HttpHeaders();
                headers.add("Content-Disposition","attachment;filename=test3.txt");
    
                HttpStatus statusCode=HttpStatus.OK;
    
                ResponseEntity<byte[]> response=new ResponseEntity<byte[]>(body,headers,statusCode);
                return response;
            }
        

    整个项目工程的代码如下所示:

     

     44. 尚硅谷_佟刚_SpringMVC_国际化_概述.avi

    第一步:

    在src目录下建立下面三个文件

    message_en_US.properties

    message.username=username

    message_zh_CN.properties

    message.username=u7528u6237u540D

    message.properties

    message.username=username

    上面名字以啥开头message_en_US.properties都是以message开头的,对于的文件内容都以message开头

    接下来在spring-mvc中配置

    <?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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
        <!-- 配置自动扫描包  扫描com.ibigsea.springmvc 包下的类,后期会使用spring进行管理 -->
        <context:component-scan base-package="com.wst.springmvc.handlers"/>
    <!-- 配置视图解析器 如返回helloworld     
                             为 [/WEB-INF/pages/helloworld.jsp] -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
         <!-- 前缀 -->
            <property name="prefix" value="/WEB-INF/pages/"/>
             <!-- 后缀 -->
            <property name="suffix" value=".jsp"/>
        </bean>
        
            <!-- 配置国际化资源文件 -->
        <bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource">
                <property name="basename" value="message"></property>  
        </bean>
        <mvc:annotation-driven></mvc:annotation-driven>
    </beans>
    上面中
    <property name="basename" value="message"></property>  对于的就是文件开头的名字
    并且需要配置mvc:annotation-driven></mvc:annotation-driven>
    <context:component-scan配置扫描对于的handle文件,因为handle使用@Control自动标签进行扫描
    web.xml为
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        version="3.0" >
            <filter>
                <filter-name>HiddenHttpMethodFilter</filter-name>
                <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
            </filter>
            
            <filter-mapping>
                <filter-name>HiddenHttpMethodFilter</filter-name>
                <url-pattern>/*</url-pattern>
            </filter-mapping>
        <servlet>
            <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <!-- 加载spirng配置文件 -->
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:spring-mvc.xml</param-value>
            </init-param>
            <!-- 启动就加载 -->
            <load-on-startup>1</load-on-startup>
        </servlet>
    
        <!-- 拦截所有请求 -->
        <servlet-mapping>
            <servlet-name>springDispatcherServlet</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
          <!-- 避免中文乱码 -->
      <filter>  
            <filter-name>characterEncodingFilter</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>  
            <init-param>  
                <param-name>forceEncoding</param-name>  
                <param-value>true</param-value>  
            </init-param>  
        </filter>  
        <filter-mapping>  
            <filter-name>characterEncodingFilter</filter-name>  
            <url-pattern>/*</url-pattern>  
        </filter-mapping> 
    </web-app>
    接下来在jsp页面就可以使用国际化资源文件了
    使用标签
    <fmt:message key="message.username"></fmt:message>

    需要在jsp页面中引入springmc的标签

      <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

    hello.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
        <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    <fmt:message key="message.username"></fmt:message>
        <br><br>
    
        
    </body>
    </html>

     index.jsp

    <%@ 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 'index.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>
        This is my JSP page0000. <br>
        <a href="abc">测试</a>
      </body>
    </html>

    除了在jsp页面可以得到对于的

    message.username"值之外,我们也可以在handler控制层中获得message.username"对应的值,对于的handle层的代码为
    package com.wst.springmvc.handlers;
    
    import java.util.Locale;
    import java.util.ResourceBundle;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.support.ResourceBundleMessageSource;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    public class HelloHandler {
    
        @Autowired
        ResourceBundleMessageSource reBundleMessageSource;
        
        @RequestMapping(value="/abc")
        public String testLocal(Locale local ){
            String message = reBundleMessageSource.getMessage("message.username", null,local);
            System.out.println(message);
            return "hello";
        }
    }
    index.jsp

    我们运行看下效果

    在英文浏览器下啊

     在中文浏览器下

    整个代码的下载路径为:

     https://pan.baidu.com/s/1D_AbtPvPhO6APS3IkhKjvg

    46. 尚硅谷_佟刚_SpringMVC_国际化_通过超链接切换Locale.avi

    在上一节的课程中,我们是通过切换浏览器的语言来得到国际话的显示,现在我们想到达下面的这种效果

     通过超链接的形式来实现语言的切换,点击中文的时候显示中文,点击英文的时候显示英文,如何实现了,具体可以参考博客

    https://blog.csdn.net/hj7jay/article/details/51383248

    相当的经典

    我们来看整个项目的目录结构如下所示

    首先在src目录下建立下面三个文件

    message_en_US.properties

    message.username=username

    message_zh_CN.properties

    message.username=u7528u6237u540D

    message.properties

    message.username=username

    这里需要注意的是

    message.username中的第一个值必须和message.properties名字是一一对应的二者都是message

    接下来在spring-mvc.xml中配置国际化资源文件

    <?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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
        <!-- 配置自动扫描包  扫描com.ibigsea.springmvc 包下的类,后期会使用spring进行管理 -->
        <context:component-scan base-package="com.ibigsea.springmvc"/>
    <!-- 配置视图解析器 如返回helloworld     
                             为 [/WEB-INF/pages/helloworld.jsp] -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
         <!-- 前缀 -->
            <property name="prefix" value="/WEB-INF/pages/"/>
             <!-- 后缀 -->
            <property name="suffix" value=".jsp"/>
        </bean>
        
        <!--将自定义的转换器加入到框架中-->
           <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
                  <property name="converters">
                         <set>
                                <bean class="com.ibigsea.springmvc.handler.EmployeeConverts"/>
                         </set>
                  </property>
           </bean>
           
             <!-- 视图相关配置 -->
        <bean
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/pages/" />  <!-- 视图前缀 -->
            <property name="suffix" value=".jsp" />  <!-- 视图后缀 -->
        </bean>
        <!-- 存储区域设置信息 -->
        <bean id="localeResolver"
            class="org.springframework.web.servlet.i18n.SessionLocaleResolver" />
        <!-- 国际化资源文件 -->
        <bean id="messageSource"
            class="org.springframework.context.support.ResourceBundleMessageSource">
            <property name="basename" value="message" />
        </bean>
     
        <mvc:interceptors>
            <bean id="localeChangeInterceptor"
                class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
                <property name="paramName" value="lang" />
            </bean>
        </mvc:interceptors>
        <!-- 配置运行可以访问静态资源文化 -->
        <mvc:default-servlet-handler/>
        <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
        
    
    </beans>
    配置三个参数InternalResourceViewResolver 、ResourceBundleMessageSource、LocaleChangeInterceptor和<mvc:annotation-driven
    接下来是handle控制层代码
    package com.ibigsea.springmvc.handler;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    public class GuojihuaHandler {
    
        @RequestMapping("/testGuojihua")
        public String testGuojihua(){
            return "sucess";
        }
    }
    
    
    
    我们要在sucess.jsp中得到国际化的值
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
     <%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
     <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 
    <%@taglib prefix="spring" uri="http://www.springframework.org/tags" %>
    <%
    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 'index.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>
      sucess.jsp页面  
      <spring:message code="message.username" /> 
      Locale: ${pageContext.response.locale }
       
      </body>
    </html>
    
    
    
    这里使用了spring标签,需要添加
    <%@taglib prefix="spring" uri="http://www.springframework.org/tags" %>

    在index.jsp中访问
    <%@ 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 'index.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>
        <a href="testGuojihua?lang=zh_CN">中文</a> <br>
        <a href="testGuojihua?lang=en_US">英文</a> <br>
        
       
       
      </body>
    </html>
    
    
    
    我们来看下运行的效果
    点击中文的时候显示

     

     点击英文的时候显示

    整个代码的下载目录是

    https://pan.baidu.com/s/1Whpg447aY79Mz9YiDM1f1w

  • 相关阅读:
    使用NHibernate(1)--资料汇总
    mono上部署web程序初体验
    一次简单的ORM调研
    【设计模式】02-评判代码质量的标准?如何写出高质量代码?
    【设计模式】01-初识设计模式
    【ARTS】004-第四周(2020.06.15-2020.06.21)
    【leetcode】14-Longest Common Prefix
    【ARTS】003-第三周(2020.06.08-2020.06.14)
    【行成于思】04-读《如何超过大多数人》有感
    【leetcode】009-Palindrome Number
  • 原文地址:https://www.cnblogs.com/kebibuluan/p/8864203.html
Copyright © 2020-2023  润新知