thymeleaf, external_img

2024. 3. 12. 17:57Daily Codig Reminder

thymeleaf2__JPA_H2

package com.example.demo.controller;

@Controller
public class MainController {
	// 자동 index.html 부터 시작  주소는 / 
	@Autowired
	UserService service;

	
	@RequestMapping("/join")  //회원가입 폼
	public String join(){
		System.out.println("/join");
		return "joinForm";
	}
	
		@RequestMapping("/register")  //회원가입 
		public String register(User user){
			System.out.println("/register "+ user);
			service.save(user);//db insert 
			return "redirect:/";//index.html 
		}
	
	@GetMapping("/users")  //전체 목록
	public String getUsers(Model m) {
		List<User> users= service.findAll();
		System.out.println("users" + users);
		m.addAttribute("users", users);
		return "userList";
	}
	@GetMapping("/json/users")
	@ResponseBody
	public List<User> JsonUsers() {//Json데이터
		List<User> users= service.findAll();
		System.out.println("JsonUsers users" + users);		
		return users;
	}
	
	@GetMapping("/users/{id}")  //get 사원한명찾기
	public String findUser(@PathVariable("id") int id, Model m) {		
		System.out.println("findUser id" + id);
		Optional<User> user= service.findById(id);
		m.addAttribute("user", user.get());
		return "userDetail";
	}
	
	@PostMapping("/users/{id}")  //get 사원한명찾기
	public String updateUser(User user) {		
		System.out.println("update user" + user);
		service.update(user);		
		return "redirect:/";
	}
	
	@GetMapping("/users/{id}/delete")
	public String delete(@PathVariable int id) {
		service.delete(id);
		return "redirect:/users";
	}
	
	@GetMapping("/json/users/{id}")  //get 사원한명찾기
	@ResponseBody
	public Optional<User> jsonfindUser(@PathVariable("id") int id, Model m) {		
		System.out.println("findUser id" + id);
		Optional<User> user= service.findById(id);
		//m.addAttribute("user", user.get());
		return user;
	}

}

 

@Entity
public class User {
	//Id컬럼지정, db서버의 키 값을 지정
	@Id@GeneratedValue(strategy = GenerationType.IDENTITY)
	 int id;
	 String name;
	 String address;

 

 

package com.example.demo.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.example.demo.domain.User;

public interface JpaUserRepository extends JpaRepository<User,Integer> {
		//JpaRepository를 이용하여 Spring에서 구현한다.
		//구현을 위한 코드를 개발자가 아닌 Spring이 처리한다.
		//User 클래스를 Entity로 지정하고, Id/Key 의 데이터 타입을 Integer로 지정한다.
}

 

 

package com.example.demo.service;

import java.util.List;
import java.util.Optional;

import com.example.demo.domain.User;

public interface UserService {
	public User save(User user);
	public List<User> findAll();
	public Optional<User> findById(int id);
	public User update(User user);
	public void delete(int id);
}

 

 

package com.example.demo.service;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.demo.domain.User;
import com.example.demo.repository.JpaUserRepository;

@Service
public class UserServiceImpl implements UserService{
	@Autowired
	private JpaUserRepository repository;
	//Spring Boot에서는 자동 생성 후 @Autowired 없이 생성자에서 자동 주입됨
	public UserServiceImpl(JpaUserRepository repository) {
		super();
		System.out.println("UserServiceImpl 생성자 자동호출 "+ repository);
		this.repository = repository;
	}
	
	public User save(User user) {
		return repository.save(user);
	}
	
	public List<User> findAll(){
		return repository.findAll();
	}
	public Optional<User> findById(int id){
		return repository.findById(id);
	}
	public User update(User user) {
		return repository.save(user);
	}
	public void delete(int id) {
		 repository.deleteById(id);
	}

	public JpaUserRepository getRepository() {
		return repository;
	}

	public UserServiceImpl() {
		super();
		// TODO Auto-generated constructor stub
	}

	

