1.EL Expression Language

EL은 JSP에서 제공 지원됨.

자바코드를 사용하지않고 좀더 간편하게 출력을 지원해주는 도구. 

영역은 (page → request → session → application) 순이다.



2. JSTL Jsp Standard Tag Library

JSP는 자신만의 태그를 추가할 수 있는 기능을 제공하고 있는데요. 

<jsp:include>나 <jsp:usebean>과 같은 커스텀 태그처럼

연산이나 조건문이나 반복문인

if문, for문, DB를 편하게 처리할 수 있는것이 JSTL입니다.

사용법(선언) : <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>



1
2
3
4
5
6
7
8
9
10
<c:choose> // if else 문
    <c:when test="${not empty sessionScope.id }">    // if문, sessionScope영역에 id라는 값이 비어있지 않으면
        <li><a href="${pageContext.request.contextPath }/users/info.do">${sessionScope.id } 님</a></li>
        <li><a href="${pageContext.request.contextPath }/logout.do"> 로그아웃 </a></li>
                    // 경로는 pageContext.request.contextPath 를 쓴다.
    </c:when>
    <c:otherwise>    // else 문이랑 같음.
        <li><a href="javascript:showPopup()">회원가입/로그인</a></li>
    </c:otherwise>                  
</c:choose>
cs




cf) session 처리


1
2
3
4
5
    @RequestMapping("/home.do")
    public ModelAndView home(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.setAttribute("_RSA_WEB_Key_", privateKey); // session에 RSA 개인키를 세션에 저장
    }
cs


1. pom.xml 


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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.gura</groupId>
    <artifactId>step07</artifactId>
    <name>Step07_Cafe</name>
    <packaging>war</packaging>
    <version>1.0.0-BUILD-SNAPSHOT</version>
    <properties>
        <java-version>1.8</java-version>
        <org.springframework-version>4.0.0.RELEASE</org.springframework-version>
        <org.aspectj-version>1.6.10</org.aspectj-version>
        <org.slf4j-version>1.6.6</org.slf4j-version>
    </properties>
    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework-version}</version>
            <exclusions>
                <!-- Exclude Commons Logging in favor of SLF4j -->
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                 </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
                
        <!-- AspectJ -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>${org.aspectj-version}</version>
        </dependency>    
        
        <!-- Logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${org.slf4j-version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.15</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.mail</groupId>
                    <artifactId>mail</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.jms</groupId>
                    <artifactId>jms</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jdmk</groupId>
                    <artifactId>jmxtools</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jmx</groupId>
                    <artifactId>jmxri</artifactId>
                </exclusion>
            </exclusions>
            <scope>runtime</scope>
        </dependency>
 
        <!-- @Inject -->
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>
                
        <!-- Servlet -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    
        <!-- Test -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.7</version>
            <scope>test</scope>
        </dependency> 
        <!-- MyBatis 라이브러리 -->
          <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.8</version>
        </dependency>
          <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.0</version>
        </dependency>
        <!-- Spring JDBC 라이브러리 -->
          <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.0.0.RELEASE</version>
        </dependency>
        <!-- 파일업로드 처리를 위한 라이브러리 (SmartEditor 에서도 필요함)-->
          <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
          <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>                        
        <!--  json, xml 응답을 편하게 할수 있도록 도와 주는 라이브러리 -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.6.0</version>
        </dependency>
        <!-- Aop 용 라이브러리 -->
          <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>4.0.0.RELEASE</version>
        </dependency>
          <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.0</version>
        </dependency>
          <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.2.0</version>
        </dependency>               
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
 
cs



2. web.xml


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
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    
    <welcome-file-list>
        <welcome-file>home.do</welcome-file>
    </welcome-file-list>
    
    <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml</param-value>
    </context-param>
    
    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
 
    <!-- Processes application requests -->
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
        
    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    
    <!-- 한글 깨지지 않도록 Spring 인코딩 필터 정의하기  -->
    <filter>
        <filter-name>EncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <!-- Spring 인코딩 필터 맵핑하기 -->
    <filter-mapping>
        <filter-name>EncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>      
</web-app>
cs


3. servlet-context.xml


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
<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:c="http://www.springframework.org/schema/c"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    <!-- DB 접속 정보를 가지고 있는 문서 읽어들이기 -->
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location">
            <value>classpath:com/gura/step07/mybatis/db.properties</value>
        </property>
    </bean>
    <!-- DataSource 설정 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
        <property name="driverClass" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
    </bean>
    
    <!-- SqlSessionFactory 객체 -->
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation"
            value="classpath:com/gura/step07/mybatis/Configuration.xml"/>
    </bean>
    
    <!-- Dao 에 주입해줄 SqlSession 인터페이스를 구현한 
    SqlSessionTemplate 객체 -->
    <bean class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sessionFactory"/>
    </bean>    
    
    
    <!-- Multipart 폼 전송을 처리하기 위한 bean -->
    
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="10240000"/>
    </bean>
    
    <bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
        <property name="order" value="0"/>
    </bean>
    
    <mvc:annotation-driven/>
    
    <!-- 어노테이션 기반으로 Aop 적용하기 위한 설정 -->
    <aop:aspectj-autoproxy/>
    
    <context:component-scan base-package="com.gura.step07"/>
    <context:component-scan base-package="com.gura.step07.aspect"/>    
    <context:component-scan base-package="com.gura.step07.users.*"/>
    <context:component-scan base-package="com.gura.step07.cafe.*"/>
    <!-- View Page 설정 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
 
</beans>
cs



4. mybatis 


파일 첨부 다운로드 > 패키지 생성 후 복붙.

CafeCommentMapper.xml

CafeMapper.xml

Configuration.xml

db.properties

UsersMapper.xml


cf) com.kkk.clawring.mybatis 패키지 안에 복붙.


