'3. Implementation/Spring'에 해당되는 글 6건

  1. 2016.11.23 Spring Websocket example (웹 채팅)
  2. 2016.05.12 CGLIB Sample
  3. 2015.05.12 Exception Handling in Spring MVC
  4. 2015.04.15 Spring Security JSP Tag Libraries
  5. 2015.04.07 Spring MVC and HDIV example application and Debugging
  6. 2015.02.02 Spring Framework Reference Documentation 4.1.4 RELEASE
2016. 11. 23. 00:45

Spring Websocket example (웹 채팅)

Spring 으로 push 서버 기능 구현을 알아보다가 HTML5 의 WebSocket 샘플을 스프링에서 제공하는 걸 확인하였다. git 에서 다운받고 gradle 로 실행해보니 바로 기능을 테스트 해 볼 수 있어 좋았다.



https://spring.io/guides/gs/messaging-stomp-websocket/



gradle 일 경우 아래 명령 입력 후,


gradlew bootRun



브라우저에서 아래 주소로 접속하면 보인다.


http://localhost:8080/


아래는 샘플 스크린 샷. 크롬과 IE 간 메시지를 주고 받는 예이다.





2016. 5. 12. 00:59

CGLIB Sample

It's very simple sample for CGLib Proxy being used by Spring.


	public static void main(String[] args) {
	    Enhancer enhancer = new Enhancer();
	    // enhancer.setSuperclass(MemberServiceImpl.class);
	    enhancer.setSuperclass(MemberService.class);
	    enhancer.setCallback(new MethodCallLogInterceptor());
	    Object obj = enhancer.create();
	    MemberService memberService = (MemberService)obj;
	    memberService.regist(new Member());
	}


public class MethodCallLogInterceptor implements MethodInterceptor {
	
	MemberService memberService = new MemberServiceImpl();
    
    public Object intercept(Object object, Method method, Object[] args, 
            MethodProxy methodProxy) throws Throwable {
        System.out.println("before ");
        
        // Object returnValue = methodProxy.invokeSuper(memberService, args);
        Object returnValue = method.invoke(memberService, args);
        
        System.out.println("after ");
        return returnValue;
    }
}



cglib.zip


Refer : http://javacan.tistory.com/entry/114

2015. 5. 12. 04:28

Exception Handling in Spring MVC

The following link provides good explanation for exception handling in Spring MVC.


https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc


In addition, it also provides the sample to demonstrate it.


https://github.com/paulc4/mvc-exceptions


I recognized the ResponseStatus annotation is very useful to return abnormal http status.


@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "No such order")
public class OrderNotFoundException extends RuntimeException {

	/**
	 * Unique ID for Serialized object
	 */
	private static final long serialVersionUID = -8790211652911971729L;

	public OrderNotFoundException(String orderId) {
		super(orderId + " not found");
	}
}


In the case of using ControllerAdvice, the following code should be considered if you let other exceptions with ResponseStatus annotation  be handled as it is.


@ControllerAdvice
public class GlobalExceptionHandlingControllerAdvice {

	@ExceptionHandler(SupportInfoException.class)
	public ModelAndView handleError(HttpServletRequest req, Exception exception)
			throws Exception {

		// Rethrow annotated exceptions or they will be processed here instead.
		if (AnnotationUtils.findAnnotation(exception.getClass(),
				ResponseStatus.class) != null)
			throw exception;

		logger.error("Request: " + req.getRequestURI() + " raised " + exception);

		ModelAndView mav = new ModelAndView();
		mav.addObject("exception", exception);
		mav.addObject("url", req.getRequestURL());
		mav.addObject("timestamp", new Date().toString());
		mav.addObject("status", 500);

		mav.setViewName("support");
		return mav;
	}

}


mvc-exceptions.zip


2015. 4. 15. 23:34

Spring Security JSP Tag Libraries

Declaring the Taglib


<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>


The authorize Tag


<sec:authorize access="hasRole('supervisor')">

This content will only be visible to users who have the "supervisor" authority in their list

of <tt>GrantedAuthority</tt>s.

</sec:authorize>


<sec:authorize access="hasPermission(#domain,'read') or hasPermission(#domain,'write')">

This content will only be visible to users who have read or write permission to the Object found as a

request attribute named "domain".

</sec:authorize>


<sec:authorize url="/admin">

This content will only be visible to users who are authorized to send requests to the "/admin" URL.

</sec:authorize>


Disabling Tag Authorization for Testing


If you set the system property spring.security.disableUISecurity to true, the authorize tag will still run but will not hide its contents. By default it will also surround the content with <span class="securityHiddenUI">…</span> tags. This allows you to display "hidden" content with a particular CSS style such as a different background colour. Try running the "tutorial" sample  application with this property enabled, for example.


This can be tested by using the following sample:



tutorial-xml.zip


After downloading it, type the command as below (need to install gradle) :


gradle jettyRun -Dspring.security.disableUISecurity=true


If it succeeded to run, visit the "http://localhost:8080/sample". Then you will see the following page. 





The texts highlighted with orange background will be hidden if it's false.