	public void setRepository(JpaUserRepository repository) {
		this.repository = repository;
	}

}

 

#아래 데이터소스 연결 정보를 제공하면 정보를 바탕으로 DataSource를 생성한다.
#아래 데이터소스 연결 정보가 없는 경우에는 H2, HSQL, Derby 등의 
#Embeded Database 기능을 제공하는 Database를 사용할 경우 내장 DB를 이용하도록 자동설정한다.
#단, 해당 Database의 Driver가(*.jar) 클래스패스에 존재할 경우에만 
#자동설정으로 해당 Driver를 이용하기 때문에 Driver가 경로상에 존재해야 된다.
#즉, 아래 4가지의 정보를 기술하면 외부 DB를 이용하고 기술하지 않으면 내부(메모리) DB를 이용한다.
#내부 DB와 외부 DB를 이용하는 두 경우 모두 schema.sql을 제공하지 않으면 Domain(Entity)를 이용하여 테이블을 유추하여 생성한다.
spring.datasource.url=jdbc:h2:tcp://localhost/~/test
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

server.port=8090
#server.servlet.context-path=/app
# 주소는 / 이됨


#ddl-auto 기능 create, create-drop, none, update, validate
#create :해당 테이블 drop 후 create
#create-drop :create와 같으나 종료시점에 테이블 drop
#update:변경분만 반영
#none :사용하지않음
#validate: 앤티티와 테이블이 정상매핑되었는지만 확인
#운영장비에서는 create,create-drop, update 사용하면 안됨
#h2 database의 경우 create가 기본으로 설정됨
spring.jpa.hibernate.ddl-auto=none
#SQL 실행정보출력
spring.jpa.show-sql=true
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

 

 

<!--index-->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Hello Spring Template!!!</h1>
<a href="/join">회원가입</a>
<a href="/users">유저리스트</a>
<a href="/json/users">유저리스트[json]</a>
</body>
</html>

 

 

<!DOCTYPE html>
<!--join-->
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>welcome join!!!</h2>
<form action="/register" method="post">
	<label>이름</label>
	<input type="text" name="name"><br>
	<label>주소</label>
	<input type="text" name="address"><br>
	<input type="submit" th:value="'회원가입'">
	<input type="reset" value="취소">
</form>
</body>
</html>

 

 

<!DOCTYPE html>
<!--userdetail-->
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>사원정보수정</h2>
<form method="post">   <!-- action 주소는 post방식의  user/{id} 가 됨 -->
<div th:object="${user}">
	<input type="hidden" name="id" th:value="*{id}">
	<table border="1">
		<tr>
			<th>아이디</th>
			<th th:text="*{id}"></th>
		</tr>
		<tr>
			<td>이름</td>
			<td>
				<input type="text" name="name" th:value="*{name}" th:placeholder="*{name}">
			</td>
		</tr>
			<tr>
			<td>주소</td>
			<td>
				<input type="text" name="address" th:value="*{address}" th:placeholder="*{address}">
			</td>
		</tr>
			<tr>
			<td><input  type="submit" value="update user"></td>
			<td>
				<input  type="reset" value="취소">
			</td>
		</tr>
	</table>
</div>
</form>
</body>
</html>

 

 

<!DOCTYPE html>
<!--userList-->
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>사원목록보기</h1>
	<table border="1">
	<thead>
	<tr>
		<th>번호</th>
		<th colspan="2">자세히 보기</th>
		<th>번호</th>
		<th>번호</th>	
	</tr>
	</thead>
	<tbody>
	<tr th:each="user : ${users} ">
		<td th:text="${user.id}"></td>
		<td ><a th:href="@{|/users/${user.id}|}" th:text="[html]">수정</a></td>
		<td ><a th:href="@{|/json/users/${user.id}|}" th:text="[json]"></a></td>
		<td th:text="${user.name}"></td>
		<td th:text="${user.address}"></td>
		<td ><a th:href="@{|/users/${user.id}/delete|}">삭제</a></td>	
	</tr>
	</tbody>
	</table>
	<a href="/">처음으로 </a>
</body>
</html>

 

 

web_thyleaf_mybatis

package com.example.controller;


@Controller
public class MainController {
@Autowired
DBDao dao;
@Autowired
DBService service;
//@Autowired
//SqlSessionTemplate session;

//@RequestMapping("/test")
//@ResponseBody
//public String Test() {
//	System.out.println(service);
//	System.out.println(dao);
//	System.out.println(session);
//	return"list";
//}
	@GetMapping("/list")
//	@ResponseBody
	public String list(Model m) {
		List<Dept> allData  = service.list();
		System.out.println(allData);
		m.addAttribute("allData",allData);
		return "list";
		//list.html
	}
	@RequestMapping("/insertForm")
	public String insertForm() {
		return "addForm";
		//addForm.html
	}
	@RequestMapping("/insert")
	public String insert(Dept dept) {
		System.out.println("insert>>>insert"+dept);
		service.insert(dept);
		return "redirect:list";
	}
	@RequestMapping("/deptRetrive")
	public String deptRetrive(@RequestParam int deptno, Model m) {
		System.out.println("deptRetrive>>>"+deptno);
		Dept dept =service.selectByDeptno(deptno);
		System.out.println(dept);
		m.addAttribute("dept",dept);
		return "deptRetrive";
	}
	@RequestMapping("/deptDelete")
	public String deptDelete(int deptno) {
		System.out.println("delete>>>"+deptno);
		service.delete(deptno);
		return "redirect:list";
	}
	@RequestMapping("/update")
	public String update(Dept dept) {
		System.out.println("update>>>"+dept);
		int n =service.update(dept);
		return "redirect:list";
	}
	@RequestMapping("/deptUpdateForm")
	public ModelAndView updateForm(@RequestParam int deptno) {
		System.out.println("update>>>"+deptno);
		Dept dept = service.selectByDeptno(deptno);
		System.out.println(dept);
		ModelAndView mav = new ModelAndView();
		mav.addObject("dept",dept);
		mav.setViewName("update");
		return mav;
	}
}

 

 

package com.example.service;

import java.util.List;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.dao.DBDao;
import com.example.dto.Dept;

@Service("myService")
public class DBOracleService implements DBService {
	@Autowired
	DBDao dao;
	@Autowired
	SqlSessionTemplate session;