1. Jackson 파일 받기 


https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind


jackson 라이브러리란?

: json, xml 응답을 편하게 할 수 있도록 도와주는 라이브러리


2. servlet-context.xml

@ResponseBody 어노테이션 동작하도록 설정해준다.

@ResponseBody 란? 자바 객체를 HTTP 응답 몸체로 변환하는 데 사용


1
2
<!-- @ResponseBody 어노테이션이 동작 가능하도록 설정 -->
<mvn:annotation-driven/>
cs

3. 요청 처리 부분


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@RequestMapping("/json")
@RequestBody
public List<Map<String, Object>> json(){
    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    Map<String, Object> map1 = new HashMap<String, Object>();
    map1.put("prod_name""아이폰");
    map1.put("prod_img""/image.jpg");
    map1.put("prod_price""1,200만원");
    Map<String, Object> map2 = new HashMap<String, Object>();
    map1.put("prod_name""아이폰x");
    map1.put("prod_img""/ipone.jpg");
    map1.put("prod_price""2,600만원");
    list.add(map1);
    list.add(map2);
    return list;
}
cs


 다나와 에서 '잘만' 검색어로 상품검색할때 다나와에서는 상품리스트를 ajax통신으로 불러오게되어있다.







 크롬 개발자 도구에서 ajax 로딩파일을 찾음



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
 
public class crawling {
 
    public static void main(String[] args) {
        try {            
            Document doc = Jsoup.connect("http://search.danawa.com/ajax/getProductList.ajax.php")
                    .header("Origin""http://search.danawa.com")
                    .header("Referer""http://search.danawa.com/")
                    .data("query""잘만").post();
            
            Elements items = doc.select("li.prod_item");
            
            for (Element item : items) {
                System.out.println(item.html());
                System.out.println(" ");
            }            
        } catch (Exception e) {e.printStackTrace();}
    }
}
 
cs



POINT!

1. Jsoup.connect(url)  url 연결.

2. .header("request header ", "value") 값으로 대입.

3. .data("key", "value") 값 대입.

4. 여기서 post() 로 호출하는 거랑 get()의 차이가 있다.

5. HTML DOM 으로 css selector 를 구한다.


Spring MVC 프로젝트 환경설정 중 Error 상황.



<<Error configuring application listener of class org.springframework.web.context.ContextLoaderListener>>


 ※  Maven > Update Project Configuration 실행시 maven 라이브러리 경로가 삭제되는 현상이 발생한다고 한다.





  1. 프로젝트 우클릭 > properties 
  2. Deployment Assembly > Add 버튼 > Java Build Path Entries > Maven Dependencies 선택 > Apply버튼





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
package mailsend;
 
