ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 1. 기본세팅하기
    java/Spring블로그 만들기 2020. 7. 2. 21:00
    728x90

    [STS로 스프링 mvc프로젝트 생성후]

    1.web.xml에 먼저 한글 인코딩부터 설정한다

    <!-- 한글 인코딩 Start -->
    	<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>
    		<init-param>
    			<param-name>forceEncoding</param-name>
    			<param-value>true</param-value>
    		</init-param>
    	</filter>
    	<filter-mapping>
    		<filter-name>encodingFilter</filter-name>
    		<url-pattern>/*</url-pattern>
    	</filter-mapping>
    	<!-- 한글 인코딩 End -->

     

    2.pom.xml에 나는 db가 mariadb이고 mybatis를 사용할거기 때문에

    <!-- spring-test -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>${org.springframework-version}</version>
                <scope>test</scope>
            </dependency>
         
            <!-- log4jdbc-log4j2-jdbc4 -->
            <dependency>
                <groupId>org.bgee.log4jdbc-log4j2</groupId>
                <artifactId>log4jdbc-log4j2-jdbc4</artifactId>
                <version>1.16</version>
            </dependency>
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
    		<dependency>
    		    <groupId>org.mybatis</groupId>
    		    <artifactId>mybatis-spring</artifactId>
    		    <version>2.0.4</version>
    		</dependency>
    		<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
    		<dependency>
    		    <groupId>org.springframework</groupId>
    		    <artifactId>spring-jdbc</artifactId>
    		    <version>3.1.1.RELEASE</version>
    		</dependency>
    
    		
    		     <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    		<dependency>
    		    <groupId>org.mybatis</groupId>
    		    <artifactId>mybatis</artifactId>
    		    <version>3.5.4</version>
    		</dependency>
    				     
    				     <!-- https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client -->
    		<dependency>
    		    <groupId>org.mariadb.jdbc</groupId>
    		    <artifactId>mariadb-java-client</artifactId>
    		    <version>2.6.0</version>
    		</dependency>

    3.src/main/resources에서 우 클릭 > new > Other...클릭

    File name에 log4jdbc.log4j2.properties 적어주시고 Finish클릭

    log4jdbc.spylogdelegator.name=net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator

    추가 후 저장 이렇게 추가한다.

     

    4.src/main/webapp/WEB-INF/spring/root-context.xml을 열고 아래에

    Namespaces 클릭한후 빨간 박스에 있는것을 체크후 반영

    img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&fname=https%3A%2F%2Fk.kakaocdn.net%2Fdn%2F2yP3X%2FbtqwD2talYJ%2Fk34DS4hDZfoi9cWpnRptUK%2Fimg.png

    그리고 Namespaces 왼쪽에 Source탭에 들어갑니다.

    <!-- Root Context: defines shared resources visible to all other web components -->
    	<bean id="dataSource"
    
    		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    
    		<property name="driverClassName" value="org.mariadb.jdbc.Driver" />
    
    		<property name="url" value="jdbc:mariadb://localhost:3306/blog" />
    
    		<property name="username" value="root" />
    
    		<property name="password" value="rhkdtjd83**" />
    
    	</bean>
    	 <!-- Mybatis 연동 -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
             <property name="dataSource" ref="dataSource"></property>
             <property name="configLocation" value="classpath:/mybatis-config.xml"></property>
             <property name="mapperLocations" value="classpath:mappers/**/*Mapper.xml"/>
        </bean>
        
    	<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"
    
    		destroy-method="clearCache">
    
    		<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" />
    
    	</bean>
    	<!-- scan -->
        <context:component-scan base-package="kr.co.service"></context:component-scan>
        <context:component-scan base-package="kr.co.dao"></context:component-scan>
        <context:component-scan base-package="kr.co.vo"></context:component-scan>
        
        <context:component-scan base-package="kr.co.util"></context:component-scan>

    db접속정보나 파일 스캔 내용 mybatis 추가 

    (중요) 이렇게해도 페이지 404가 뜰 수 있다.

    그래서,

    src/main/resources에 mappers폴더를 하나만든후 boardMapper.xml파일을 하나만들어주고

    아래 코드를 추가해줍니다.

    <?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="boardMapper">
       
    </mapper>

    src/main/resources에 mybatis-config.xml 파일을 만들어주고 아래코드를 추가해줍니다.

    <?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>
      
    </configuration>

    5. 새로운 컨트롤러를 만들어서 url 매핑이 먼저 잘 되는지 확인한다.

    BoardController.java 생성

    package kr.co.contorller;
    
    import java.text.DateFormat;
    import java.util.Date;
    import java.util.Locale;
    
    import javax.inject.Inject;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    
    /**
     * Handles requests for the application home page.
     */
    @Controller
    @RequestMapping("/board/*")
    public class BoardController {
    	
    	private static final Logger logger = LoggerFactory.getLogger(BoardController.class);
    	
    	@RequestMapping(value="/getBoardList",method = RequestMethod.GET)
    	public String getBoardList() throws Exception{
    		logger.info("get register");
    		
    		return "board/getBoardList";
    	}
    }
    

     컨트롤러 생성후 아파치 재시작후 http://localhost:9090/yang4/board/getBoardList 접속테스트

    6.

    자 이제 dao service vo를 만들자

     

    오류)

    <!-- scan -->

    이게 오류난다. 아직 vo dao service 를 안만들어서 그런지 모르겠다.

    우선 dao service vo 를 만들자

     

    Board.VO.java

    public class BoardVO {
    	public int bid;
    
    	public String cate_cd;
    
    	public String title;
    
    	public String content;
    
    	public String tag;
    
    	public int view_cnt;
    
    	public String reg_id;
    
    	public String reg_dt;
    
    	public String edit_dt;
    }

    getter setter 만들고 tostring함수로 만든다

     

    boardMapper.xml

    <select id="getBoardList" resultType="kr.co.vo.BoardVO">
    		SELECT
    			BID, CATE_CD, TITLE, CONTENT, TAG, VIEW_CNT, REG_ID, REG_DT, EDIT_DT
    		FROM
    			TBL_BOARD
    	</select>

     

    게시글 리스트 가져오는 쿼리 추가

     

    BoardDAO.java (interface) 

    package kr.co.dao;
    import java.util.List;
    import kr.co.vo.BoardVO;
    
    public interface BoardDAO {
    	
    	public List<BoardVO> getBoardList() throws Exception;
    }
    

     

    BoardDAOImpl

    package kr.co.dao;
    
    import java.util.List;
    import javax.inject.Inject;
    import org.apache.ibatis.session.SqlSession;
    import org.springframework.stereotype.Repository;
    import kr.co.vo.BoardVO;
    
    
    
    @Repository
    public class BoardDAOImpl implements BoardDAO  {
    	
    	@Inject
    	private SqlSession sqlSession;
    
    	@Override
    	public List<BoardVO> getBoardList() throws Exception {
    
    		return sqlSession.selectList("boardMapper.getBoardList");
    		
    	}
    
    }
    

     

    BoardService

    package kr.co.service;
    
    
    import java.util.List;
    import java.util.Map;
    
    
    import kr.co.vo.BoardVO;
    
    public interface BoardService {
    	
    	public List<BoardVO> getBoardList() throws Exception;
    	
    }
    

     

    BoardServiceImlp

    package kr.co.service;
    
    import java.util.List;
    
    
    
    import javax.inject.Inject;
    import org.springframework.stereotype.Service;
    import kr.co.dao.BoardDAO;
    import kr.co.vo.BoardVO;
    
    @Service
    public class BoardServiceImpl implements BoardService{
    	
    	@Inject
    	private BoardDAO boardDAO;
    
    	
    
    	public List<BoardVO> getBoardList() throws Exception {
    
    		return boardDAO.getBoardList();
    
    	}
    
    }
    

     

    BoardController.java

    package kr.co.contorller;
    
    import java.text.DateFormat;
    import java.util.Date;
    import java.util.Locale;
    
    import javax.inject.Inject;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    
    import kr.co.service.BoardService;
    
    /**
     * Handles requests for the application home page.
     */
    @Controller
    @RequestMapping("/board/*")
    public class BoardController {
    	
    	private static final Logger logger = LoggerFactory.getLogger(BoardController.class);
    	
    	@Inject
    	private BoardService boardService;
    
    
    	@RequestMapping(value="/getBoardList",method = RequestMethod.GET)
    	public String getBoardList(Model model) throws Exception{
    		logger.info("get register");
    		model.addAttribute("boardList", boardService.getBoardList());
    		return "board/getBoardList";
    	}
    }
    

     

     

    컨트롤러 코드설명 : 

    먼저 @Inject 어노테이션으로 서비스 선언하고

    getBoardList 파라미터 url을 받았을떄 get메소드로

     

    Model model 객체를 인자값으로 받고

    model 객체에 boardService.getBoardList(); 함수의 결과값을 boardList라는 객체이름으로 담는다

    boardList객체를 getBoardList.jsp로 반환한다.

     

    Error creating bean with name 'boardController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private kr.co.service.BoardService kr.co.contorller.BoardController.boardService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [kr.co.service.BoardService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.inject.Inject()}

    에러뜸 자살각

     

    org.springframework.beans.factory.BeanCreationException:

    이런오류가 뜨는데....

    해결방법으로는)

    servlet.context.xml에서

    <!--scan-->추가해줘야함

    <context:component-scan base-package="kr.co.service"></context:component-scan>
        <context:component-scan base-package="kr.co.dao"></context:component-scan>
        <context:component-scan base-package="kr.co.vo"></context:component-scan>

    해결

    728x90

    'java > Spring블로그 만들기' 카테고리의 다른 글

    ㄷㄱ  (0) 2021.05.25
    2. view단에서 컨트롤러로 ajax 요청하기.  (0) 2020.07.14
Designed by Tistory.