	public void test() {
		System.out.println(dao);
		System.out.println(session);
	}

	@Override
	public List<Dept> list() {
		// TODO Auto-generated method stub
		return dao.list(session);
	}

	@Override
	public int insert(Dept dept) {
		// TODO Auto-generated method stub
		return dao.insert(session, dept);
	}

	@Override
	public int update(Dept dept) {
		// TODO Auto-generated method stub
		return dao.update(session, dept);
	}

	@Override
	public int delete(int deptno) {
		// TODO Auto-generated method stub
		return dao.delete(session, deptno);
	}

	@Override
	public Dept selectByDeptno(int deptno) {
		// TODO Auto-generated method stub
		return dao.selectByDeptno(session, deptno);
	}

	@Override
	public Dept select(int deptno) {
		// TODO Auto-generated method stub
		return dao.select(session, deptno);
	}


}

 

 

package com.example.service;

import java.util.List;

import com.example.dto.Dept;

public interface DBService {
public abstract List<Dept> list();
public abstract int insert(Dept dept);
public abstract int update(Dept dept);
public abstract int delete(int deptno);
public abstract Dept select(int deptno);
public abstract Dept selectByDeptno(int deptno);
}

 

 

package com.example.dao;

import java.util.List;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Repository;

import com.example.dto.Dept;

@Repository
public class DBOracleDAO implements DBDao {

	@Override
	public List<Dept> list(SqlSessionTemplate session) {
		// TODO Auto-generated method stub
		return session.selectList("DeptMapper.selectAll");
	}

	@Override
	public int insert(SqlSessionTemplate session, Dept dept) {
		// TODO Auto-generated method stub
		return session.insert("DeptMapper.insert", dept);
	}

	@Override
	public int update(SqlSessionTemplate session, Dept dept) {
		// TODO Auto-generated method stub
		return session.update("DeptMapper.update",dept);
	}

	@Override
	public int delete(SqlSessionTemplate session, int deptno) {
		// TODO Auto-generated method stub
		return session.delete("DeptMapper.delete",deptno);
	}

	@Override
	public Dept select(SqlSessionTemplate session, int deptno) {
		// TODO Auto-generated method stub
		return session.selectOne("DeptMapper.selectByDeptno", deptno);
	}

	@Override
	public Dept selectByDeptno(SqlSessionTemplate session, int deptno) {
		// TODO Auto-generated method stub
		return session.selectOne("DeptMapper.selectByDeptno", deptno);
	}

}

 

package com.example.dao;

import java.util.List;

import org.mybatis.spring.SqlSessionTemplate;

import com.example.dto.Dept;

public interface DBDao {

	List<Dept> list(SqlSessionTemplate session);

	int insert(SqlSessionTemplate session, Dept dept);

	int update(SqlSessionTemplate session, Dept dept);

	int delete(SqlSessionTemplate session, int deptno);

	Dept select(SqlSessionTemplate session, int deptno);

	Dept selectByDeptno(SqlSessionTemplate session, int deptno);

}

 

 

<?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="DeptMapper">

<!-- sql 삭제해서 맵퍼 작성할 것  -->
<select id="selectAll" resultType="com.example.dto.Dept"><!-- 결과를 Dept의 List형태로 -->

   select deptno,dname, loc from dept

