[JSP] jstl - pageContext.request.contextPath 줄여 쓰기.

<c:set var="myContextPath" value="${pageContext.request.contextPath}"/>
${myContextPath}로 사용

 

댓글()

[Spring]spring 로그인 체크 하는 인터셉터

 

- AdminSessionInterceptor.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
package com.test.exam.interceptor;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
 
import com.test.exam.controller.AdminController;
 
 
//인터셉터를 등록하는 방법은 스프링 3.1이전과 3.2 이후는 다르다. 우리는 3.2이후 방법을 쓴다.
public class AdminSessionInterceptor extends HandlerInterceptorAdapter {
    private static final Logger logger = LoggerFactory.getLogger(AdminSessionInterceptor.class);
    
    @Override
    public boolean preHandle(HttpServletRequest request,
                                        HttpServletResponse response, 
                                        Object handler) throws Exception {
        HttpSession session = request.getSession();    
//        logger.debug(" what user login? : {}", session.getAttribute("whatUser"));
        if((session.getAttribute("whatUser") != "admin"
            || (session.getAttribute("sessionAdmin") == null)){
            response.sendRedirect(request.getContextPath()+"/");
            return false;
        }
        return super.preHandle(request, response, handler);
    }
}


-root-context.xml
1
2
3
4
5
6
7
8
9
10
11
12
    <!-- interceptor 설정. -->
    <interceptors>
    
        <!-- admin session interceptor 설정. -->
        <!-- 어드민 로그인을 체크하고 로그아웃 상태일 경우 메인페이지로 보내는 인터셉터를 등록. -->
        <interceptor>
            <!-- /admin/* 형태의 요청에 한해서만 인터셉트 적용 -->
            <mapping path="/admin/**/*"/>
            <beans:bean class="com.test.exam.interceptor.AdminSessionInterceptor"/>
        </interceptor>
        
    </interceptors>

인터셉터는 필터의 역할과 같다.

요청, 응답, 응답후의 상황엥 처리가 가능하도록 메소드가 존재한다.

preHandler는 요청시에 처리하도록 한다.



 - 위의 로그인 처리는 필터로 가능하나 사용하기에는 좀더 유용한것 같다.


댓글()

[Spring]Spring - MyBatis 연동하기.

http://blog.naver.com/sorlove0?Redirect=Log&logNo=20190380263



    필요한 라이브러리.


-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
          <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.26</version>
        </dependency>
 
        <!-- MyBatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.3</version>
        </dependency>
        
        <!-- MyBatis-Spring 연동 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.1</version>
        </dependency>
        
        <!-- Spring Tranjection -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>3.2.4.RELEASE</version>
        </dependency>
        
        <!-- commons dbcp -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
        
        <!-- Spring jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>3.2.4.RELEASE</version>
        </dependency>




- 스프링 빈 관리 설정파일에 다음 코드를 추가한다.

- root-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
    <!-- Scan all annotations exclude controller -->
    <!-- 컨트롤러 어노테이션을 제외한 모든 컴포넌트 어노테이션을 스캔. -->
    <context:component-scan base-package="com.exam.*">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    
    <!-- Transaction used annotation.-->
   <!-- 트랙잭션 처리를 어노테이션으로 사용.-->
    <tx:annotation-driven transaction-manager="transactionManager"/>
    
    <!-- 데이터소스 -->
   <!-- db에 접속하기 위한 커넥션 설정.-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/project" />
        <property name="username" value="root" />
        <property name="password" value="java1234" />
    </bean>
    
