1

Получаю данную ошибку только при передаче данных модели image. остальные работают и отправляются нормально, возможно дело в том что в этой модели используется Blob и Multipart. Используется hibernate.

Controller

    package com.bascon;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Blob;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletContext;

import org.hibernate.Hibernate;
import org.jboss.logging.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.support.PagedListHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
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.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.dao.comment.CommentService;
import com.dao.comment.CommentServiceImpl;
import com.dao.episode.EpisodeServiceImpl;
import com.dao.image.ImageServiceImpl;
import com.model.Comment;
import com.model.Episode;
import com.model.Image;
import com.validation.EpisodeValidation;

@Controller
public class HelloController {

    @Autowired
    ServletContext context;

    @Autowired
    EpisodeValidation epsiodeValidator;

    //Три сервиса для работы с базой данных
    CommentServiceImpl commentService = new CommentServiceImpl();
    EpisodeServiceImpl episodeService = new EpisodeServiceImpl();
    ImageServiceImpl imageService = new ImageServiceImpl();

    //Приветственная страница
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ModelAndView Welcome(){
        ModelAndView md = new ModelAndView("Hello");

        String rick = "https://www.youtube.com/embed/AqT-MJnbePM";      
        String title = "Добро пожаловать на мой сайт о Madness Combat";
        md.addObject("title", title);
        md.addObject("rick",rick);

        return md;
    }

    //Игра в Project Nexus
    @RequestMapping(value = "/playNexus", method = RequestMethod.GET)
    public ModelAndView PlayNexus(){
        ModelAndView md = new ModelAndView("Nexus");

        Comment come = new Comment();

        String title = "Здесь вы можеть сыграть в Madness Project Nexus";
        String link = "http://www.newgrounds.com/portal/view/592473";

        md.addObject("title", title);
        md.addObject("link",link);

        return md;
    }

    //Форма с добавлением эпизодов
    @RequestMapping(value = "/addEpisode", method = RequestMethod.GET)
    public ModelAndView AddEpisode(){
        ModelAndView md = new ModelAndView("AddEpisode");
        String title = "Добавить новый эпизод";
        String but = "Загрузить";


        String titlePlac = "Напишите название файла здесь";
        String linkPlac = "Ссылка должна содержать https://www.youtube.com/embed/";
        String descPlac = "Введите описание здесь";

        Episode episode = new Episode();

        md.addObject("episode",episode);
        md.addObject("title",title);
        md.addObject("titlePlac", titlePlac);
        md.addObject("linkPlac", linkPlac);
        md.addObject("descPlac", descPlac);
        md.addObject("butto",but);

        return md;
    }

    //Метод POST, добавляющий эпизод
    @RequestMapping(value = "/addEpisodeAction", method = RequestMethod.POST)
    public String addEpisodeAction(@Validated @ModelAttribute("episode") Episode episode, BindingResult result ,ModelMap map) throws UnsupportedEncodingException{

        map.addAttribute("title", episode.getTitle());
        map.addAttribute("link",episode.getLink());
        map.addAttribute("desc",episode.getDesc());

        /*epsiodeValidator.validate(episode, result);
        if(result.hasErrors()){
            return "redirect:/addEpisode";
        } else {}*/

            String mel = new String(episode.getTitle().getBytes("ISO-8859-1"), "UTF-8");
            String mec = new String(episode.getLink().getBytes("ISO-8859-1"), "UTF-8");
            String mev = new String(episode.getDesc().getBytes("ISO-8859-1"), "UTF-8");

            episode.setTitle(mel);
            episode.setLink(mec);
            episode.setDesc(mev);

        episodeService.addEpisode(episode);

        return "redirect:/getSeries";

    }

    //Список эпизодов
    @RequestMapping(value = "/getSeries/{id}")
    public ModelAndView GetSeries(){
        ModelAndView md = new ModelAndView("AllEpisodes");
        String title = "Вы можеть смотреть сериал Madness Combat здесь";

        long count = episodeService.getCount();

        long pages = count / 5 + 1;

        List<Episode> eps = episodeService.listEpisode();

        md.addObject("pages",pages);
        md.addObject("episodes",eps);
        md.addObject("title",title);

        return md;
    }

    //Просмотр эпизодов
    @RequestMapping(path = "/watchEpisode/{id}")
    public ModelAndView watchEpisode(@PathVariable int id){
        ModelAndView md = new ModelAndView("WatchEpisode");

        Episode eps = episodeService.getEpisode(id);
        String title = eps.getTitle();

        md.addObject("title",title);
        md.addObject("episode",eps);

        return md;
    }

