spring boot2017. 9. 5. 10:30
반응형

https://spring.io/blog/2015/06/17/devtools-in-spring-boot-1-3



Spring Boot 1.3 will ship with a brand new module called spring-boot-devtools. The aim of this module is to try and improve the development-time experience when working on Spring Boot applications.

To use the module you simply need to add it as a dependency in your Maven POM:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
    </dependency>
</dependencies>

or your Gradle build file:

dependencies {
    compile("org.springframework.boot:spring-boot-devtools")
}

Once included, the spring-boot-devtools module provides a number of nice features that we cover below (If you can’t be bother to read the text, skip to the end of the post for a short video).

Property Defaults

If you’ve used templating technologies such as Thymeleaf with Spring Boot 1.2, you might be familiar with properties such as spring.thymeleaf.cache. These properties are used to disable caching and allow you to update pages without needing to restart your application. Having support for these properties is pretty handy, but remembering to set them during development has always been a bit of a pain.

Now, when you use the spring-boot-devtools module, you no longer need to remember to set the properties. During development caching for Thymeleaf, Freemarker, Groovy Templates, Velocity and Mustache are all automatically disabled.

Automatic Restart

You may have used tools such as JRebel or Spring Loaded in the past to provide instant reload for your Java applications. These tools are great, but they do often require additional configuration or IDE plugins to work (and some of them even cost money!)

With Spring Boot 1.3 we’ve been working on something that’s a little slower than these “instant reload” techniques, and instead works by restarting your application. When you have the spring-boot-devtools module included, any classpath file changes will automatically trigger an application restart. We do some tricks to try and keep restarts fast, so for many microservice style applications this technique might be good enough.

LiveReload

With sensible “cache properties” and “automatic restarts” working, needing to manually click the browser refresh button each time something changes starts to become a little tedious. So to help save your mouse buttons, Spring Boot 1.3 DevTools includes an embedded LiveReload server. LiveReload is a simple protocol that allows your application to automatically trigger a browser refresh whenever things change. Browser extensions are freely available for Chrome, Firefox and Safari from livereload.com.

Remote Debug Tunneling

If you’ve ever tried to host a Java application using Docker, or if you’ve tried a micro PaaS such as Lattice, you may have been frustrated about how difficult it can be to debug your code. You need configure Java to start with -Xdebug and somehow forward the appropriate port so that you can attach the remote debugger.

To help with this, Spring Boot 1.3 can tunnel JDWP (the Java Debug Wire Protocol) over HTTP directly to your application. This can even work with applications deployed to Internet Cloud providers that only expose port 80 and 443 (although since JDWP is quite a chatty protocol this can be quite slow).

Remote Update and Restart

The final trick that DevTools offers is support for remote application updates and restarts. This works by monitoring your local classpath for file changes and pushing them to a remote server which is then restarted. As with local restarts, you can also use this feature in combination with LiveReload.

Video Preview

All the features discussed in this post are already available in Spring Boot 1.3.0.M1 and detailed documentation is available in the reference guide. If you’re not ready to install the bits yourself yet, here’s a short video that shows how they work:

Posted by 1010
spring boot2016. 3. 24. 16:50
반응형

controller.java

1
2
3
4
5
6
7
8
9
10
11
12
    @RequestMapping(value = "/downLoadFile", method = RequestMethod.GET)
    public ModelAndView downLoadFile() {
        
        String fullPath = "D:\\fileupload\\2016\\3\\5da2e43f148146b2aa641d268ad99e47.txt";
        File downloadFile = new File(fullPath);
        
        ModelAndView mav = new ModelAndView();
        mav.addObject("downloadFile", downloadFile);
        mav.addObject("downloadFileName""한글.txt");
        mav.setViewName("downloadFileView");
        return mav;
    }
cs



view.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
 
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.servlet.view.AbstractView;
 
@Component("downloadFileView")
public class DownloadFileView extends AbstractView{
 
    public DownloadFileView() {
        // TODO Auto-generated constructor stub
        setContentType("application/download; ccharset=utf-8");
    }
    
    @Override
    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // TODO Auto-generated method stub
        File file = (File) model.get("downloadFile");
        String downloadFileName = (String) model.get("downloadFileName");
        
        response.setContentType(getContentType());
        response.setContentLength((int)file.length());
        setResponse(request,response,downloadFileName);
        response.setHeader("Content-Transfer-Encoding""binary");
         
