无法使用spring mvc

时间:2016-11-24 12:30:28

标签: java spring jsp spring-mvc

我正在开发一个spring web MVC应用程序。我使用Multipart上传了图像并保存到文件系统(C:\ Database \ 1.jpg)。我将文件位置保存到数据库。现在,我需要显示图像,但不知道原因是什么!我无法显示图像。

Web.xml中

 <web-app 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" version="2.5">
    <display-name>Spring3 MVC Application</display-name>
    <servlet>
        <servlet-name>spring-web</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring-web</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

弹簧的web-servlet.xml中

<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/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd">

<!-- Enables the Spring MVC @Controller programming model -->
<mvc:annotation-driven/>

<context:annotation-config/>
<context:component-scan base-package="com.springmaven"/>

<mvc:default-servlet-handler/>
<mvc:resources mapping="/**" location="/"/>
<mvc:resources mapping="C:/**" location="/" />

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

<bean id="vendorDAO" class="com.springmaven.dao.VendorDAOImpl"/>
<bean id="sendEmail" class="com.springmaven.model.Email"/>
<bean id="hairStyleDAO" class="com.springmaven.dao.HairStyleDAOImpl"/>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/seturstyle?useSSL=false"/>
    <property name="username" value="root"/>
    <property name="password" value="root"/>
</bean>
<!--For FileUpload-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="uploadTempDir" ref="uploadDirResource" />
</bean>
<bean id="uploadDirResource" class="org.springframework.core.io.FileSystemResource">
    <constructor-arg>
        <value>C:/Database/</value>
    </constructor-arg>
</bean>
<!--For Sending Mail-->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="smtp.gmail.com"/>
    <property name="port" value="587"/>
    <property name="username" value="setuastyle@gmail.com"/>
    <property name="password" value="msitmsit"/>

    <!-- The name of the property, following JavaBean naming conventions -->
    <property name="javaMailProperties">
        <props>
            <prop key="mail.transport.protocol">smtp</prop>
            <prop key="mail.smtp.auth">true</prop>
            <prop key="mail.smtp.starttls.enable">true</prop>
            <prop key="mail.debug">true</prop>
        </props>
    </property>
</bean>

HairStyleController

package com.springmaven.controllers;
import com.springmaven.dao.HairStyleDAOImpl;
import com.springmaven.model.HairStyle;
import com.springmaven.model.Vendor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

@Controller
public class HairStyleController {
@Autowired
HairStyleDAOImpl hairStyleDAO;

@RequestMapping(value = "/AddHairstyle")
public ModelAndView addHairstyleView() {
    ModelAndView modelView = new ModelAndView("vendor_AddHairStyle");
    return modelView;
}

@RequestMapping(value = "/EditHairstyleDetails")
public ModelAndView editHairstyleView() {
    ModelAndView modelView = new ModelAndView("vendor_editHairstyle");
    return modelView;
}

@RequestMapping(value = "/ViewHairstyles")
public ModelAndView viewAllHairstyleView(HttpSession session) {
    Vendor v = (Vendor) session.getAttribute("vendor");
    List<HairStyle> hairstyles=hairStyleDAO.getAllVendorhairstyles(v.getEmail());
    ModelAndView modelView = new ModelAndView("vendor_viewAllHairstyles");
    modelView.addObject("hairstyles",hairstyles);
    return modelView;
}

@RequestMapping(value = "/addHairstyleForm", method = RequestMethod.POST)
public ModelAndView addhairStyleForm(@ModelAttribute("hairstyle") HairStyle hairStyle, @RequestParam("files") MultipartFile[] files,
                             HttpServletRequest request) {
    ModelAndView modelView = new ModelAndView("redirect:/AddHairstyle");


    File pics[]=new File[files.length];

    for (int i = 0; i < files.length; i++) {
        MultipartFile file = files[i];
        try {
            byte barr[] = file.getBytes();
            String orgfileName = file.getOriginalFilename();
            int lastIndex = orgfileName.lastIndexOf('.');
            String extension = orgfileName.substring(lastIndex, orgfileName.length());

            String saloonName = hairStyle.getSaloonName();
            saloonName = saloonName.replace(" ", "");

            String path = request.getContextPath();
            File d = new File("C:\Database\");
            if(!d.exists())
                d.mkdir();

            File di = new File(d+ "\" + saloonName);
            if (!di.exists()) {
                boolean br = di.mkdir();
            }

            String hairStyleName = hairStyle.getHairstyleName();
            hairStyleName = hairStyleName.replace(" ", "");

            File dir = new File(di + "\" + hairStyleName);
            if (!dir.exists()) {
                boolean br = dir.mkdir();
            }
            // Create the file on server
            File serverFile = new File(dir+ "\" + hairStyleName + "_" + (i+1) + extension);

            BufferedOutputStream bout = new BufferedOutputStream(
                    new FileOutputStream(serverFile));

            bout.write(barr);
            bout.flush();
            bout.close();
            pics[i] = serverFile;
        } catch (Exception e) {
            System.out.println(e);
        }
    }
    hairStyle.setHairstylePics(pics);
    int i = hairStyleDAO.addHairStyle(hairStyle);
    if (i == 1) {
        modelView.setViewName("success");
    }
    else
    {
        modelView.addObject("error","Error occured during registration please do try again");
    }
    return modelView;
}
}

现在查看所有发型JSP,我无法加载图片。显示空的空白空间。

任何人都可以解决这个问题吗?

提前致谢

1 个答案:

答案 0 :(得分:0)

假设您要在FileSystem中存储图像,您需要读取文件路径并获取图像。

这是后端代码(注意我使用的是Spring框架)

 @RequestMapping(value = "/showImage/{saloonName}/{folder}/{hairstyleName}/{imageName}", method = RequestMethod.GET)
@ResponseBody
public void getImage(@PathVariable(value = "saloonName") String saloonName,
                     @PathVariable(value = "folder") String folder,
                     @PathVariable(value = "hairstyleName") String haistyleName,
                     @PathVariable(value = "imageName") String imageName, HttpServletResponse response) throws IOException {

    response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
    try {
        InputStream is = new FileInputStream("C:\\Database" + File.separator + saloonName +
                File.separator + folder + File.separator + haistyleName + File.separator + imageName + ".jpg");
        IOUtils.copy(is, response.getOutputStream());
    } catch (IOException e) {
        System.out.println("Couldn't open image from " + "C:\\Database\\" + saloonName + "\\" + folder + "\\" + haistyleName + "\\" + imageName + ".jpg");
    }
}

然而,在前端

<img class="group list-group-image" src="/showImage/${hairstyles.get(i).hairstylePics[0]}"/>

这里在上面的代码中,我使用Servlet作为请求/响应模型。              / showImage / {FOLDER_PATH} / IMAGE_NAME 当我请求上面指定的图像时它将请求映射功能从文件系统加载图像并将响应发送为image / jpeg,image / jpg,image / png,image / gif格式。