    //Метод POST добавления комметариев
    @RequestMapping(value = "/addComment", method = RequestMethod.POST)
    public String addComment(@Validated @ModelAttribute("comment") Comment comment, BindingResult result, ModelMap model ) throws UnsupportedEncodingException{

        model.addAttribute("author", comment.getAuthor());
        model.addAttribute("content", comment.getContent());

        String mel = new String(comment.getAuthor().getBytes("ISO-8859-1"), "UTF-8");
        String mec = new String(comment.getContent().getBytes("ISO-8859-1"), "UTF-8");
        comment.setAuthor(mel); 
        comment.setContent(mec);

        commentService.addComment(comment);

        return "redirect:/comments/1";
    }

    //Список комметариев
    @RequestMapping(value = "/comments/{id}")
    public ModelAndView Commentaries(@PathVariable int id){
        ModelAndView md = new ModelAndView("Comments");
        String title = "Оставьте отзыв";        
        String post = "Отправить";

        long count = commentService.getCount();

        long pages = count / 5 + 1;

        List<Comment> coms = commentService.listComments(id);

        Comment comment = new Comment();

        md.addObject("comment", comment);

        md.addObject("comments",coms);
        md.addObject("title",title);
        md.addObject("Post",post);
        md.addObject("pages", pages);       

        return md;
    }

    //Доступ к галерее (В разработке)
    @RequestMapping(value = "/galery")
    public ModelAndView Gallery(){
        ModelAndView md = new ModelAndView("Gallery");

        Image image = new Image();

        String title2 = "Посмотрите галерею";
        String butto = "Загрузить картинку";

        md.addObject("butto", butto);
        md.addObject("title2",title2);
        md.addObject("image",image);

        return md;
    }

    //Добавление изображений (В разработке)
    @RequestMapping(value = "/addImage", method = RequestMethod.POST)
    public String addImage(@Validated @ModelAttribute("image") Image image, @RequestParam("file") MultipartFile file , ModelMap map, BindingResult result ) throws IOException{

        map.addAttribute("title", image.getTitle());

        imageService.addImage(image, file);

        if(result.hasErrors()){
            return "redirect:/";
        }

        return "redirect:/galery";
    }
}

Image Model

package com.model;

import java.io.File;
import java.sql.Blob;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;

import org.springframework.web.multipart.MultipartFile;

@Entity
@Table(name = "gallery_table")
public class Image {

    @Id
    @GeneratedValue
    @Column(name = "image_id")
    private int id;

    @NotNull
    @Column(name = "image_title")
    private String title;

    @NotNull
    @Column(name = "image_file")
    @Lob
    private Blob file;

    @Column(name = "image_date")
    private Date date;  

    public Image() {
        this.date = new Date();
    }

    public void setId(int id) {
        this.id = id;
    }

    public Image(String title, Date date) {
        this.title = title;
        this.file = null;
        this.date = date;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Blob getFile() {
        return file;
    }

    public void setFile(Blob file) {
        this.file = file;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public int getId() {
        return id;
    }   

}

ImageDAO

package com.dao.image;

import java.sql.Blob;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.springframework.web.multipart.MultipartFile;

import com.model.Episode;
import com.model.Image;

public class ImageDAOImpl implements ImageDAO {

    SessionFactory sessionfactory = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Image.class).buildSessionFactory();

    public List<Image> getGallery() {       
        Session sess = sessionfactory.openSession();
        Transaction tx = null;
        List<Image> images = new ArrayList<Image>();

        try {
            tx = sess.beginTransaction();
            tx.begin();
            images = sess.createQuery("from Image").list();
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            sess.close();
        }

        return images;
    }

    public void addImage(Image image,MultipartFile file) {
        Session sess = sessionfactory.openSession();
        Transaction tx = null;
        try {
            tx = sess.beginTransaction();
            Blob blob = Hibernate.getLobCreator(sess).createBlob(file.getInputStream(), file.getSize());
            image.setFile(blob);
            tx.begin();
            sess.save(image);
            tx.commit();                        
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            sess.close();
        }

    }

    public void deleteimage(int id) {
        Session sess = sessionfactory.openSession();
        Transaction tx = null;
        try {
            tx = sess.beginTransaction();
            tx.begin();
            Image im = sess.load(Image.class, id);
            if (im != null) {
                sess.delete(im);
            }
            tx.commit();                        
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            sess.close();
        }

    }

    public Image getImage(int id) {
        Image eps = null;
        Session sess = sessionfactory.openSession();
        Transaction tx = null;
        try {
            tx = sess.beginTransaction();
            eps = sess.load(Image.class, id);
        } catch (Exception e) {
            tx.rollback();
            e.printStackTrace();
        } finally {
            sess.close();
        }

        return eps;
    }

    public long getCount() {
        Session sess = sessionfactory.openSession();
        Transaction tx = null;
        long i = 0;
        try {
            tx = sess.beginTransaction();
            i = (Long) sess.createQuery("select count(*) from Image").uniqueResult();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sess.close();
        }
        return i;
    }

}

Вьюшка

<%@ include file="Header.jsp" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>${title2 }</title>
</head>
<body>
        <form:form action="/cas/addImage" modelAttribute="image" method="POST" cssClass="divbor" enctype="multipart/form-data" >
        <table align="center">
            <tr>
                <td><form:label path="title"> Заголовок:</form:label></td>
                <td><form:input path="title" size="100px" cssClass="fieldBack" /></td>
            </tr>
            <tr>
                <td><form:label path="file" >Картинку сюда:</form:label></td>
                <td><input type="file" name="file" id="file" /></td>
            </tr>
            <tr>
                <td><input type="submit" value="${butto}" class="btn btn-primary"  ></td>
            </tr>
        </table>
    </form:form>
</body>
</html>

Dispatcher

<?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.3.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.3.xsd">

<mvc:annotation-driven/>
<mvc:resources mapping="resources/**" location="resources/"></mvc:resources>
<context:component-scan base-package="com.bascon"/>