    <!-- 트랜잭션 관리자 -->
   <!-- 위의 트랜잭션 어노테이션 처리할때 이름을 transactionManager로 설정하면 다음 코드를 
          쓸 필요 없다.-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    
    <!-- 마이바티스 설정 -->
   <!-- 커넥션 설정으로 db에 직접 접속하는 sqlSession을 만드는 팩토리를 생성.-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="typeAliasesPackage" value="mybatis.test" />
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:/mybatis-config.xml"/>
        <property name="mapperLocations">
            <array>
                <value>classpath:/*.xml</value>
            </array>
        </property>        
    </bean>
    
   <!-- 팩토리로 sqlSession을 생성.-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" />
    </bean>
    


마이바티스 설정파일에 매퍼 파일을 등록할 필요 없이 여기서 바로 등록 가능하다.

댓글()

[Spring]spring ajax처리할때 간단하게 json으로 보내기

출처 - http://blog.naver.com/platinasnow?Redirect=Log&logNo=30177554726

 



JackSon 라이브러리를 추가.


- pom.xml
1
2
3
4
5
6
<!-- JackSon -->
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>



방법 1

xml 설정.


- servlet-context.xml
1
2
3
4
5
6
7
8
9
<!-- json 처리를 위한 MessageConverter -->
<beans:bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <beans:property name="messageConverters">
        <beans:list>
            <beans:bean 
                  class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
        </beans:list>
    </beans:property>
</beans:bean>




컨트롤러 사용


-Controller.java
1
2
3
4
5
6
7
8
9
10
11
12
13
@RequestMapping(value="/ajax/index/isCheckAdminLogin", method = RequestMethod.POST)
@ResponseBody
public String isCheckedAdminLogin(@ModelAttribute Admin admin){
    //Map<String, Object> map = new HashMap<String, Object>();
//    System.out.println(admin.getAdminId()+admin.getAdminPw());
    if(adminService.isCheckedAdmin(admin)){
        //map.put("isChecked", "true");
        return "true";
    }else{
        //map.put("isChecked", "false");
        return "false";
    }        
}


ajax 요청된 컨트롤러의 리턴 값은 json으로 변환되어 응답한다.


@ResponseBody 로 객체를 리턴해도 json으로 변환 해 준다.



방법 2


-Controller.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;
//
 
@RequestMapping(value="/ajax/index/isCheckAdminLogin", method = RequestMethod.POST)
public ModelAndView isCheckedAdminLogin(
        @ModelAttribute Admin admin){        
    ModelAndView modelAndView = new ModelAndView(new MappingJacksonJsonView());
    //Map<String, Object> map = new HashMap<String, Object>();
//    System.out.println(admin.getAdminId()+admin.getAdminPw());
    if(adminService.isCheckedAdmin(admin)){
        modelAndView.addObject("isChecked""true");    
    }else{
        modelAndView.addObject("isChecked""false");    
    }
    return modelAndView;
}


메이븐 추가한 후, ModelAndView를 리턴할때 매핑을 json으로 매핑하면 된다.

댓글()

[Spring]스프링 charactor 인코딩 필터 추가.

<!-- 인코딩 필더-->
 <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>

 <filter-mapping>
  <filter-name>encodingFilter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

출처 - http://www.java2go.net/blog/12

댓글()

[Mybatis]마이바티스 설정하기.

마이바티스MyBatis 홈페이지 https://code.google.com/p/mybatis/


iBatis       ->    MyBatis  가 되었다.

(apache)         (Google)


mybatis는 자바 소스안에 쿼리를 두지않고 따로 관리한다.

쿼리를 수정하게 되더라도 다시 재 컴파일 할 필요가 없다는 것이다.


1. 마이바티스 라이브러리 추가.


홈페이지에서 라이브러리 다운로드.

클래스패스에 라이브러리 추가.


혹은


메이븐 툴을 이용하여 의존성 주입.


2. 설정파일 생성.


- 설정파일 이름은 자신이 정하는 것이다.


-mybatis-config.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?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>
  
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/exam"/>
        <property name="username" value="root"/>
        <property name="password" value="java1234"/>
      </dataSource>
    </environment>
  </environments>
  
  <mappers>
    <mapper resource="AdminMapper.xml"/>
  </mappers>
  
</configuration>


AdminMapper.xml은 쿼리를 모아놓은 xml파일이다.

여러개를 만들 수 있으며 실행 될때 전부 합쳐진다. 관리상 나눈것이다.



-AdminMapper.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
<mapper namespace="AdminMapper">
    <select id="selectAdminById" resultType="domain.Admin" parameterType="String">
        SELECT admin_name as adminName
             , admin_id as adminId
             , admin_password as adminPw
        FROM ADMIN
        WHERE admin_id = #{adminId}
    </select>
</mapper>


select태그의 resultType은 쿼리를 실행 후 리턴할 데이터 형이고, parameterType은 입력하는 데이터 형을 말한다.


쿼리문 중 #{}를 이용하여 변수를 입력한다.


3.Dao에서 xml파일 호출, 실행.


-AdminDao.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
import java.io.IOException;
import java.io.InputStream;
 
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 
import domain.Admin;
 
public class AdminDao {
    SqlSessionFactory sqlSessionFactory = null;
    
    public AdminDao(){
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }
 
    public Admin selectAdminbyId(String adminId){
        SqlSession session = sqlSessionFactory.openSession();
        
        return session.selectOne("AdminMapper.selectAdminById", adminId);
    }
}


- InputStream에 xml파일 리소스를 넣고, 이 것으로 sqlSessionFactory를 만든다.


- dao메소드에 팩토리를 이용하여 sqlSession을 만들고(db에 접속하고),

따로 만든xml파일의 쿼리문을 호출(namespace + sql Id로 호출.), 입력할 변수가 잇다면 변수도 입력한다.


- 리턴 형은 위의 xml파일의 쿼리문의 resultType으로 지정 되어있다.

댓글()

[Spring]6. spring MVC 시작하기.

- xml 설정파일에 직접 <bean> 태그로 등록 할 수 있지만 spring 3.0 이후부터는 대부분이 @(어노테이션)을 사용하게 된다.


1. 만든 두개의 xml 파일에 다음과 같은 코드를 추가한다.


1
2
3
4
5
6
7
8
<beans>
 
    <context:component-scan base-package="com.controller">
   </context:component-scan>
    <!-- 지정한 패키지에 존재하는 어노테이션을 사용한 클래스를 
          전부 스캔하여 여기에 <bean> 형태로 등록한다 라는 뜻이다. -->
    
</beans>


-base-package= 안에 설정에 해당하는 (서블릿 설정파일이면 컨트롤러를, 리스너의 설정파일이면 모델단에 해당하는) 패키지 명이 들어간다.


2. @(어노테이션)을 이용해 컨트롤러, 서비스 등을 만든다.


- com.controller.HelloController.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
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
 
import com.service.HelloService;
 
@Controller
public class HelloController {
    
    @Autowired
    HelloService service;
    
    @RequestMapping("/hello.do")
    public String hello(Model model){
        System.out.println("sfefd");
        
        service.exe();
        
        //포워딩 시키고 싶은 데이터는 메소드의 매개변수로 모델을 받으면 된다.
        //모델에 속성을 추가하면 된다.
        //이렇게 만들어진 모델은 리퀘스트의 생명 주기와 같다. 
          //설정을 통해 어플리케이션, 세션으로 바꿀 수 있다.
        //jsp에서 호출을 할 때는 EL을 사용하면 된다.
        model.addAttribute("pw""1234");
        
        return "/WEB-INF/view/hello.jsp";
    }
}



-com.service.HelloService.java
 1
2
3
4
5
6
7
8
9
import org.springframework.stereotype.Service;
 
@Service
public class HelloService {
    public void exe(){
        System.out.println("service 실행");
    }
}
 




@Controller, @Service, @Repository는 @Component의 자식들이다. Component를 스캔하면 전부 스캔 되는 것이다.


@Controller는 이것만 쓰면은 기능을 못한다.

기능을 실행 하는 메소드에 @RequestMapping("/hello.do")라는 매핑 어노테이션이 필요하고,

 리턴으로 데이터를 받거나 보여줄 jsp 파일 위치가 들어가야 한다.


서비스를 호출 해야 한다면 서비스를 맴버 변수로 가지고, 위에 @Autowired 가 붙으면 자동으로 생성자나 setter를 이용한 di를 생성한다.

constructor 나 byType 혹은 byName 으로 생성자나 setter를 설정할 수 있다. 생성자나 setter가 존재 해야 가능하다.
























댓글()

[Spring]5. Spring MVC 설정하기.

- 스프링 mvc 프로젝트는 2개의 xml파일이 필요하다.

보통의 pojo객체를 관리하는 bean관리 xml, M

컨트롤러 bean을 관리하기 위한 xml. C


- 자바 빈 객체를 관리하는 xml은 톰캣 서버가 실행 될때 같이 실행 되어야 한다.

즉, 서버 실행과 동시에 spring 컨테이너가 같이 실행 되어야 한다.


- 서버가 실행 될 때를 감지하는 리스너와 spring bean 설정파일이 필요하다.

리스너는 스프링 라이브러리 안에 존재 하며, spring bean xml파일과 web.xml에 등록을 해야 한다.



1. 프로젝트에 스프링 라이브러리를 추가한다.


1-1. 일반적인 다이나믹 웹 프로젝트를 생성.



1-2. /WEB-INF/lib 폴더에 스프링 라이브러리를 추가.

- 스프링을 사용하려면 logging 라이브러리가 필요하다.





2. web.xml에 스프링 라이브러리 안에 있는 리스너와 프론트 서블릿을 추가한다.


2-1. 리스너를 추가한다.

- 리스너를 추가하는 이유는 스프링의 자바 빈을 관리하는 xml파일을 서버가 실행 할때 같이 로딩 시키기 위함.


-web.xml에 등록해야할 리스너와 xml설정파일 위치.
1
2
3
4
5
6
7
8
<listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
 
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

- 이 코드의 뜻은 이렇다.

* 서버 웹 어플리케이션안의 contextConfigLocation라는 변수에 /WEB-INF/applicationContext.xml를 넣는다.

* 서버가 실행할 때 ContextLoaderListener리스너가 실행 된다.

* 리스너는 contextConfigLocation변수 안에 존재하는

 설정 파일 패스와 이름을 호출하여 (/WEB-INF/applicationContext.xml 파일을 호출하여) 스프링 컨테이너를 실행 하게 된다.



2-2. 리스너가 로딩할 xml설정 파일을 만든다.

- 이름이 딱 정해진 것이 아니다. param-value에 자기가 정한대로 넣으면 된다.



- 스키마로 네임 스페이스를 정하는데 여기까진 beans, context를 추가 하면 된다.

나중에 더 추가 할 수 있다.




2-3. 프론트 서블릿을 추가한다. 

- 톰캣에서 만들어진 서블릿 기능을 스프링에서 만든 서블릿으로 위임하기 위함이다.


-web.xml에 등록해야 할 서블릿.

1
2
3
4
5
6
7
8
9
  <servlet>
    <servlet-name>mvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>mvc</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

-모든 .do가 붙은 요청은 이 서블릿이 받는다.


2-4. 서블릿이 사용할 xml 설정 파일을 만든다.

- 이 설정 파일에는 C, Controller bean을 관리한다.

- 반드시 위에서 지정한 servlet-name에 "-servlet.xml"라는 이름으로 파일을 만들어야 한다.

"mvc-servlet.xml"







댓글()

[Spring]4. scope

 

- scope : 같은 클래스를 주입할 때 주입할 때 마다 객체를 생성 할 것인가, 아니면 같은 객체를 계속 주입 시킬것인가를 설정.

* prototype : 모든 필요한 객체를 새로 생성하여 주입.
* singleton : 모든 필요한 객체를 한번 생성한 객체로 주입.
* request : 요청이 있을때마다 객체를 생성.
* session : 새로운 세션이 생성 될 때마다 객체를 생성.

1
2
3
4
5
6
7
8
9
10
11
12
public class MainTest {
 
    public static void main(String[] args) {
        Resource resource = new ClassPathResource("applicationContext.xml");
        BeanFactory factory = new XmlBeanFactory(resource);
        Controller c1 = factory.getBean(Controller.class);
        Controller c2 = factory.getBean(Controller.class);
        
        System.out.println(c1.hashCode()+" "+c1);
        System.out.println(c2.hashCode()+" "+c2);
    }
}



1
2
3
<bean     id         = "controller" 
            class    = "Controller"
            scope    = "singleton"/>


- scope에 설정하면 된다.

댓글()

[Spring]3. Spring DI - @(어노테이션)을 이용한 DI



- @(어노테이션)을 이용한 방법.


- Spring DI는 xml로 직접 소스를 작성하지 않고, @(어노테이션)을 써도 ApllicationContext.xml 파일에 자동으로 <bean>형태로 객체를 생성한다.

 

- context 스키마를 추가한다.


 

- xml설정 파일에 다음과 같은 코드를 추가 한다.


-applicationContext.xml

1
2
3
4
5
6
<beans>
 
    <context:component-scan base-package="com"></context:component-scan>
    <!-- 지정한 패키지에 존재하는 어노테이션을 사용한 클래스를 전부 스캔하여 여기에 등록한다 라는 뜻이다. -->
    
</beans>

 

클래스에 @Component 를 추가한다.

1
2
3
4
5
6
7
@Component
public class HelloService {
    public void exe(){
        System.out.println("service 실행");
    }
}
 


끝.

'웹 & 안드로이드 > JAVA & JSP' 카테고리의 다른 글

[Spring]5. Spring MVC 설정하기.  (0) 2013.10.22
[Spring]4. scope  (0) 2013.10.21
[Spring]2. Spring DI - xml파일을 이용한 DI  (0) 2013.10.21
[Spring] 1. Spring DI  (0) 2013.10.21
XML 이란?  (0) 2013.10.21

댓글()