2020년 5월 26일 화요일

[Spring] To set tiles

What is Tiles?

 Tiles is a library that organizes screens on a single web page by attaching each area, such as attaching tiles. Areas on a web page are divided into size headers, content, left, Nav, and footers, and if you want to use them in common on multiple webpages, you can use them conveniently by specifying them as tiles tags.

pom.xml

dependency
<!-- Tiles -->
<dependency>
    <groupId>org.apache.tiles</groupId>
    <artifactId>tiles-core</artifactId>
    <version>3.0.7</version>
</dependency>
<dependency>
    <groupId>org.apache.tiles</groupId>
    <artifactId>tiles-jsp</artifactId>
    <version>3.0.7</version>
</dependency>

servlet-context.xml

View Resolver Settings
<!-- Resolves views selected for rendering by @Controllers to .jsp resources
    in the /WEB-INF/views directory -->
<beans:bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
    <beans:property name="order" value="2" />
</beans:bean>

<!-- Tiles 뷰 리졸버 -->
<beans:bean id="tielsViewResolver"
    class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <beans:property name="viewClass"
        value="org.springframework.web.servlet.view.tiles3.TilesView" />
    <beans:property name="order" value="1" />
</beans:bean>
<!-- Tiles 설정 파일 -->
<beans:bean id="tilesConfigurer"
    class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
    <beans:property name="definitions">
        <beans:list>
            <beans:value>/WEB-INF/tiles/tiles.xml</beans:value>
        </beans:list>
    </beans:property>
</beans:bean>
 In the existing blank setting, define the order attribute as 2, and paste the settings related to the tiles. where the order means the priority to be executed and in the value tag, type the path to the xml file to which you want to tile.

tiles.xml

 Create the /WEB-INF/tiles folder, as you entered in the path above, and create the tiles.xml file in it.

예시
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE tiles-definitions PUBLIC 
    "-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN" 
    "http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
<tiles-definitions>
    <definition name="default-layout" template="/WEB-INF/tiles/layouts/default-layout.jsp">
        <put-attribute name="head" value="/WEB-INF/tiles/components/head.jsp" />
        <put-attribute name="footer" value="/WEB-INF/tiles/components/footer.jsp" />
    </definition>
    
    <definition name="*/*" extends="default-layout">
        <put-attribute name="content" value="/WEB-INF/views/{1}/{2}.jsp" />
    </definition>
</tiles-definitions>
Type the path to the default-layout.jsp file to use the tiles tag as the default. Then enter the name of the tag to be used as a put-attribute tag, and the path to the jsp file. The content part is jsp that will be displayed on the screen by the controller.Because it means a file, write '*/*' in the name property and 'value' in the path using the replacement as shown above.

Jsp file

header.jsp
<!DOCTYPE html>
<html>
    <head>
        <!-- head내용 -->
        <meta charset="UTF-8">
        <title>이름</title>
        <link rel="stylesheet" href="<c:url value='/resources/css/reset.css'></c:url>">
        <link rel="stylesheet" href="<c:url value='/resources/css/style.css'></c:url>">
    </head>
    <body>

    </body>
</html>
footer.jsp
<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
    <!-- footer 내용 -->
    <footer id="footer">
    ....
    </footer>
    </body>
</html>
 main.jsp
<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <!-- content 내용 -->
        <div id="content">
        ...
        </div>
    </body>
</html>
 이 부분들은 tiles:insertAttribute 태그가 될 부분이기 때문에 head 부분만 내용을 작성합니다. footer.jsp, main.jsp 파일도 작성합니다. contents 내용을 담고 있는 main.jsp는 폴더를 하나 만들어서 그 폴더 안에 만들도록 합니다.

Default Layout file

default-layout.jsp
<%@ page pageEncoding="utf-8" session="false"%>
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>

<html>
    <head>
        <tiles:insertAttribute name="head" />
    </head>
    <body>
        <div class="container">
            <tiles:insertAttribute name="content" />
            <tiles:insertAttribute name="footer" />
        </div>
    </body>
</html>
 The default layout page is where you use the tile tag, where the jsp contents associated with the tile tag are linked to a single web page.

Controller file

HomeController.java
@Controller
public class HomeController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home() {
        
        return "main/main";
    }
}
  The '*/*' format was satisfied in the tile settings, so the main.jsp file will appear linked to the part pput-insertAttribute name=content//.

[Spring] To enable Spring Security

What is Spring Security?

 Spring security is a tool that makes it easier to implement technologies such as login features and administrator privileges. Traditionally, the developer had to manually create the logic using sessions and interceptors, but the spring security feature allows several settings to be implemented.

pom.xml

Setting the Spring Security Version
<!-- 스프링 시큐리티 버전 명시 -->
    <properties>
 <java-version>1.8</java-version>
 <org.springframework-version>5.1.4.RELEASE</org.springframework-version>
 <org.aspectj-version>1.9.2</org.aspectj-version>
 <org.slf4j-version>1.7.25</org.slf4j-version>
        <spring.security.version>4.1.3.RELEASE</spring.security.version>
    </properties>
 The version of the spring security uses 4.1.3 and the spring version must be higher than the version of the security.