  </select>
  <insert id="insert" parameterType="Dept"> 
  insert into dept (deptno, dname, loc)
  values (#{deptno}, #{dname}, #{loc})
  </insert>
  
  <update id="update" parameterType="Dept">
	 update dept
	 set dname = #{dname} , loc = #{loc}
	 where deptno = #{deptno}
	</update>
	
	<delete id="delete" parameterType="int">
	 delete from dept
	 where deptno = #{deptno}
	</delete>
		<delete id="delete2" parameterType="int">
	 delete from dept
	 where deptno =
	</delete>
<select id="selectByDeptno" resultType="com.example.dto.Dept"><!-- 결과를 Dept의 List형태로 -->

   select deptno, dname, loc from dept where deptno = #{deptno}

  </select>
</mapper>

 

 

addForm

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org/">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>부서추가화면</h1>
<form  th:action="@{insert}" method="post">
부서번호:<input type="text" name="deptno"><br>
부서이름:<input type="text" name="dname"><br>
지역: <input type="text" name="loc"><br>
<input type="submit" value="저장" ><br>
<a th:href="@{list}">부서목록</a>
</form>
</body>
</html>

 

deptRetrive

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org/">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body th:align="center">
<h1>dept 상세보기 화면</h1>
<table border="1" th:align="center">
<tr>
    <td>부서번호</td>
    <td>부서명</td>
    <td>부서위치</td>

  </tr>
  <tr >
  <td><a th:href="@{deptRetrive(deptno=${dept.deptno}, dname=${dept.dname}, loc=${dept.loc})}" 
  th:text="${dept.deptno}"></a></td>
    <td th:text="${dept.dname}"></td>
    <td th:text="${dept.loc}"></td>
 
  </tr>
  
</table><br>
<center><a th:href="@{list}" th:text="부서목록으로가기"></a>
</center>
</body>
</html>

list

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org/">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body th:align="center">
<h1>게시글 목록</h1>
<table border="1" th:align="center">
<tr>
    <td>부서번호</td>
    <td>부서명</td>
    <td>부서위치</td>
    <td>삭제</td>
    <td>수정</td>
    <td>상세보기</td>
  </tr>
  <tr th:each="dept: ${allData}">
    <td th:text="${dept.deptno}"></td>
    <td th:text="${dept.dname}"></td>
    <td th:text="${dept.loc}"></td>
    <td><a th:href= "@{deptDelete(deptno=${dept.deptno})}" th:text="'삭제leaf'"></a></td>
    <td><a th:href= "@{deptUpdateForm(deptno=${dept.deptno})}" th:text="'수정leaf'"></a></td>
    <td><a th:href= "@{deptRetrive(deptno=${dept.deptno})}" th:text="'상세보기leaf'"></a></td>
  </tr>
  
</table><br>
<center><a th:href="@{insertForm}" th:text="'등록화면Leaf'"></a>
</center>
</body>
</html>

 

 

update

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org/">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>dept 수정화면</h1>
<form  th:action="@{update}" method="get">
부서번호:<input th:value="${dept.deptno}" type="text" name="deptno"><br>
부서이름:<input th:value="${dept.dname}" type="text" name="dname"><br>
지역: <input th:value="${dept.loc}" type="text" name="loc"><br>
<input th:attr="type='submit', value='전송'" ><br>
</form>
<hr>
<form  th:action="@{update}" method="post" th:object="${dept}">
부서번호:<input type="text" name="deptno" th:object="${deptno}"><br>
부서이름:<input type="text" name="dname" th:object="${dname}"><br>
지역: <input type="text" name="loc" th:object="${loc}"><br>
<input th:attr="type='submit', value='전송'" ><br>
</form>
</body>
</html>

#server
server.port=8090
server.servlet.context-path=/app
#datasource
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:xe
spring.datasource.username=scott
spring.datasource.password=tiger

#mybatis.
mybatis.mapper-locations=com/example/mapper/*.xml
mybatis.type-aliases-package=com.example.dto

 

external_img

package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MainController {

	@RequestMapping("/")
	public String main() {
		return "main";
	}
}

 

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>

</head>
<body>
main.jsp<br>
<img alt="" src="/app/test2/a.jpg" width="100" height="200">
</body>
</html>

 

 

package com.example.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
	System.out.println("webconfig 실행");
	registry.addResourceHandler("/test2/**").addResourceLocations("file:///C:/resource/");
}
}

 

 

#server
server.port=8090
server.servlet.context-path=/app
#view-resolver
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp

'Daily Codig Reminder' 카테고리의 다른 글

ECMA  (0) 2024.03.13
ECMA  (1) 2024.03.12
redirect,thymeleaf  (0) 2024.03.12
boot-mybatis  (0) 2024.03.12
boot-database  (0) 2024.03.11