import java.util.Properties;
 
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
 
public class mailsend {
    public static void main(String[] args) {
        final String user = "email@gmail.com";
        final String password = "password";
        
        Properties prop = new Properties();
        prop.put("mail.smtp.host""smtp.gmail.com");
        prop.put("mail.smtp.port"465);
        prop.put("mail.smtp.auth""true");
        prop.put("mail.smtp.ssl.enable""true");
        prop.put("mail.smtp.ssl.trust""smtp.gmail.com");
        
        Session session = Session.getDefaultInstance(prop, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, password);
            }
        });
        
        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(user));
            
            message.addRecipient(Message.RecipientType.TO, new InternetAddress("email@naver.com"));
            
            message.setSubject("메일 테스팅중....!");
            message.setText("메일 내용 테스트");
            
            Transport.send(message);
            System.out.println("message sent successfully....");            
            
            
        } catch (AddressException e) {
            // TODO: handle exception
            e.printStackTrace();
        } catch (MessagingException e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        
    }
}
 
cs



메일 수신 확인..





해당 글은 다시한번 정리해서 소스리뷰 및 설명을 포스팅 하겠습니다.


1. Jsoup 라이브러리 다운


  • https://jsoup.org/download 에서 최신버전 다운로드



2. 이클립스 라이브러리 추가




  • Eclipse Java project에서 Java Build Path - Add External JARs로 Jsoup.jar 라이브러리를 추가해준다.

  • 라이브러리 추가 하면 Package Explorer Referenced Libraries 폴더가 생성되면서 Jsoup 라이브러리가 import 된다.


3. 간단한 예제로 다나와 사이트의 오늘의 특가정보를 가져와보자.




  • 간단한 파싱을 위해 다나와에서 오늘의 특가를 파싱해본다.

  • 구글 크롬 개발자 도구를 통해 해당 뉴스 부분의 제목이나 class id를 확인 할 수 있다.

  • 개발자 도구를 통해 파싱하고 싶은 부분의 class id, tag 등을 먼저 찾는다.

  • Jsoup.connect() : 파싱할 웹 사이트 URL을 입력해 파싱 데이터가 Document 형태로 반환된다.





  • text()로 해당 li 태그의 title 값을 얻어올 수 있다.

  • getElementsByAttribute("href").attr("href")로 href 태그 값을 얻어와 해당 URL을 얻어올 수 있다.

  • URL을 다시 Jsoup.connect()해 링크를 들어간다면, 본문을 크롤링 할 수 있을 것이다.

  • element.toString()은 파싱한 태그 값 전체를 출력하고, element.text()는 파싱한 태그의 title 값만 출력할 수 있다.





N개의 숫자가 공백 없이 쓰여있다. 이 숫자를 모두 합해서 출력하는 프로그램을 작성하시오.

'웹개발 > 알고리즘' 카테고리의 다른 글

[알고리즘] for 문 이용하여 별 찍기  (0) 2017.12.19
11721번 열 개씩 끊어 출력하기  (0) 2017.10.21
1924번 2007년  (0) 2017.10.21
알파벳 소문자와 대문자로만 이루어진 길이가 N인 단어가 주어진다. 한 줄에 10글자씩 끊어서 출력하는 프로그램을 작성하시오.

'웹개발 > 알고리즘' 카테고리의 다른 글

[알고리즘] for 문 이용하여 별 찍기  (0) 2017.12.19
11720번 숫자의 합  (0) 2017.10.21
1924번 2007년  (0) 2017.10.21
오늘은 2007년 1월 1일 월요일이다. 그렇다면 2007년 x월 y일은 무슨 요일일까? 이를 알아내는 프로그램을 작성하시오.

'웹개발 > 알고리즘' 카테고리의 다른 글

[알고리즘] for 문 이용하여 별 찍기  (0) 2017.12.19
11720번 숫자의 합  (0) 2017.10.21
11721번 열 개씩 끊어 출력하기  (0) 2017.10.21

+ Recent posts