-----------------------------web.xml-----------------------------
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>chapter06_1</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 위치 또는 이름을 변경할 때 : /WEB-INF/spring/appServlet/servlet-context.xml-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/appServlet/mvc-context.xml
/WEB-INF/spring/appServlet/servlet-context.xml
</param-value>
</init-param>
</servlet>
<!-- 한글처리 -->
<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>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
-----------------------------mvc-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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="suffix" value=".jsp"></property>
<property name="prefix" value="/WEB-INF"></property>
</bean>
<bean id="sungJukController" class="com.controller.SungJukController"></bean>
</beans>
-----------------------------SungJukController.java-----------------------------
package com.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import com.bean.SungJukDTO;
@Controller
public class SungJukController {
@GetMapping(value = "/sungJuk/input.do")
public String input() {
return "/sungJuk/input";
}
@PostMapping(value = "/sungJuk/result.do")
public String result(@ModelAttribute SungJukDTO sungjukDTO, Model model) {
model.addAttribute("name", sungjukDTO.getName());
model.addAttribute("kor", sungjukDTO.getKor());
model.addAttribute("eng", sungjukDTO.getEng());
model.addAttribute("math", sungjukDTO.getMath());
return "/sungJuk/result";
}
}
-----------------------------input.jsp-----------------------------
<%@ 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>
<form action="result.do" method="post">
<table border="1">
<tr>
<th>이름</th>
<td>
<input type="text" name="name">
</td>
</tr>
<tr>
<th>국어</th>
<td>
<input type="text" name="kor">
</td>
</tr>
<tr>
<th>영어</th>
<td>
<input type="text" name="eng">
</td>
</tr>
<tr>
<th>수학</th>
<td>
<input type="text" name="math">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="계산">
<input type="reset" value="취소">
</td>
</tr>
</table>
</form>
</body>
</html>
-----------------------------result.jsp-----------------------------
<%@ 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>
<h1>*** ${name } 성적 ***</h1>
<br>
<h2>총점 : ${kor + eng + math }</h2>
<h2>평균 : ${(kor + eng + math)/3 }</h2>
</body>
</html>
@RequestMapping(value="sungJuk")하고 @GetMapping에(value= "input.do)가능
이렇게 하고 result에 sungJukDTO.name~~도 가능
- 웹 환경과 독립적인 빈 등록
- 디폴트 설정 파일 /WEB-INF/applicationContext.xml 으로 설정 된다
- 서비스계층과 데이터 액세스 계층을 포함해서 웹 환경과 직접 관련이 없는 모든 빈들을 여기에 등록 한다
→ 만약에 사용할 이름이 다르거나 설정파일이 여러 개인 경우
contextConfigLocation 파라미터를 추가해서 설정해주면 된다
특정 패키지 내의 클래스를 스캔하고 Annotation(@Component @Controller @Service @Repository)을 확인한 후 Bean 인스턴스로 생성한다.
이를 이용하면 @Autowired와 @Qualifier Annotation을 인식할 수 있다.
<context:component-scan /> 을 선언했다면 <context:annotation-config /> 를 선언할 필요가 없다.
ApplicationContext 안에 이미 등록된 Bean들의 Annotation을 활성화하기 위해 사용된다.
Component-scan과의 차이점은 이 설정은 Bean을 등록하는 작업을 수행하지 않는다는 것이다.
다 돌고 다시 와야된다.
-------------------------------pom.xml-------------------------------
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>chapter06_Web</groupId>
<artifactId>chapter06_Web</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<release>17</release>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.3</version>
</plugin>
</plugins>
</build>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.23</version>
</dependency>
<!-- Spring Web MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.23</version>
</dependency>
<!-- Connection pool -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.23</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.9.0</version>
</dependency>
<!-- Oracle -->
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc11</artifactId>
<version>23.2.0.0</version>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.13</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>3.0.2</version>
</dependency>
<!-- JSTL -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.28</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
-------------------------------web.xml-------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>chapter06_Web</display-name>
<!-- 웹과 독립된 WAC -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 웹과 관련된 WAC -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 위치 또는 이름을 변경할 때 : /WEB-INF/spring/appServlet/servlet-context.xml-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</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>
<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>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
-------------------------------servlet-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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF"/>
<property name="suffix" value=".jsp"/>
</bean>
<context:component-scan base-package="user.controller" />
<!-- Spring Web MVC를 하기 위해서 설정해야하는 값들을 자동으로 추가해 준다. -->
<!-- xml에서url패턴을 '/'줬기때문에 설정줘야함 -->
<mvc:annotation-driven />
<mvc:resources location="/WEB-INF/js/" mapping="/js/**"></mvc:resources>
</beans>
-------------------------------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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<context:component-scan base-package="user.service"/>
<context:component-scan base-package="user.dao"/>
<context:component-scan base-package="user.bean"/>
<context:component-scan base-package="spring.conf"/>
</beans>
-------------------------------UserController.java-------------------------------
package user.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import user.bean.UserDTO;
import user.service.UserService;
// servlet-context.xml안에
// <bean id="userController" class="user.controller.UserController"></bean>
// 설정 안하려면 @component
@Component
@Controller
public class UserController {
@Autowired
private UserService userService;
@GetMapping(value = "/user/writeForm")
public String writeForm() {
return "/user/writeForm";
}
@PostMapping(value = "/user/isExistId")
@ResponseBody // resolver 타지말고 jsp 바로 타라
public String isExistId(@RequestParam String id){
return userService.isExistId(id);
}
@PostMapping(value = "write")
@ResponseBody // resolver 타지말고 jsp 바로 타라
public void write(@ModelAttribute UserDTO userDTO) {
userService.write(userDTO);
}
@GetMapping(value = "/user/list")
public String list(@RequestParam(required = false, defaultValue = "1") String pg, Model model) { //(required = false, defaultValue = "1") ?pg=1 안쓰려고
model.addAttribute("pg", pg);
return "/user/list";
}
}
-------------------------------UserService.interface-------------------------------
package user.service;
import user.bean.UserDTO;
public interface UserService {
public String isExistId(String id);
public void write(UserDTO userDTO);
}
-------------------------------UserServiceImpl.java-------------------------------
package user.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import user.bean.UserDTO;
import user.dao.UserDAO;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDAO userDAO;
@Override
public String isExistId(String id) {
//DB
UserDTO userDTO = userDAO.isExistId(id); //UserDAO로 id를 갖고 보내버려라
if(userDTO ==null)
return "non_exist";
else
return "exist";
}
@Override
public void write(UserDTO userDTO) {
userDAO.write(userDTO);
}
}
-------------------------------UserDTO.java-------------------------------
package user.bean;
import org.springframework.stereotype.Component;
import lombok.Getter;
import lombok.Setter;
@Component
@Getter
@Setter
public class UserDTO {
private String name;
private String id;
private String pwd;
}
-------------------------------UserDAO.java-------------------------------
package user.dao;
import user.bean.UserDTO;
public interface UserDAO {
public UserDTO isExistId(String id);
public void write(UserDTO userDTO);
}
-------------------------------UserDAOMybatis.java-------------------------------
package user.dao;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import user.bean.UserDTO;
@Repository
@Transactional
public class UserDAOMybatis implements UserDAO {
@Autowired
private SqlSession sqlSession;
@Override
public UserDTO isExistId(String id) {
// return sqlSession.selectOne("userSQL.isExistId", id);
// getUser의 sql문장이 Mapper파일 안에서 이미 같아서 생성하지 않고 getUser씀
return sqlSession.selectOne("userSQL.isExistId", id);
}
@Override
public void write(UserDTO userDTO) {
sqlSession.insert("userSQL.write", userDTO);
}
}
-------------------------------userMapper.xml-------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="userSQL">
<insert id="write" parameterType="user">
insert into usertable values(#{name}, #{id}, #{pwd})
</insert>
<select id="getUserList" resultType="user">
select * from usertable
</select>
<select id="getUser" parameterType="String" resultType="user">
select * from usertable where id=#{id}
</select>
<update id="update" parameterType="java.util.Map">
update usertable set name=#{name}, pwd=#{pwd} where id=#{id}
</update>
<delete id="delete" parameterType="String">
delete usertable where id=#{id}
</delete>
<select id="isExistId" parameterType="String" resultType="user">
select * from usertable where id=#{id}
</select>
</mapper>
-------------------------------index.jsp-------------------------------
<%@ 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>
<h3>*** 메인화면 ***</h3>
<h4>
<p><a href="/chapter06_Web/user/writeForm">입력</a></p>
<p><a href="/chapter06_Web/user/list">출력</a></p>
<p><a>수정</a></p>
<p><a>삭제</a></p>
</h4>
</body>
</html>
-------------------------------writeForm.jsp-------------------------------
<%@ 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>
<style type="text/css">
table{
border-collapse: collapse;
}
th, td {
padding: 5px;
}
#writeForm div{
color: red;
font-size: 8pt;
font-weight: bold;
}
</style>
</head>
<body>
<form id="writeForm">
<table border="1">
<tr>
<th>이름</th>
<td>
<input type="text" name="name" id="name">
<div id="nameDiv"></div>
</td>
</tr>
<tr>
<th>아이디</th>
<td>
<input type="text" name="id" id="id">
<div id="idDiv"></div>
</td>
</tr>
<tr>
<th>비밀번호</th>
<td>
<input type="password" name="pwd" id="pwd">
<div id="pwdDiv"></div>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="button" value="입력" id="writeBtn">
<input type="reset" value="취소">
</td>
</tr>
</table>
</form>
<script src="http://code.jquery.com/jquery-3.7.0.min.js"></script>
<script type="text/javascript" src="../js/write.js"></script>
</body>
</html>
-------------------------------write.js-------------------------------
$(function(){
//입력
$('#writeBtn').click(function(){
$('#nameDiv').empty();
$('#idDiv').empty();
$('#pwdDiv').empty();
if($('#name').val() == ''){
$('#nameDiv').text('이름 입력해라고');
$('#name').focus();
}
else if($('#id').val() == ''){
$('#idDiv').text('아디 입력해라고');
$('#id').focus();
}
else if($('#pwd').val() == ''){
$('#pwdDiv').text('비번 입력해라고');
$('#pwd').focus();
}
else{
$.ajax({
type: 'post',
url: '/chapter06_Web/write',
data: $('#writeForm').serialize(),
success: function(){
alert("회원가입 완료")
},
error : function(e){
console.log(e);
}
});
}
});
//아이디 중복체크
$('#id').focusout(function(){
$('#idDiv').empty();
if($('#id').val() == ''){
$('#idDiv').text('먼저 아디 입력해라니깐?');
$('#id').focus();
}else{
$.ajax({
type: 'post',
url : '/chapter06_Web/user/isExistId',
data : 'id='+ $('#id').val(), //json = {'id' : $('#id').val()}
dataType : 'text',
success : function(data){
if(data == 'exist'){ //아이디 존재
$('#idDiv').text('사용 불가합니다.');
$('#idDiv').css('color', 'red');
}else if(data=='non_exist'){ //아이디 x
$('#idDiv').text('사용 가능합니다.');
$('#idDiv').css('color', 'blue');
}
},
error : function(e){
console.log(e);
}
});
}
});
});
너무 어려움으로 복습 필수