В chrome я вижу ошибки в консоли «Не разрешено загружать локальный ресурс: file: /// ...» при попытке загрузить изображения через приложение Spring. Я использую freemarker для моего взгляда. Кстати, у меня есть Spring Security в моем проекте.
Это MvcConfig
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Value("${upload.path}")
private String uploadPath;
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{
registry.addResourceHandler("/img**")
.addResourceLocations("file:///" + uploadPath + "/");
}
}
WebSecurityConfig для Spring Security
import com.example.sweater.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/registration", "/static/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService)
.passwordEncoder(NoOpPasswordEncoder.getInstance());
// auth.jdbcAuthentication()
// .dataSource(dataSource)
// .passwordEncoder(NoOpPasswordEncoder.getInstance())
// .usersByUsernameQuery("select username, password, active from usr where username=?")
// .authoritiesByUsernameQuery("select u.username, ur.roles from usr u inner join user_role ur on u.id = ur.user_id where u.username=?");
}
}
Это мое мнение, основанное на freemarker main.ftl
<#import "parts/login.ftl" as l>
<@c.page>
<div>
<@l.logout/>
<span><a href="/user">User list</a></span>
</div>
<div>
<form method="post" enctype="multipart/form-data">
<input type="text" name="text" placeholder="Введите сообщение"/>
<input type="text" name="tag" placeholder="Тэг"/>
<input type="file" name="file">
<input type="hidden" name="_csrf" value="${_csrf.token}" />
<button tupe="submit">Добавить</button>
</form>
</div>
<div>Список сообщений</div>
<form method="get" action="/main">
<input type="text" name="filter" value="${filter?ifExists}">
<button type="submit">Найти</button>
</form>
<#list messages as message>
<div>
<b>${message.id}</b>
<span>${message.text}</span>
<i>${message.tag}</i>
<strong>${message.authorName}</strong>
<div>
<#if message.filename??>
<img src="C:\letscode\src\main\resources\static\${message.filename}">
</#if>
</div>
</div>
<#else>
No message
</#list>
</@c.page>
MainController
package com.example.sweater.controller;
import com.example.sweater.domain.Message;
import com.example.sweater.domain.User;
import com.example.sweater.repos.MessageRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;
@Controller
public class MainController {
@Autowired
private MessageRepo messageRepo;
@Value("${upload.path}")
private String uploadPath;
@GetMapping("/")
public String greeting(String name, Map<String, Object> model)
{
return "greeting";
}
@GetMapping("/main")
public String main(@RequestParam(required = false, defaultValue = "") String filter, Model model)
{
Iterable<Message> messages = messageRepo.findAll();
if (filter != null && !filter.isEmpty())
{
messages = messageRepo.findByTag(filter);
}
else
{
messages = messageRepo.findAll();
}
model.addAttribute("messages", messages);
model.addAttribute("filter", filter);
return "main";
}
@PostMapping("/main")
public String add(@RequestParam("file") MultipartFile file,
@AuthenticationPrincipal User user,
@RequestParam String text, @RequestParam String tag, Map<String, Object> model)
throws IOException
{
Message message = new Message(text, tag, user);
if (file != null)
{
File uploadDir = new File(uploadPath);
if (!uploadDir.exists())
{
uploadDir.mkdir();
}
String uuidFile = UUID.randomUUID().toString();
String resultFilename = uuidFile + "." + file.getOriginalFilename();
file.transferTo(new File(uploadPath + "/" + resultFilename));
message.setFilename(resultFilename);
}
messageRepo.save(message);
Iterable<Message> messages = messageRepo.findAll();
model.put("messages", messages);
return "main";
}
}