Spring笔记(3):SpringMVC数据响应与接收含文件上传

SpringMVC数据返回可以是页面跳转也可以是数据对象

页面跳转:返回字符串,会与视图服务器设定的前后缀拼接返回给客户端定位资源

上节代码中没有配置视图服务器
在配置Controller类的RequestMapping后,需要注意会偷偷在前面再添加该RequestMapping的路由

页面跳转:ModelAndView对象
package com.CakeCN.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.xml.ws.RequestWrapper;

@Controller
public class UserController {

    @RequestMapping(value="/save2",method = {RequestMethod.GET, RequestMethod.POST}, params = {"username"})
    public ModelAndView save2(){
        /*
            Model   模型,封装数据
            View    视图,展示数据
         */
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("success.jsp");
        return modelAndView;
    }


    @RequestMapping("/save")
    public String save(){
        System.out.println("Controller save running...");
        return "success.jsp";
    }
}

访问路由要注意格式正确
Spring笔记(3):SpringMVC数据响应与接收含文件上传_第1张图片

设置页面视图中的数据 格式: ${username}
        modelAndView.addObject("username","CakeCN");
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Success!!title>
head>
<body>
    <h1>HelloWorld ${username}h1>
body>
html>
值得一提的模型、视图分别设定,也是可以成功的

model用于设定数据

    @RequestMapping("/save3")
    public String save3(Model model){
        model.addAttribute("username","CakeCN");
        return "success.jsp";
    }

Spring笔记(3):SpringMVC数据响应与接收含文件上传_第2张图片

数据返回
通过框架为处理方法切片注入需要的数据,从底层做这些事情
    @RequestMapping("/save3")
    public String save3(Model model, HttpServletRequest req, HttpServletResponse resp){
        model.addAttribute("username","CakeCN");
        return "success.jsp";
    }
通过注解告诉MVC,本处理方法不进行页面跳转,直接是数据写回
    @RequestMapping("/save3")
    @ResponseBody
    public String save3(){
        return "Hello World";
    }
正常情况下显然返回json格式的字符串,用第三方库帮助实现json转换

pom.xml

		<dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-coreartifactId>
            <version>2.9.0version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-databindartifactId>
            <version>2.9.0version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-annotationsartifactId>
            <version>2.9.0version>
        dependency>
	class tempStruct{
        public String username;
        public int age;

        public void setAge(int age) {
            this.age = age;
        }

        public void setUsername(String username) {
            this.username = username;
        }
    }
    @RequestMapping("/save4")
    @ResponseBody
    public String save4() throws Exception {
        tempStruct tmp = new tempStruct();
        tmp.setAge(18);
        tmp.setUsername("CakeCN");

        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(tmp);
    }
可以通过配置SpinrgMVC 简化json字符串转化的过程

Spring-mvc.xml

    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
            list>
        property>
    bean>

此时直接返回对象,就能帮忙转化为json格式

    @RequestMapping("/save5")
    @ResponseBody
    public tempStruct save5(){
        tempStruct tmp = new tempStruct();
        tmp.setAge(18);
        tmp.setUsername("CakeCN");
        return tmp;
    }
上述Spring-mvc的配置代码还是比较麻烦,可以添加mvc的命名空间后直接用mvc注解驱动底层默认自带json字符串转化功能

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="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.xsd
                        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">


    <context:component-scan base-package="com.CakeCN.controller"/>

    <mvc:annotation-driven/>
beans>

SpringMVC数据接收

Get方法中,直接在Controller方法的参数列表添加参数信息:
    @RequestMapping("/save5")
    @ResponseBody
    public tempStruct save5(String username, int age){
        tempStruct tmp = new tempStruct();
        tmp.setAge(age);
        tmp.setUsername(username);
        return tmp;
    }

在这里插入图片描述

也可以自动封装成参数对应的对象实体
    @RequestMapping("/save5")
    @ResponseBody
    public tempStruct save5(tempStruct tmp){
        return tmp;
    }

自定义数据转换

对于自定义格式的字符串,可以通过自定义数据转换器转换为相应的对象

定义转化器实体类,实现转换器Converter接口,并声明出转换器数据前后的类型

package com.CakeCN.converter;

import org.springframework.core.convert.converter.Converter;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateConverter implements Converter<String, Date> {

    public Date convert(String s) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = format.parse(s);
        } catch (Exception e){
            e.printStackTrace();
        }
        return date;
    }
}

Spring-mvc.xml中配置转换器服务工厂并在注解驱动中引用



    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <list>
                <bean class="com.CakeCN.converter.DateConverter"/>
            list>
        property>
    bean>
       <mvc:annotation-driven conversion-service="conversionService"/>

MVC文件上传

pom.xml导包

        <dependency>
            <groupId>commons-fileuploadgroupId>
            <artifactId>commons-fileuploadartifactId>
            <version>1.2.2version>
        dependency>
        <dependency>
            <groupId>commons-iogroupId>
            <artifactId>commons-ioartifactId>
            <version>2.4version>
        dependency>

Spring-mvc.xml配置


    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="5242800"/>
        <property name="maxUploadSizePerFile" value="5242800"/>
        <property name="defaultEncoding" value="UTF-8"/>
    bean>

文件接收控制器,注意其中MultipartFile的参数名字要与前端页面表单中的文件名字一致

    @RequestMapping("/save6")
    @ResponseBody
    public void save6(String name, MultipartFile uploadFile) throws Exception{
        String filename = uploadFile.getOriginalFilename();
        uploadFile.transferTo(new File("H:\\test\\"+filename));
    }

前端页面表单如此:

<body>
    <form action="${pageContext.request.contextPath}/save6" method="post" enctype="multipart/form-data">
        <label>名称:<input type="text" name="username"/>label>
        <label>文件:<input type="file" name="uploadFile"/>label>
        <label><input type="submit" value="提交"/>label>

    form>
body>

之后可以在对应文件夹下找到文件

MVC开启静态资源访问

    <mvc:resources mapping="/js/**" location="/js/"/>
    <mvc:resources mapping="/img/**" location="/img"/>

全局Filter解决中文乱码


    <filter>
        <filter-name>CharacterEncodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>UTF-8param-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

你可能感兴趣的:(Spring学习笔记,spring,java,mvc)