使用Spring表单在Spring

使用Spring表单在Spring

本文介绍了使用Spring表单在Spring MVC中无法上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个jsp页面,在其中使用了spring form标签,以便可以使用model属性并将数据绑定到它.提交表单时工作正常,但是在添加enctype="multipart/form-data"模型属性后,该属性对控制器重现了null.这是怎么了?我的代码是- proflie.jsp

I have a jsp page in which i have used spring form tag so that i can use model attribute and bind data to it. It was working fine on submit the form but after adding enctype="multipart/form-data" model attributes are returing null to the controller. What is wrong here ?My Code is -proflie.jsp

 <sf:form method="POST" action="update" modelAttribute="user" class="form-horizontal" >
    <div class="form-group">
        <label for="inputEmail3" class="col-sm-2 control-label">Avatar</label>
        <div class="col-md-6">
            <div class="media v-middle">
                <div class="media-left">
                    <div class="icon-block width-100 bg-grey-100">
                        <i class="fa fa-photo text-light"></i>
                    </div>
                </div>
                <div class="media-body">
                    <i class="fa fa-upl"><sf:input path="imageFile" type="file" class="btn btn-white btn-sm paper-shadow relative" placeholder="Add Image" id="imageFile" />
                     </i>
                </div>
            </div>
        </div>
    </div>
    <div class="form-group">
        <label for="inputEmail3" class="col-md-2 control-label">Full Name</label>
        <div class="col-md-8">
            <div class="row">
                <div class="col-md-6">
                    <div class="form-control-material">
                        <sf:input path="firstName" type="text" class="form-control" id="firstName" placeholder="Your first name" value="${user.firstName}" />
                        <sf:input path="id" type="hidden" class="form-control" id="id" value="${user.id}" />
                        <label for="firstName">First name</label>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-control-material">
                            <sf:input path="lastName" class="form-control" id="lastName" placeholder="Your last name" value="${user.lastName}" />
                        <label for="lastName">Last name</label>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="form-group">
        <label for="inputEmail3" class="col-md-2 control-label">Email</label>
        <div class="col-md-6">
            <div class="form-control-material">
                <div class="input-group">
                    <span class="input-group-addon"><i class="fa fa-envelope"></i></span>
                    <sf:input path="email" type="email" class="form-control" id="inputEmail3" placeholder="Email" value="${user.email}" />
                    <label for="inputEmail3">Email address</label>
                </div>
            </div>
        </div>
    </div>
     <div class="form-group">
        <label for="inputEmail3" class="col-md-2 control-label">Phone</label>
        <div class="col-md-6">
            <div class="form-control-material">
                <div class="input-group">
                    <span class="input-group-addon"><i class="fa fa-envelope"></i></span>
                    <sf:input path="phone" type="number" class="form-control" id="inputEmail3" placeholder="Phone" value="${user.phone}" />
                    <label for="phone">Phone</label>
                </div>
            </div>
        </div>
    </div>
    <div class="form-group">
        <label for="inputEmail3" class="col-md-2 control-label">Address</label>
        <div class="col-md-6">
            <div class="form-control-material">
                <div class="input-group">
                    <span class="input-group-addon"><i class="fa fa-link"></i></span>
                    <sf:input path="address" type="text" class="form-control used" id="website" placeholder="Address" value="${user.address}" />
                    <label for="address">Address</label>
                </div>
            </div>
        </div>
    </div>
    <div class="form-group">
        <label for="inputPassword3" class="col-md-2 control-label">Change Password</label>
        <div class="col-md-6">
            <div class="form-control-material">
               <sf:input path="password" type="password" class="form-control" id="inputPassword3" placeholder="Password" value="${user.password}" />
                <label for="password">Password</label>
            </div>
        </div>
    </div>

    <div class="form-group margin-none">
        <div class="col-md-offset-2 col-md-10">
            <button type="submit" class="btn btn-primary paper-shadow relative" data-z="0.5" data-hover-z="1" data-animated>Save Changes</button>
        </div>
    </div>
</sf:form>

AccountController类

package com.vc.teacher.controller;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.vc.teacher.db.dao.UserDao;
import com.vc.teacher.entities.User;
import com.vc.teacher.util.Constants;

@Controller
public class AccountController {

    @Autowired
    UserDao userDao;

    @RequestMapping("/login")
    public String loginUser(@RequestParam("email") String email,
            @RequestParam("password") String password, Model model) {

        User user = userDao.checkCreditionals(email, password);
        if (user != null) {
            model.addAttribute("user", user);
            return "jsp/profile";
        } else {
            model.addAttribute("error", "Wrong creditionals");
            return "jsp/signin";
        }

    }

    @RequestMapping("/signUp")
    public String initilize(Model model) {
        model.addAttribute(new User());
        return "jsp/signup";
    }

    @RequestMapping(method = RequestMethod.POST, value = "/register")
    public String signUpUser(User user, RedirectAttributes attributes) {
        boolean result = false;
        File imageFile = null;

        try {
            imageFile = user.getImageFile();

            if (imageFile != null) {
                File imageFileSave = new File(Constants.MEDIA_FILE_PATH);
                FileUtils.copyFile(imageFile, imageFileSave);
                user.setImageFileName(imageFile.getName());
            }

            user.setStatus("Deactive");
            result = userDao.registerUser(user);

            if (result == true) {
                attributes.addFlashAttribute("message",
                        "You are ready to go now !");
                return "redirect:/signUp";
            } else {
                attributes.addFlashAttribute("message", "Something went wrong");
                return "redirect:/signUp";
            }

        } catch (Exception e) {
            attributes.addFlashAttribute("message", "Something went wrong");
            return "redirect:/signUp";
        }

    }

    @RequestMapping(method = RequestMethod.POST, value = "/update")
    public String updateUser(User user, RedirectAttributes attributes) {
        boolean result = false;
        File imageFile = null;

        try {
            System.out.println("=================================="+user.getEmail());
            System.out.println("=================================="+user.getId());
            System.out.println("=================================="+user.getFirstName());

            imageFile = user.getImageFile();

            if (imageFile != null) {
                File imageFileSave = new File(Constants.MEDIA_FILE_PATH);
                FileUtils.copyFile(imageFile, imageFileSave);
                user.setImageFileName(imageFile.getName());
            }

            user.setStatus("Active");
            result = userDao.updateUser(user);

            if (result == true) {
                attributes.addFlashAttribute("message", "Profile Updated !");
                return "jsp/profile";
            } else {
                attributes.addFlashAttribute("message", "Something went wrong");
                return "jsp/profile";
            }
        } catch (Exception e) {
            attributes.addFlashAttribute("message", "Something went wrong");
            return "jsp/profile";
        }

    }
}

推荐答案

DispatcherServlet本身不知道如何处理多部分表单数据.这就是为什么我们需要多部分解析器.

On its own, DispatcherServlet doesn't know how to handle multipart form data; that's why we require multipart resolver.

您应该在servlet-config中注册它:

You should register it in your servlet-config:

    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="500000" />
    </bean>

在您的User对象中使用CommonsMultipartFile或MultipartFile代替File:

Use CommonsMultipartFile or MultipartFile instead of File in your User object:

private CommonsMultipartFile imageFile;

您可以尝试以下代码来保存文件:

You can try this code to save file:

File imageFileSave = new File(Constants.MEDIA_FILE_PATH);
FileUtils.writeByteArrayToFile(imageFileSave , imageFile.getBytes());

这篇关于使用Spring表单在Spring MVC中无法上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 03:50