    <bean id="episodeValidator" autowire="byName"
        class="com.validation.EpisodeValidation">
    </bean>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">     
        <property name="maxUploadSizePerFile" value="5242880"/>
    </bean>
</beans>
2
  • multipartResolver в конфигурации DispatcherServlet есть? 14 мая 2017 в 15:00
  • Да, добавил Dispatcher.
    – Lukashman
    14 мая 2017 в 15:13

2 ответа 2

0

Я бы предложил Вам использовать следующий подход:

  1. Изменить класс Image так, чтобы он содержал не данные изображения, а ссылку на файл (зачем лишний раз нагружать БД?), например:

@Column(name = "pathOriginal",nullable = false) private String pathOriginal; (+getter'ы/setter'ы)

  1. Создать интерфейс, например StorageService в котором будут методы Image store(@NotNull MultipartFile file); и List<Image> store(@NotNull List<MultipartFile> files);, и заимплементить StorageService, например классом FileSystemStorageService, пометив его аннотацией @Service
  2. В методе public Image store(MultipartFile file) выполнить сохранение файла на диск, создать и вернуть новый объект класса Image, в поле pathOriginal будет (относительная или абсолютная) ссылка на сохраненный файл
  3. В контроллере выполнить сохранение в БД и проверку.

  4. Для получения файла, создать контроллер ImageController и метод public ResponseEntity<byte[]> getImage(@PathVariable("path"(или)"id")String path), пометив его аннотациями @RequestMapping и @ResponseBody. Далее выполнить поиск файла по переданному пути (или, если выбрали вариант с id, то взять сначала получить объект из БД, а затем поиск файла) и, например, использовать следующий код.

    try
    {
        image = Files.readAllBytes(imagePath);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.IMAGE_PNG);
        return new ResponseEntity<byte[]>(image,httpHeaders, HttpStatus.OK);
    } catch (IOException e)
    {
        System.err.println("[getImage.Line("+
                Thread.currentThread().getStackTrace()[1].getLineNumber()+//Error line number
                ")]: file "+imagePath+" not found");
        return null;
    }
    

Для сохранения можно будет использовать

@Autowired StorageService storageService .... Image image = storageService.store(multipartFile); image = imageRepository.save(image); //или тот метод, который сохраняет объект в БД if(image == null) { //что-то не так } ....

1
  • Большое спасибо за помощь, я учту ваше предложение, проблема была в двойной отправке транзакции
    – Lukashman
    17 июн 2017 в 20:06
0

Всем спасибо за ответы, проблема была в двойной отправке транзакции в ImageDAOImpl

public void addImage(Image image, MultipartFile file) {
    Session sess = sessionfactory.openSession();
    Transaction tx = null;
    try {
            **tx = sess.beginTransaction();**
        Blob blob = Hibernate.getLobCreator(sess)
                .createBlob(file.getInputStream(), file.getSize());
        image.setFile(blob);
            **tx.begin();**
        sess.save(image);
        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();
    } finally {
        sess.close();
    }
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.