Skip to content
Snippets Groups Projects
Commit 3e4c8538 authored by Jingeun Lee's avatar Jingeun Lee
Browse files

update

parent e2bb62d8
No related branches found
No related tags found
No related merge requests found
Showing
with 304 additions and 14 deletions
package com.example.demo; package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.ApplicationContext;
import java.util.Arrays;
import com.example.demo.entity.Item;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;
import
org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.Resource;
@RestController @RestController
@SpringBootApplication @SpringBootApplication
public class DemoApplication { // @EntityScan(basePackageClasses = {Item.class})
public class DemoApplication{// implements CommandLineRunner{
// @Autowired
// private ApplicationContext appContext;
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args); SpringApplication.run(DemoApplication.class, args);
} }
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
Resource[] res = new
PathMatchingResourcePatternResolver().getResources("mapper/UserMapper.xml");
sessionFactory.setMapperLocations(res);
return sessionFactory.getObject();
}
} }
\ No newline at end of file
package com.example.demo.constant;
public enum Role {
USER, ADMIN
}
package com.example.demo.controller;
import com.example.demo.service.MemberService;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.example.demo.entity.Member;
import com.example.demo.dto.MemberDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.*;
import com.google.gson.JsonParser;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
@RestController
public class MemberController {
@Autowired
MemberService memberService;
public Member createMember(){
MemberDto memberDto = new MemberDto();
memberDto.setEmail("test@email.com");
memberDto.setName("홍길동");
memberDto.setAddress("서울시 마포구 합정동");
memberDto.setPassword("1234");
return Member.createMember(memberDto);
}
@RequestMapping(value = "/membertest", method = RequestMethod.GET)
public void membertest(){
Member member = createMember();
Member savedMember = memberService.saveMember(member);
System.out.println(member);
System.out.println(savedMember);
}
@RequestMapping(value = "/makeMember", method = RequestMethod.POST)
public String makeMember(@RequestBody String param){
System.out.println(param);
JsonElement element = JsonParser.parseString(param);
JsonObject object = element.getAsJsonObject();
String id = object.get("id").getAsString();
System.out.println("id : " + id);
String email = object.get("email").getAsString();
System.out.println("email : " + email);
String address = object.get("address").getAsString();
System.out.println("address : " + address);
String name = object.get("name").getAsString();
System.out.println("name : " + name);
String password = object.get("password").getAsString();
System.out.println("password : " + password);
return "OK";
}
@RequestMapping(value = "/get_member", method= RequestMethod.GET)
public String getMember(@RequestParam String id){
if(id.equals("user")){
JsonObject obj = new JsonObject();
obj.addProperty("name", "Jane");
obj.addProperty("age", "18");
obj.addProperty("success", "OK");
return obj.toString();
}
else{
JsonObject obj = new JsonObject();
obj.addProperty("success", "NOT OK");
return obj.toString();
}
}
}
\ No newline at end of file
...@@ -5,6 +5,7 @@ import org.springframework.web.bind.annotation.RequestMethod; ...@@ -5,6 +5,7 @@ import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
@RestController @RestController
public class TestController { public class TestController {
...@@ -15,15 +16,27 @@ public class TestController { ...@@ -15,15 +16,27 @@ public class TestController {
dto.setName("Jane"); dto.setName("Jane");
return dto; return dto;
} }
@RequestMapping(value = "/", method = RequestMethod.GET) @RequestMapping(value = "/productlist", method = RequestMethod.GET)
public String test(@RequestParam("id") String id){ public String productList(){
System.out.println(id); JsonObject obj1 = new JsonObject();
JsonObject obj = new JsonObject(); obj1.addProperty("item_nm", "수제 햄버거");
obj.addProperty("title", "산사와 아가싸"); obj1.addProperty("item_detail", "소고기 패티와 토마토가 들어 있는 햄버거");
obj.addProperty("content", "로맨틱 코메디"); obj1.addProperty("item_reg_date", "2022/04/22");
JsonObject data = new JsonObject(); obj1.addProperty("item_price", "4000");
data.addProperty("time", "토일 8시"); JsonObject obj2 = new JsonObject();
obj.add("data", data); obj2.addProperty("item_nm", "카레라이스");
return obj.toString(); obj2.addProperty("item_detail", "매운 3분 카레라이스");
obj2.addProperty("item_reg_date", "2022/03/10");
obj2.addProperty("item_price", "8000");
JsonObject obj3 = new JsonObject();
obj3.addProperty("item_nm", "라면");
obj3.addProperty("item_detail", "소고기 라면");
obj3.addProperty("item_reg_date", "2021/09/10");
obj3.addProperty("item_price", "1500");
JsonArray infoArray = new JsonArray();
infoArray.add(obj1);
infoArray.add(obj2);
infoArray.add(obj3);
return infoArray.toString();
} }
} }
\ No newline at end of file
package com.example.demo.controller;
import java.util.List;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.dao.UserDAO;
import com.example.demo.dto.UserDTO;
@RestController
@MapperScan(basePackages="com.example.demo.dao")//탐색할 패키시 설정
public class UserController {
@Autowired
private UserDAO userDAO;//UserDAO bean을 자동으로 주입
@RequestMapping("/users")
public List<UserDTO> users(@RequestParam(value="country", defaultValue ="")String country) throws Exception { //query String으로 country를 받도록 설정
final UserDTO param = new UserDTO(0, null, country);
final List<UserDTO> userList = userDAO.selectUsers(param);
return userList;
}
}
\ No newline at end of file
package com.example.demo.dao;
import java.util.List;
import com.example.demo.dto.UserDTO;
public interface UserDAO {
List<UserDTO> selectUsers(UserDTO param) throws Exception;
}
\ No newline at end of file
package com.example.demo.dto;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class MemberDto {
private String name;
private String email;
private String password;
private String address;
}
\ No newline at end of file
package com.example.demo.dto;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
@AllArgsConstructor // 자동으로 모든 매개변수를 받는 생성자를 생성
@Getter // Getter 생성
@Setter // Setter 생성
public class UserDTO {
private int seq;
private String name;
private String country;
}
\ No newline at end of file
package com.example.demo.entity;
import javax.persistence.*;
import com.example.demo.dto.MemberDto;
import com.example.demo.constant.Role;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Entity
@Table(name="member")
@Getter
@Setter
@ToString
public class Member {
@Id
@Column(name="member_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@Column(unique = true)
private String email;
private String password;
private String address;
@Enumerated(EnumType.STRING)
private Role role;
public static Member createMember(MemberDto memberDto){
Member member = new Member();
member.setName(memberDto.getName());
member.setEmail((memberDto.getEmail()));
member.setAddress((memberDto.getAddress()));
member.setPassword(memberDto.getPassword());
member.setRole(Role.USER);
return member;
}
}
\ No newline at end of file
package com.example.demo.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.demo.entity.*;
public interface MemberRepository extends JpaRepository<Member, Long>{
Member findByEmail(String email);
}
\ No newline at end of file
package com.example.demo.service;
import com.example.demo.entity.Member;
import com.example.demo.repository.MemberRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
@Service
@Transactional
@RequiredArgsConstructor
public class MemberService {
private final MemberRepository memberRepository;
public Member saveMember(Member member){
validateDuplicatetMember(member);
return memberRepository.save(member);
}
private boolean validateDuplicatetMember(Member member){
Member findMember = memberRepository.findByEmail(member.getEmail());
if(findMember != null){
System.out.println("이미 가입된 회원입니다.");
return false;
}
return true;
}
}
\ No newline at end of file
<?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.example.demo.dao.UserDAO"><!--namespace를 통해 UserDAO와 연결합니다. -->
<select id="selectUsers" parameterType="com.example.demo.dto.UserDTO" resultType="com.example.demo.dto.UserDTO">
SELECT `seq`, `name`, `country` FROM lab03
<if test='country != null and country != ""'>
WHERE country = #{country}
</if>
</select>
</mapper>
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Product</title>
<link rel="stylesheet"
href="/webjars/bootstrap/5.1.3/css/bootstrap.min.css">
<script src="/webjars/jquery/3.6.0/jquery.min.js"></script>
<script
src="/webjars/popper.js/2.9.3/umd/popper.min.js"></script>
<script
src="/webjars/bootstrap/5.1.3/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
37
$("button").click(function(){
$.ajax({
type: 'GET',
url: '/productlist',
success: function(data){
var array = JSON.parse(data);
for(i=0; i < array.length; i++){
var obj = array[i];
html = '';
html += '<tr>';
html += '<td>' + obj.item_nm + '</td>'
html += '<td>' + obj.item_detail + '</td>'
html += '<td>' + obj.item_reg_date + '</td>'
html += '<td>' + obj.item_price + '</td>'
html += '</tr>';
$("#tableBody").append(html);
}
}
});
});
});
</script>
</head>
<body>
<h1>상품 데이터 목록 출력</h1>
<button>조회</button>
<table class="table table-hover">
<thead class="thead-dark">
<tr>
<th>상품이름</th>
<th>상품상세설명</th>
<th>상품등록일</th>
<th>상품가격</th>
</tr>
</thead>
<tbody id="tableBody">
</tbody>
</table>
</body>
</html>
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment