본문 바로가기
Back-end/Spring Framework

spring lagacy project / 생성, 설정, 오류 처리, maven, mybatis | 히카리 cp

by javapp 자바앱 2022. 5. 6.
728x90

 

 

 

 

 

 

 

 

 

STS4 JAVA EE Tool 및 여러 Tools 설치

STS4 utf-8 설정

 

 


 

spring legacy project

 

 

STS 플러그인 설치 및 스프링 프로젝트 생성

[Spring] Spring Legacy Project 초기 설정

 

Java Build Path, Project Facets --> set java version 

 

 

pom.xml

	<properties>
		<java-version>11</java-version>
		<org.springframework-version>5.3.2.RELEASE</org.springframework-version>
		<org.aspectj-version>1.6.10</org.aspectj-version>
		<org.slf4j-version>1.6.6</org.slf4j-version>
	</properties>

메이븐 업데이트 하기

가끔 경로 이탈 할 경우 있음.

 

https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api

		<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>4.0.1</version>
			<scope>provided</scope>
		</dependency>

 

 

https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api

		<!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>javax.servlet.jsp-api</artifactId>
			<version>2.3.1</version>
			<scope>provided</scope>
		</dependency>

 

 

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>11</source>
                    <target>11</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>

 


 

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xsi:schemaLocation="http://java.sun.com/xml/ns/javaee; https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" version="2.5">
<!-- 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>/</url-pattern>
    </servlet-mapping>

    <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>
</web-app>

 

 


 

 

톰캣 설치

 

에러

The server cannot be started because one or more of the ports are invalid. Open the server editor and correct the invalid ports. 

 

 

 

component-scan 관련 에러

 

root-context.xml

<context:component-scan base-package="com.myspring.models"/>

에러

org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 33 in XML document from ServletContext resource [/WEB-INF/spring/root-context.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 33; columnNumber: 61; The prefix "context" for element "context:component-scan" is not bound.

 


 

데이터베이스 연결

DBMS : MySQL 8.0

 

JdbcTemplate 사용

<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.9.RELEASE</version>
</dependency>

 

MySQL Connector/J

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.21</version>
</dependency>

 

root-context.xml

	<bean class="org.springframework.jdbc.datasource.SimpleDriverDataSource" id="ds">
            <property value="com.mysql.cj.jdbc.Driver" name="driverClass"/>
            <property value="jdbc:mysql://localhost:3306/springtestdb?serverTimezone=Asia/Seoul" name="url"/>
            <property value="root" name="username"/>
            <property value="1111" name="password"/>
	</bean>

	<!-- template -->
	<bean class="org.springframework.jdbc.core.JdbcTemplate" id="template">
		<property name="dataSource" ref="ds"/>
	</bean>

 

 


 

mybatis

 

pom.xml

<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.7</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.2</version>
</dependency>

 

 

root-context.xml

	<bean id="ds"
		class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
		<property name="driverClass" value="com.mysql.cj.jdbc.Driver" />
		<property name="url"
			value="jdbc:mysql://localhost:3306/springtestdb?serverTimezone=Asia/Seoul&amp;
			useUnicode=true&amp;allowPublicKeyRetrieval=TRUE&amp;useSSL=false&amp;characterEncoding=UTF-8"></property>
		<property name="username" value="root" />
		<property name="password" value="3578" />
		
	</bean>
    
    <!-- mybatis -->
	<bean id="sqlSessionFactoryBean" 
	                  class="org.mybatis.spring.SqlSessionFactoryBean">
	                 <property name="dataSource" ref="ds"/>
		    <property name="configLocation" value="classpath:/Configuration.xml"/>
	</bean>
    
	<!-- 	sqlMapper는 SqlSessionTemplate를 통해서 -->
	<bean id="sqlMapper" class="org.mybatis.spring.SqlSessionTemplate">
	   <constructor-arg index="0" ref="sqlSessionFactoryBean" />
	</bean>

sqlMapper -> Configuration.xml(ConfigLocation)

 

MySQL 8.0 이후 부터 

allowPublicKeyRetrieval=true

driver error 해결

 

 

 

XML SqlSessionFactory 빌드하기 (My batis)

path: src/main/resources

Configuration.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>
	 <mappers>
	 	<mapper resource="Person.xml"/>
	  </mappers>
  </configuration>

명명공간에 대한 설명

    패키지 경로를 포함한 전체 이름을 가진 구문을 구분하기 위해 필수로 사용

    ex) com.mypackage.MyMapper.selectAllThings

 

 

Person.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="com.myspring.Person"> 
 <!-- 추가 -->
 <insert id="insertPerson" parameterType="com.myspring.vo.PersonVO">
  insert into person values(#{id},#{name},#{password},#{gender},#{job})
 </insert>
 
 <!-- 전체보기 -->
 <select id="allPerson" resultType="com.myspring.vo.PersonVO">
 select * from person
 </select>
 
 <!-- 개수 -->
 <select id="allCnt" resultType="int">
 select count(*) from person
 </select>
 
 <!-- 상세보기 -->
 <select id="viewPerson" 
  parameterType="String" 
  resultType="com.myspring.vo.PersonVO">
 select * from person where id= #{id}
  </select>
  <!-- 수정하기 -->
  <update id="updatePerson" parameterType="com.myspring.vo.PersonVO">
  update
  person
  set name=#{name}, gender=#{gender}, job=#{job}, password=#{password}
  where id=#{id}
  </update>
  <!-- 삭제하기 -->
  <delete id="deletePerson" parameterType="String">
  delete from person where id=#{id}
  </delete>
 
 </mapper>

 

 

 

실행 경로

 

insert.jsp

<form action="per_insert" method="post">

post 방식으로 Controller "per_insert" 호출

 

 

 

Controller.java

@Controller
public class HomeController {
	@Autowired
	private PersonService service; 
	
	
    @PostMapping("per_insert")
	public String insert(PersonVO person) {
		service.insert(person);
		return null;
	}
    
    ...

@Controller, @Autowired 태그 꼭 적어주기

비즈니스 유스케이스 기능 (person 정보를 저장한다.)

 

root-context.xml 에 component-scan 등록

<context:component-scan base-package="com.myspring.models"/>

 

 

 

PersonServiceImpl.java

@Service
public class PersonServiceImpl  implements PersonService{
  @Autowired
  private PersonDAOImpl dao;

	@Override
	public void insert(PersonVO person) {
		dao.dao_insert("insertPerson", person);  // insertPerson --> Person.xml , mapper의 insert id
	}

@Service, @Autowired 태그 꼭 적어주기

DB 접근  (person 정보를 DB에 삽입한다.)

Person.xml mybatis의 id = "insertPerson" 이라는 태그를 찾는다.

 

 

 

PersonDAOImpl.java

@Repository
public class PersonDAOImpl  implements PersonDAO{
  @Autowired
  private SqlSession sqlMapper;
  
	@Override
	public void dao_insert(String mid, PersonVO person) {
		sqlMapper.insert(mid, person); //mid = insertPerson
		
	}
    ...

 

 

 

Person.xml

 <mapper namespace="com.myspring.Person">
     <!-- 추가 -->
     <insert id="insertPerson" parameterType="com.myspring.vo.PersonVO">
      insert into person values(#{id},#{name},#{password},#{gender},#{job})
     </insert>

  </mapper>

 

public class PersonVO {
	private String id;
	private String name;
	private String password;
	private String gender;
	private String job;
    ...
}

table의 컬럼명과 VO(DTO)의 변수명이 같아야 된다.

 

 

 

 


 

 

데이터베이스

히카리cp

Mapper 클래스 사용

pom.xml

https://mvnrepository.com/artifact/com.zaxxer/HikariCP/3.4.5

<!-- https://mvnrepository.com/artifact/com.zaxxer/HikariCP -->
<dependency>
    <groupId>com.zaxxer</groupId>
    <artifactId>HikariCP</artifactId>
    <version>3.4.5</version>
</dependency>

 

root-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
	<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
		<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
		
		<property name="jdbcUrl"
			value="jdbc:mysql://localhost:3306/springtestdb?serverTimezone=Asia/Seoul&amp;
			useUnicode=true&amp;allowPublicKeyRetrieval=TRUE&amp;useSSL=false&amp;characterEncoding=UTF-8"></property>
		<property name="username" value="root" />
		<property name="password" value="3578" />
	</bean>
		
		<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
			<constructor-arg ref="hikariConfig"/>
		</bean>
		
<!-- 		mybatis  id= "dataSource" : ref -->
	<bean id="sqlSessionFactoryBean" 
	                  class="org.mybatis.spring.SqlSessionFactoryBean">
	                 <property name="dataSource" ref="dataSource"/>
	</bean>
</beans>
<!-- 	Namespaces check -->
	<mybatis-spring:scan base-package="com.guest.mapper"/>

1.  .jsp

		$.ajax({
			type:"post",
			url:"insert",
			contentType:"application/json;charset=utf-8",
			data: JSON.stringify(postString),
			success:function(resp){
				alert(resp);
			},
			beforeSend:showRequest,
			error:function(e){
				alert("e: "+e)
			}
		})//ajax

post , json 통신

 

 

Controller.java

@Controller
public class HomeController {
	@Autowired
	private GuestService service;
	
	@PostMapping("insert") // json 형태로 넘어 올때 @RequestBody로 받는다.
	@ResponseBody// 데이터 반환값
	public String insert(@RequestBody GuestVO guest, HttpServletRequest request) {
		guest.setIpaddr(request.getRemoteAddr());
		service.guestInsert(guest);
		return "success1";
	}
    ..

service.guestInsert(guest);

@RequestBody // json 타입 값을 받는다.

@ResponseBody// 데이터 반환값, 반환값이 jsp 페이지가 아닐때

 

 

GuestServiceImpl.java

@Service
public class GuestServiceImpl implements GuestService
{
	@Autowired
	private GuestRepository repository;
	
	@Override
	public void guestInsert(GuestVO guest) {
		repository.dao_guestInsert(guest);
	}
    ..

(비즈니스 유스케이스)

 

 

GuestRepositoryImpl.java

@Repository
public class GuestRepositoryImpl implements GuestRepository
{
	@Autowired
	private GuestMapper mapper; //mybatis spring이 바로 연결
	
	@Override
	public void dao_guestInsert(GuestVO person) {
		mapper.insert(person);
	}
    ...

(데이터베이스 접근)

 

 

GuestMapper.java

//sql, db 접근
//GuestRepositoryImpl 에서 메소드를 부른다.
public interface GuestMapper 
{
	//짧은 경우 바로 사용
	@Insert("insert into guest(name, content, grade, created, ipaddr) "
			+ " values(#{name}, #{content}, #{grade},now(), #{ipaddr})")
	public void insert(GuestVO guest);
}

or

GuestMapper.xml  (mybatis 사용)

<?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="com.guest.mapper.GuestMapper">
      <sql id="search">
        <where>
                    <if test="word !=null and filed=='name'">name like CONCAT('%',#{word},'%')</if>
                    <if test="word!=null and field =='content'">content like CONCAT('%',#{word},'%') </if>
        </where>
      </sql>

    <!--id =  함수명 : list -->
    <select id="list"  resultType="com.guest.model.GuestVO">
        select * from guest
        <include refid="search"/>
    </select>

     <select id="count" resultType="int">
        select count(*) from guest
        <include refid="search"/>
     </select>
 </mapper>

 

 

 

 


 

Lombok

pom.xml

<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.22</version>
    <scope>provided</scope>
</dependency>

lombok-1.18.22.jar
1.86MB

설치 참고

 

 


 

JSON 파싱

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.2.2</version>
</dependency>

 

.jsp

$("#btnModify").click(function(){
	data ={
			"num":$("#num").val(),
			"title":$("#title").val(),
			"content":$("#content").val(),			
	}
	
	$.ajax({
		type:"put",
		url : "/app07/update",
		contentType:"application/json;charset=utf-8",
		data :JSON.stringify(data),
		success:function(resp){
			location.href="/app07/view/${board.num}"
		},
		error:function(e){
			alert("실패: "+e)
		}
		
	})
})

data :JSON.stringify(data),   --> JSON 타입으로 데이터를 컨트롤러로 넘겼다.

 

 

HomeController.java

@Controller
public class HomeController {
	@Autowired
	private BoardService boardService;

	@PutMapping("update")
	@ResponseBody
	public String update(@RequestBody BoardDTO board) //json을 객체로
	{
		boardService.update(board);
		return "ok";
	}
    ...

public String update(@RequestBody BoardDTO board) //json을 객체로 자동으로 파싱

num, title, content 속성

 

BoardDTO.java

@Data
public class BoardDTO 
{
	private int num;
	private String writer;
	private String title;
	private String content;
	private Date  regdate;
	private int hitcount;
	private int replayCnt;
}

 

 

댓글