        OutputStream out = response.getOutputStream();
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            FileCopyUtils.copy(fis, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) { try { fis.close(); } catch (Exception e2) {}}
        }
        out.flush();
    }
    private void setResponse(HttpServletRequest request, HttpServletResponse response, String fileName) throws UnsupportedEncodingException{
        String userAgent = request.getHeader("User-Agent");
        if (userAgent.indexOf("MSIE 5.5"> -1) { // MS IE 5.5 이하
            response.setHeader("Content-Disposition""filename=" + URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+""\\ "+ ";");
        } else if (userAgent.indexOf("MSIE"> -1) { // MS IE (보통은 6.x 이상 가정)
            response.setHeader("Content-Disposition""attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+""\\ "+ ";");
        } else if (userAgent.indexOf("Trident"> -1) { // MS IE 11
            response.setHeader("Content-Disposition""attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+""\\ "+ ";");
        } else { // 모질라나 오페라
            response.setHeader("Content-Disposition""attachment; filename=" + new String(fileName.getBytes("euc-kr"), "latin1").replaceAll("\\+""\\ "+ ";");
        }
    }
}
cs


Posted by 1010
spring boot2016. 3. 21. 13:59
반응형

기존 버전 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// import org.apache.poi.hssf.usermodel.*;
 
HSSFWorkbook wb = new HSSFWorkbook();
// create a new sheet
HSSFSheet s = wb.createSheet();
// declare a row object reference
HSSFRow r = null;
// declare a cell object reference
HSSFCell c = null;
// create 2 cell styles
HSSFCellStyle cs = wb.createCellStyle();
HSSFCellStyle cs2 = wb.createCellStyle();
HSSFDataFormat df = wb.createDataFormat();
 
// create 2 fonts objects
HSSFFont f = wb.createFont();
HSSFFont f2 = wb.createFont();
 
// Set font 1 to 12 point type, blue and bold
f.setFontHeightInPoints((short12);
f.setColor( HSSFColor.RED.index );
f.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
 
// Set font 2 to 10 point type, red and bold
f2.setFontHeightInPoints((short10);
f2.setColor( HSSFFont.RED.index );
f2.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
 
// Set cell style and formatting
cs.setFont(f);
cs.setDataFormat(df.getFormat("#,##0.0"));
 
// Set the other cell style and formatting
cs2.setBorderBottom(cs2.BORDER_THIN);
cs2.setDataFormat(HSSFDataFormat.getBuiltinFormat("text"));
cs2.setFont(f2);
 
 
// Define a few rows
for(short rownum = (short)0; rownum < 30; rownum++) {
    HSSFRow r = s.createRow(rownum);
    for(short cellnum = (short)0; cellnum < 10; cellnum += 2) {
        HSSFCell c = r.createCell(cellnum);
        HSSFCell c2 = r.createCell(cellnum+1);
 
        c.setCellValue((double)rownum + (cellnum/10));
        c2.setCellValue(new HSSFRichTextString("Hello! " + cellnum);
    }
}
 
// Save
FileOutputStream out = new FileOutputStream("workbook.xls");
wb.write(out);
out.close();
cs

new 버전

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// import org.apache.poi.ss.usermodel.*;
 
Workbook[] wbs = new Workbook[] { new HSSFWorkbook(), new XSSFWorkbook() };
for(int i=0; i<wbs.length; i++) {
   Workbook wb = wbs[i];
   CreationHelper createHelper = wb.getCreationHelper();
 
   // create a new sheet
   Sheet s = wb.createSheet();
   // declare a row object reference
   Row r = null;
   // declare a cell object reference
   Cell c = null;
   // create 2 cell styles
   CellStyle cs = wb.createCellStyle();
   CellStyle cs2 = wb.createCellStyle();
   DataFormat df = wb.createDataFormat();
 
   // create 2 fonts objects
   Font f = wb.createFont();
   Font f2 = wb.createFont();
 
   // Set font 1 to 12 point type, blue and bold
   f.setFontHeightInPoints((short12);
   f.setColor( IndexedColors.RED.getIndex() );
   f.setBoldweight(Font.BOLDWEIGHT_BOLD);
 
   // Set font 2 to 10 point type, red and bold
   f2.setFontHeightInPoints((short10);
   f2.setColor( IndexedColors.RED.getIndex() );
   f2.setBoldweight(Font.BOLDWEIGHT_BOLD);
 
   // Set cell style and formatting
   cs.setFont(f);
   cs.setDataFormat(df.getFormat("#,##0.0"));
 
   // Set the other cell style and formatting
   cs2.setBorderBottom(cs2.BORDER_THIN);
   cs2.setDataFormat(df.getFormat("text"));
   cs2.setFont(f2);
 
 
   // Define a few rows
   for(int rownum = 0; rownum < 30; rownum++) {
       Row r = s.createRow(rownum);
       for(int cellnum = 0; cellnum < 10; cellnum += 2) {
           Cell c = r.createCell(cellnum);
           Cell c2 = r.createCell(cellnum+1);
   
           c.setCellValue((double)rownum + (cellnum/10));
           c2.setCellValue(
                 createHelper.createRichTextString("Hello! " + cellnum)
           );
       }
   }
   
   // Save
   String filename = "workbook.xls";
   if(wb instanceof XSSFWorkbook) {
     filename = filename + "x";
   }
 
   FileOutputStream out = new FileOutputStream(filename);
   wb.write(out);
   out.close();
}
cs


Posted by 1010
spring boot2016. 3. 16. 13:01
반응형
1
2
3
4
5
6
7
8
9
 
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryForMyBatis() throws Exception  {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        sqlSessionFactoryBean.setConfigLocation(applicationContext.getResource("classpath:mybatis-config.xml"));
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
        return sqlSessionFactoryBean; 
    }
cs



1
2
3
4
5
6
7
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
         <setting name="callSettersOnNulls" value="true"/>
    </settings>
</configuration>
cs


Posted by 1010
spring boot2016. 3. 15. 17:03
반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import javax.persistence.EntityNotFoundException;
 
import org.baeldung.web.exception.MyResourceNotFoundException;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
//import org.springframework.security.access.AccessDeniedException;
 
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
 
    public RestResponseEntityExceptionHandler() {
        super();
    }
 
    // API
 
    // 400
 
    @ExceptionHandler({ ConstraintViolationException.class })
    public ResponseEntity<Object> handleBadRequest(final ConstraintViolationException ex, final WebRequest request) {
        final String bodyOfResponse = "This should be application specific";
        return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
    }
 
    @ExceptionHandler({ DataIntegrityViolationException.class })
    public ResponseEntity<Object> handleBadRequest(final DataIntegrityViolationException ex, final WebRequest request) {
        final String bodyOfResponse = "This should be application specific";
        return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
    }
 
    @Override
    protected ResponseEntity<Object> handleHttpMessageNotReadable(final HttpMessageNotReadableException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
        final String bodyOfResponse = "This should be application specific";
        // ex.getCause() instanceof JsonMappingException, JsonParseException // for additional information later on
        return handleExceptionInternal(ex, bodyOfResponse, headers, HttpStatus.BAD_REQUEST, request);
    }
 
    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(final MethodArgumentNotValidException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
        final String bodyOfResponse = "This should be application specific";
        return handleExceptionInternal(ex, bodyOfResponse, headers, HttpStatus.BAD_REQUEST, request);
    }
 
    // 403
    @ExceptionHandler({ AccessDeniedException.class })
    public ResponseEntity<Object> handleAccessDeniedException(final Exception ex, final WebRequest request) {
        System.out.println("request" + request.getUserPrincipal());
        return new ResponseEntity<Object>("Access denied message here"new HttpHeaders(), HttpStatus.FORBIDDEN);
    }
 
    // 404
 
    @ExceptionHandler(value = { EntityNotFoundException.class, MyResourceNotFoundException.class })
    protected ResponseEntity<Object> handleNotFound(final RuntimeException ex, final WebRequest request) {
        final String bodyOfResponse = "This should be application specific";
        return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.NOT_FOUND, request);
    }
 
    // 409
 
    @ExceptionHandler({ InvalidDataAccessApiUsageException.class, DataAccessException.class })
    protected ResponseEntity<Object> handleConflict(final RuntimeException ex, final WebRequest request) {
        final String bodyOfResponse = "This should be application specific";
        return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.CONFLICT, request);
    }
 
    // 412
 
    // 500
 
    @ExceptionHandler({ NullPointerException.class, IllegalArgumentException.class, IllegalStateException.class })
    /*500*/public ResponseEntity<Object> handleInternal(final RuntimeException ex, final WebRequest request) {
        logger.error("500 Status Code", ex);
        final String bodyOfResponse = "This should be application specific";
        return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request);
    }
 
}
cs


Posted by 1010
spring boot2016. 3. 10. 10:55
반응형
1
2
3
4
5
6
7
8
9
10
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.stereotype.Component;
 
@Componentpublic class EmbeddedServletConfig implements EmbeddedServletContainerCustomizer{
    @Override    public void customize(ConfigurableEmbeddedServletContainer container) {
        // TODO Auto-generated method stub        
        container.setPort(8080);    \
    }
}
cs


Posted by 1010
spring boot2016. 3. 10. 10:51
반응형
1
(String)((OAuth2Authentication) principal).getName()
cs


Posted by 1010
spring boot2016. 3. 10. 10:49
반응형

spring boot linux 배포후 한글 파라미터 않먹을때

spring security 처리된 경우 


1
2
3
4
5
6
7
8
9
@Override    
public void configure(HttpSecurity http) throws Exception {         
    CharacterEncodingFilter filter = new CharacterEncodingFilter();        
    filter.setEncoding("UTF-8");        
    filter.setForceEncoding(true);        
    http.addFilterBefore(filter,CsrfFilter.class);        
    http.authorizeRequests().antMatchers("/**").permitAll();
//        http.authorizeRequests().antMatchers("/api/**").hasRole("ADMIN");    
}
cs


Posted by 1010
spring boot2016. 1. 19. 14:36
반응형

spring boot springloaded 


개발시 서버 재기동없이 소스 반영하기.

유료는 jrabel 정도....










pom.xml 설정하고


서버 기동시 vm arguments 설정 : 진입시점 생성


Posted by 1010
spring boot2016. 1. 5. 14:31
반응형

http://kimseunghyun76.tistory.com/388

Posted by 1010