The authentication Tag


<sec:authentication property="principal.username" />


You can access the Authentication object in your MVC controller

(by calling SecurityContextHolder.getContext().getAuthentication()) and add the data

directly to your model for rendering by the view.


The accesscontrolllist Tag


<sec:accesscontrollist hasPermission="1,2" domainObject="${someObject}">

This will be shown if the user has all of the permissions represented by the values "1" or "2" on the

given object.

</sec:accesscontrollist>



The csrfInput Tag


If CSRF protection is enabled, this tag inserts a hidden form field with the correct name and value for

the CSRF protection token. If CSRF protection is not enabled, this tag outputs nothing.

Normally Spring Security automatically inserts a CSRF form field for any <form:form> tags you use,

but if for some reason you cannot use <form:form>, csrfInput is a handy replacement.

You should place this tag within an HTML <form></form> block, where you would normally place

other input fields. Do NOT place this tag within a Spring <form:form></form:form> block—Spring

Security handles Spring forms automatically.


<form method="post" action="/do/something">

<sec:csrfInput />

Name:<br />

<input type="text" name="name" />

...

</form>


The csrfMetaTags Tag


If CSRF protection is enabled, this tag inserts meta tags containing the CSRF protection token form

field and header names and CSRF protection token value. These meta tags are useful for employing

CSRF protection within JavaScript in your applications.


You should place csrfMetaTags within an HTML <head></head> block, where you would normally

place other meta tags. Once you use this tag, you can access the form field name, header name, and

token value easily using JavaScript. JQuery is used in this example to make the task easier.


<!DOCTYPE html>

<html>

<head>

<title>CSRF Protected JavaScript Page</title>

<meta name="description" content="This is the description for this page" />

<sec:csrfMetaTags />

<script type="text/javascript" language="javascript">

var csrfParameter = $("meta[name='_csrf_parameter']").attr("content");

var csrfHeader = $("meta[name='_csrf_header']").attr("content");

var csrfToken = $("meta[name='_csrf']").attr("content");

// using XMLHttpRequest directly to send an x-www-form-urlencoded request

var ajax = new XMLHttpRequest();

ajax.open("POST", "http://www.example.org/do/something", true);

ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded data");

ajax.send(csrfParameter + "=" + csrfToken + "&name=John&...");

// using XMLHttpRequest directly to send a non-x-www-form-urlencoded request

var ajax = new XMLHttpRequest();

ajax.open("POST", "http://www.example.org/do/something", true);

ajax.setRequestHeader(csrfHeader, csrfToken);

ajax.send("...");

// using JQuery to send an x-www-form-urlencoded request

var data = {};

data[csrfParameter] = csrfToken;

data["name"] = "John";

...

$.ajax({

url: "http://www.example.org/do/something",

type: "POST",

data: data,

...

});

// using JQuery to send a non-x-www-form-urlencoded request

var headers = {};

headers[csrfHeader] = csrfToken;

$.ajax({

url: "http://www.example.org/do/something",

type: "POST",

headers: headers,

...

});

<script>

</head>

<body>

...

</body>

</html>


If CSRF protection is not enabled, csrfMetaTags outputs nothing.


References: spring-security-reference

2015. 4. 7. 23:24

Spring MVC and HDIV example application and Debugging

Source: https://github.com/hdiv/hdiv-spring-mvc-showcase.git            

Reference: http://javahotpot.blogspot.in/2013/11/running-tomcat-maven-plugin-in-debug.html


I'll explain how to add showcase sample into the eclipse from git repository above then how to set the debugging environment step by step. 


1. Make a eclipse project


  • Select Import from the context menu in the Navigator or Project Explorer
  • Navigate to the Git folder and select "Projects from Git"
  • Select "Clone URI" from the repository source page
  • Paste the following URI into the URI 
https://github.com/hdiv/hdiv-spring-mvc-showcase.git
  • Then click Next Until "Select a wizard to use for importing projects" page is shown
  • Select "Import s general project"
In my case, other option could not import any project
  • Finally click Finish.

2. Set up the debug environment for this sample

  • Open the context menu by clicking the right mouse button on the Navigator or Project explorer
  • Go to the "Debug As" menu and select the "Debug configurations..."
  • Select "Maven Build" like the following


  • Click the right mouse button on the "Maven Build" then select "New"
  • The new configuration will be made like the following then enter name as "Debug tomcat"


  • It's time to specify "Base directory". Click "Browse Workspace" and select "hdiv-spring-mvc-showcase" as shown in the following figure.


  • Then click the Source tab and click "Add" like the following


  • Select Project like the figure above then click OK. and select "hdiv-spring-mvc-showcase".
  • Finally press the "Debug" button. 

That's all. If you meet some error, try to build maven project then start debugging. If you finished all the steps above, you can easily start debugging by clicking the menu like the following:














2015. 2. 2. 23:46

Spring Framework Reference Documentation 4.1.4 RELEASE

Here is the official spring framework reference document:



spring-framework-reference.pdf


http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/pdf/spring-framework-reference.pdf