Spring에서 Mail, File 사용하기
Mail Service
Spring에서 메일을 보내기 위한 서비스
사용법
- http://www.javacodegeeks.com/2010/07/java-mail-spring-gmail-smtp.html 참조
- http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mail.html 참조
javax.mail.Session ClassNotFoundException 발생
ClassPath에 mail.jar가 없어서 발생하는 에러
File Service
Spring에서 파일을 쓰기 위한 서비스
- multipart ViewResolver bean context.xml에 추가해주기
<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</beans:bean>
- Controller
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
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;
@Controller
@RequestMapping(value = "/file")
public class FileController {
private static final Logger log = Logger.getLogger(FileController.class);
@RequestMapping(value = "/upload", method = RequestMethod.GET)
public String file(Model model) {
return "file";
}
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(Model model,
@RequestParam("file") MultipartFile[] files) {
int length = files.length;
log.info("files length is " + length);
if (length != 0) {
for (MultipartFile file : files) {
if(file.getOriginalFilename() != "" || file.getOriginalFilename().length() != 0){
try {
log.info(file.getOriginalFilename());
File outputFile = new File(file.getOriginalFilename());
OutputStream output = new FileOutputStream(outputFile);
log.info(outputFile.getAbsolutePath());
IOUtils.copyLarge(file.getInputStream(),output);
output.flush();
output.close();
log.info("ok");
// byte[] bytes = file.getBytes();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} else {
log.info("no file");
}
return "file";
}
@RequestMapping(value = "/download/{filename}", method = RequestMethod.GET)
public void download(Model model,
@PathVariable(value = "filename") String filename) {
}
}
- JSP
<%@taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<form action="file /upload"/>" method="POST" enctype="multipart/form-data">
<input name="file" type="file" />
<input name="file" type="file" />
<input type="submit" value="Upload"/>
</form>
</body>
댓글 없음:
댓글 쓰기