dependency
<!-- Spring Security 사용을 위한 dependency -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>${spring.security.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${spring.security.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${spring.security.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
            <version>${spring.security.version}</version>
        </dependency>
<!-- Spring Security 사용을 위한 dependency -->

web.xml

 Write the following codes in the web.xml file in turn.
Adding a spring security settings file
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/spring/root-context.xml
        /WEB-INF/spring/security/security-context.xml
    </param-value>
</context-param>
Add a path to security-context.xml, which will be the setup file for spring security.

Listener
<!-- 세션이벤트 처리 관련 리스너 -->
<listener>
 <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>

Filter
<! -- 애플리케이션의 모든 요청을 스프링 시큐리티에서 처리 -->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


security-context.xml

 In web.xml, since you have routed the security key settings file to /WEB-INF/spring/security/security-context.xml, create a security folder to create a security-context.xml file and create the code below.
Settings
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:sec="http://www.springframework.org/schema/security"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security.xsd">
    
    <!-- 정적 리소스 파일 -->
    <sec:http pattern="/css/**" security="none" />
    <sec:http pattern="/img/**" security="none" />
    <sec:http pattern="/js/**" security="none" />
    
    <!-- 인터셉터, 권한, 로그인 기능 설정 -->
    <sec:http auto-config='true' use-expressions="true">
        <!-- 인터셉터 경로 설정 -->
        <sec:intercept-url pattern="/login" access="permitAll" />
        <sec:intercept-url pattern="/**" access="isAuthenticated()" />
        <!-- 폼 로그인 설정 -->
        <sec:form-login login-page="/login"
                        login-processing-url="/login/check"
                        default-target-url="/success"
                        username-parameter="userId" 
                        password-parameter="password"
                        authentication-failure-url="/login?error" 
                        always-use-default-target='true' />
        <!-- 로그아웃 설정 -->
        <sec:logout invalidate-session="true"
                    logout-url="/logout"   
                    logout-success-url="/login?logout" />
        <!-- 세션 관련 설정 -->
        <sec:session-management>
         <sec:concurrency-control max-sessions="1"
                                  expired-url="/login"
                                  error-if-maximum-exceeded="true"/>
        </sec:session-management>
        
        <!-- 보안 관련 설정 -->
        <sec:csrf/>
    </sec:http>
    
    <!-- 권한 관리 -->
    <sec:authentication-manager>
        <sec:authentication-provider>
            <sec:user-service>
                <sec:user name="user" password="1234" authorities="ROLE_USER"/>
            </sec:user-service>
        </sec:authentication-provider>
    </sec:authentication-manager>
</beans>
 There are a lot of tags, and the fact that you can set up basic settings such as interceptors, administrator rights, and log in with just this xml file is the advantage of spring security.

2020년 5월 23일 토요일

[Spring] Auto-injection of dependency using @Autowired, @Resource, @Inject

Dependency automatic injection 

 Previously, posts set xml files to inject dependency and wrote Java code. However, the dependency can be injected automatically using @Resource, @Autowired, and @Inject. As shown in the example below, we will only register the classes as empty and try to inject them automatically using the annotation.
example
@Configuration
public class Config {
 
    @Bean 
    public A a1() {
     return new A();
    }
    
    @Bean
    public A a2() {
     return new A();
    }
    
    @Bean
    public B b() {
     return new B();
    }
}

@Resource 

 @Resource is Java-supported annotations that look at the name of the object and explore which classes to inject depending on.
example
public class Normal {
 
    @Resource
    private A a1;
    
    public String method() {
     String str = a1.method();
    }
}
 When you attach @Resource to the a1 field, the object is injected into the Normal class as it is associated with a method named a1 in the class where you registered the bin. Because of the dependent injection, a1 can be used if you are in a normal class.

@Resource
private A b; // 오류 발생
 However, if you do this above, @Resource will connect to the b method that creates the B object, and the current type is declared as Class A, so it will be an error because the type does not match.

@Resource(name="a1")
private A b;
 In this case, you can correct the error by specifying a specific method by using the name attribute in the Annotation.

@Autowired, @Inject

 These two annunciations look at the type of object and explore and use the class to be injected. The only difference is that @Autowired is supported by the spring and @Inject is supported by Java.
example
public class Normal {
 
    @Autowired
    @Qulified("a1")
    private A a;
    
    public String method() {
     String str = a.method();
    }
}
 Since the type of field a is Class A, it is associated with the method that generates the object A among the methods registered as bins. Since there are two methods to create the A object, you have associated it with a specific method through the @Quired Annotation.

@Autowired
private A a1; // 오류

@Autowired
private A a2; // 오류
 Because @Autowired looks for objects to be injected as type, injecting multiple objects of the same type results in an error because they cannot find the target. To avoid errors, you can connect to a specific method with @Qualified to resolve them.