To demonstrate, I did a project. There is no Data Source Management in STS, so we will add the plug-in.
Check this figure out to understand the Spring Framework structure with MyBatis.
The first file that you need to set is pom.xml. This is for the configuration, so you must add the dependencies to use the libraries in the project.
Next, we need to take care of is web.xml. There are three excellent contents: the location of the servlet class, the servlet mapping, the connection to the servlet-context.xml, and UTF-8 encoding.
<servlet-class> and <servlet-mapping>
root-context.xml and servlet-context.xml
encoding : UTF-8
In the servlet-context.xml, you will see the base-package is myBatis1, and the root-context.xml is for database connection. In this file that I am demonstrating, there is nothing much in the root-context.xml, but
In the DeptDaoImpl.java, you will see the @Autowired annotation. This @Autowired annotation is for injecting the SQLs.
In the resources directory, there are configuration files.
In the configuration.xml, you will see three like the ones below.
<typeAlias>
<property>
<mapper resource>
This project needs six configuration files: pom.xml, web.xml, servlet-context.xml, root-context.xml, and configuration.xml.
Compare the mapper class in the Spring to the average MyBatis Model2 Mapper Class; it is way more straightforward in the Spring Framework. From Model2, when we print out the result, we use EL(Expression Language).
Spring Mapper Class
<?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="deptns">
<!-- Use type aliases to avoid typing the full classname every time. -->
<resultMap id="deptResult" type="dept">
<result property="deptno" column="deptno" />
<result property="dname" column="dname" />
<result property="loc" column="loc" />
</resultMap>
<select id="list" resultMap="deptResult">
select * from dept order by deptno
</select>
<select id="select" parameterType="int" resultType="dept">
select * from dept where deptno=#{deptno}
</select>
<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>
</mapper>
MyBatis Model2 Mapper Class
<?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="mymember">
<insert id="insert" parameterType="member">
insert into member0609 values(#{id},#{passwd},#{name},#{jumin1},#{jumin2},
#{mailid},#{domain},#{tel1},#{tel2},#{tel3},#{phone1},#{phone2},#{phone3},
#{post},#{address},#{gender},#{hobby},#{intro},sysdate)
</insert>
<select id="idcheck" parameterType="String" resultType="member">
select * from member0609 where id = #{id}
</select>
<update id="update" parameterType="member">
update member0609 set name=#{name}, jumin1=#{jumin1}, jumin2=#{jumin2},
mailid=#{mailid}, domain=#{domain}, tel1=#{tel1}, tel2=#{tel2}, tel3=#{tel3},
phone1=#{phone1}, phone2=#{phone2}, phone3=#{phone3}, post=#{post}, address=#{address},
gender=#{gender}, hobby=#{hobby}, intro=#{intro} where id = #{id}
</update>
<delete id="delete" parameterType="String">
delete from member0609 where id = #{id}
</delete>
</mapper>
In the configuration files, especially servlet-context.xml, you will see the interceptor settings like this:
Spring Interceptors are usedto intercept client requests and process them. Sometimes we want to intercept the HTTP Request and do some processing before handing it over to the controller handler methods.(Digital Ocean)
There are two ways to run interceptors: Inheriting abstract class HandlerInterceptorAdapter Class, or Inheriting interface HandlerInterceptor Interface.
In this class, we are using the latter way. Here, we are only using preHandle method, which is needed between the Dispatcher Servlet class and the Controller class.
In the if statement in preHandle method, it will load to the loginForm if there is no session.
Knowing which files are in which folder is crucial since the structure is more complex than other projects and we have to know where to put the correct files.
When you run the program, the web.xml file will be the first to read. There are basic settings in the web.xml.
Let's take a look at web.xml.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- Language Encoding -->
<filter>
<filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 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>
</web-app>
<servlet-name> is appServlet, and we can set or change the pattern.
<filter> and <filter-mapping> is for encoding Korean values into UTF-8 with the post method. Once you set the encoding here in the web.xml, you don't need to set the encoding in the other files. If the language you or your company use is not English, you always have to take care of encoding, but with Spring, it is the only thing you need to do.
web.xml is connected to servlet-context.xml and root-context.xml.
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.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.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<resources mapping="/css/**" location="/WEB-INF/css/" />
<resources mapping="/fonts/**" location="/WEB-INF/fonts/" />
<resources mapping="/js/**" location="/WEB-INF/js/" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.ch.hello" />
</beans:beans>
In servlet-context.xml, the configuration file of Spring, you will see the extension of the view files and the directory of the view files. It is set in InternalResourceViewResolver. You must save on this route otherwise it won't run.
Base-package has to be reversed
Controller classes are in the src-main-java-com-ch-hello. The classes have annotations.
In the HomeController.java, you see the @RequestMapping annotation with /hello, /color, and /gugu, and you can omit the slash.
HomeController.java
package com.ch.hello;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate);
return "home";
}
@RequestMapping("/color")
public String color(Model model) {
String[] color = { "red", "orange", "yellow", "green", "blue", "navy", "violet" };
int num = (int) (Math.random() * 7);
model.addAttribute("color", color[num]);
return "color";
}
@RequestMapping("/gugu")
public String gugu(Model model) {
int num = (int) (Math.random() * 8) + 2;
// int a = num / 0;
model.addAttribute("num", num);
return "gugu";
}
/*
* @ExceptionHandler(ArithmeticException.class)
* public String err() {
* return
* "arr-err"; }
*/
}
@RequestMapping(value = "/hello", method = RequestMethod.GET) -> this format is the original, but you can also write like this: @RequestMapping("/color").
In the controller classes, you must use at least one of the following annotations: @Controller, @RequestMapping, @RequestParam, or @ModelAttribute.
@Controller annotation is the most used annotation.
@RequestMapping annotation is to receive the client's request.
@Controller
public class HomeController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate);
return "home";
}
}
@RequestParam is to receive the name as a value, and its role is the same as request.getParameter("name").
@Controller
public class HomeController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(@RequestParam(“name”) String name, Model model) {
}
}
@ModelAttribute is for receiving the value with the DTO class.
@Controller
public class HomeController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(@ModelAttribute BoardDTO board, Model model) {
}
}
To demonstrate these concepts, I will show you an example.
The name value will be passed to the Dispatcher Servlet and Controller class.
PersonController.java(Controller Class) receives the name value with the @RequestMapping annotation. It used to be the Handler, but now the annotations take its role.
PersonController.java
package com.ch.hello;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class PersonController {
// String name = request.getParameter("name")
// @RequestParam("name") String name
@RequestMapping("/addr")
public String addr(@RequestParam("name") String name,
@RequestParam("addr") String addr,
Model model) {
model.addAttribute("name", name);
model.addAttribute("addr", addr);
return "addr";
}
@RequestMapping("/addr2")
public String addr2(@ModelAttribute Person p, Model model) {
System.out.println("name: "+ p.getName());
System.out.println("addr: "+ p.getAddr());
model.addAttribute("person", p);
return "addr2";
}
}
addr -> @RequestParam
To print out the values, we use EL.
addr.jsp -> @RequestParam
<%@ 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>${name }, your address is ${addr }.
</body>
</html>
Sometimes, the datatypes of the controller classes are not String type. We will see the example of it.
SampleController.java
package com.ch.hello;
import java.util.ArrayList;
import java.util.List;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SampleController {
@RequestMapping("/sample")
public SampleVo sample() {
SampleVo sv = new SampleVo();
sv.setMno(23);
sv.setFirstName("Meadow");
sv.setLastName("Cho");
return sv;
}
@RequestMapping("/list")
public List<SampleVo> list() {
List<SampleVo> list = new ArrayList<SampleVo>();
for (int i = 1; i <= 10; i++) {
SampleVo sv = new SampleVo();
sv.setMno(i);
sv.setFirstName("Dodo");
sv.setLastName("Cox" + i);
list.add(sv);
}
return list;
}
}
@RestController annotation is a new annotation from Spring version 4.0. The sample method has a DTO class in this controller class, and the list method has a List.
package service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.BoardDAO;
public class BoardListAction implements Action{
@Override
public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
System.out.println("BoardListAction");
int page=1;
int limit=10; /
if(request.getParameter("page")!=null) {
page = Integer.parseInt(request.getParameter("page"));
}
int startRow = (page-1) * limit + 1;
int endRow = page * limit;
List boardlist = null;
BoardDAO dao = BoardDAO.getInstance();
int listcount = dao.getCount();
// boardlist = dao.getList(startRow, endRow);
// boardlist = dao.getList(page);
// Map ----------------------------------
Map map = new HashMap();
map.put("start", startRow);
map.put("end", endRow);
boardlist = dao.getList(page);
// boardlist = dao.getList(map);
//-------------------------------------------------
System.out.println("listcount:"+listcount);
System.out.println("boardlist:"+boardlist);
int pageCount = listcount/limit + ((listcount%limit==0) ? 0:1);
int startPage = ((page-1)/10) * limit + 1;
int endPage = startPage + 10 - 1;
if(endPage > pageCount) endPage = pageCount;
request.setAttribute("page", page);
request.setAttribute("listcount", listcount);
request.setAttribute("boardlist", boardlist);
request.setAttribute("pageCount", pageCount);
request.setAttribute("startPage", startPage);
request.setAttribute("endPage", endPage);
//<c:forEach items="${}"> </forEach>
ActionForward forward = new ActionForward();
forward.setRedirect(false);
forward.setPath("/board/qna_board_list.jsp");
return forward;
}
}
DAO Class(List)
// List
public List getList(int page) throws Exception {
// public List getList(Map map) throws Exception {
List list = new ArrayList();
SqlSession session=getSession();
list = session.selectList("board_list", page);
return list;
}
// View +1
public void updateCount(int board_num) throws Exception{
SqlSession session = getSession();
session.update("board_updatecount", board_num);
}
Mapper Class(Main post)
<!-- page -->
<select id="board_list" parameterType="int" resultType="board">
select * from (select rownum rnum, board.* from (
select * from model22 order by board_re_ref desc,board_re_seq asc) board )
where rnum >= (#{page}-1) * 10 + 1 and rnum <= #{page}*10
</select>
<!-- Map -->
<!-- <select id="board_list" parameterType="Map" resultType="board">
select * from (select rownum rnum, board.* from (
select * from model22 order by board_re_ref desc,board_re_seq asc) board )
where rnum >= #{start} and rnum <= #{end}
</select> -->
qna_board_write.jsp
For the file attachment function, you need to include enctype="multiypart/form-date" in the form tag.
// New Post
if(command.equals("/BoardAddAction.do")) {
try {
action = new BoardAddAction();
forward = action.execute(request, response);
}catch(Exception e) {
e.printStackTrace();
}
// New Post form
}else if(command.equals("/BoardForm.do")) {
forward = new ActionForward();
forward.setRedirect(false);
forward.setPath("/board/qna_board_write.jsp");
BoardAddAction.java
package service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
import dao.BoardDAO;
import model.BoardBean;
public class BoardAddAction implements Action{
@Override
public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
System.out.println("BoardAddAction");
String path = request.getRealPath("boardupload");
System.out.println("path:"+path);
int size = 1024 * 1024; // 1MB
MultipartRequest multi =
new MultipartRequest(request,
path,
size,
"utf-8",
new DefaultFileRenamePolicy());
BoardBean board = new BoardBean();
board.setBoard_name(multi.getParameter("board_name"));
board.setBoard_pass(multi.getParameter("board_pass"));
board.setBoard_subject(multi.getParameter("board_subject"));
board.setBoard_content(multi.getParameter("board_content"));
board.setBoard_file(multi.getFilesystemName("board_file"));
BoardDAO dao = BoardDAO.getInstance();
int result = dao.insert(board);
if(result==1) {
System.out.println("insert");
}
ActionForward forward = new ActionForward();
forward.setRedirect(true);
forward.setPath("./BoardListAction.do");
return forward;
}
}
DAO Class (Main Post)
//Main Post(New post)
public int insert(BoardBean board) throws Exception {
int result=0;
SqlSession session = getSession();
result = session.insert("board_insert", board);
System.out.println("result:"+result);
return result;
}
Mapper Class(New Post)
<!-- New Post -->
<insert id="board_insert" parameterType="board">
insert into model22 values(model22_seq.nextval,#{board_name},
#{board_pass},#{board_subject},#{board_content},
#{board_file,jdbcType=VARCHAR},model22_seq.nextval,0,0,0,sysdate)
</insert>
package service;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.MemberDAO;
import model.MemberDTO;
public class Update implements Action{
@Override
public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
System.out.println("Update");
response.setContentType("text/html; charset=utf-8");
request.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
MemberDTO member = new MemberDTO();
member.setId(request.getParameter("id"));
member.setPasswd(request.getParameter("passwd"));
member.setName(request.getParameter("name"));
member.setJumin1(request.getParameter("jumin1"));
member.setJumin2(request.getParameter("jumin2"));
member.setMailid(request.getParameter("mailid"));
member.setDomain(request.getParameter("domain"));
member.setTel1(request.getParameter("tel1"));
member.setTel2(request.getParameter("tel2"));
member.setTel3(request.getParameter("tel3"));
member.setPhone1(request.getParameter("phone1"));
member.setPhone2(request.getParameter("phone2"));
member.setPhone3(request.getParameter("phone3"));
member.setPost(request.getParameter("post"));
member.setAddress(request.getParameter("address"));
member.setGender(request.getParameter("gender"));
String h="";
String[] h1 = request.getParameterValues("hobby");
for(String h2 : h1) {
h += h2+"-"; // h = "공부-게임-등산-"
}
member.setHobby(h);
member.setIntro(request.getParameter("intro"));
MemberDAO dao = MemberDAO.getInstance();
MemberDTO old = dao.getMember(member.getId());
// 비번 비교
if(old.getPasswd().equals(member.getPasswd())) { //비번 일치시
int result = dao.update(member);
if(result==1) System.out.println("회원수정 성공");
}else { //비번 불일치시
out.println("<script>");
out.println("alert('비번이 일치하지 않습니다.');");
out.println("history.go(-1);");
out.println("</script>");
out.close();
return null;
}
ActionForward forward = new ActionForward();
forward.setRedirect(false);
forward.setPath("/member/main.jsp");
return forward;
}
}
UpdateMember.java
package service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import dao.MemberDAO;
import model.MemberDTO;
public class UpdateMember implements Action{
@Override
public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
System.out.println("UpdateMember");
HttpSession session = request.getSession();
String id = (String)session.getAttribute("id");
System.out.println("id:"+id);
MemberDAO dao = MemberDAO.getInstance();
MemberDTO member = dao.getMember(id);
System.out.println("member:"+member);
String hobby = member.getHobby(); // "공부-게임-등산-"
String[] h = hobby.split("-");
request.setAttribute("member", member);
request.setAttribute("h", h);
ActionForward forward = new ActionForward();
forward.setRedirect(false); // dispatcher 방식으로 포워딩
forward.setPath("/member/updateform.jsp");
return forward;
}
}
Update part in DAO Class
// 회원 1명 정보 구하기 : 수정폼, 수정, 삭제
public MemberDTO getMember(String id) throws Exception{
SqlSession session = getSession();
MemberDTO member = session.selectOne("idcheck", id);
return member;
}
// 회원정보 수정
public int update(MemberDTO member) throws Exception{
int result = 0;
SqlSession session = getSession();
result = session.update("update", member);
return result;
}
package service;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import dao.MemberDAO;
import model.MemberDTO;
public class Delete implements Action{
@Override
public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
System.out.println("Delete");
response.setContentType("text/html; charset=utf-8");
request.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
String id = request.getParameter("id");
String passwd = request.getParameter("passwd");
MemberDAO dao = MemberDAO.getInstance();
MemberDTO old = dao.getMember(id);
// 비번 비교
if(old.getPasswd().equals(passwd)) { // 비번 일치시
int result = dao.delete(id);
if(result == 1) System.out.println("회원삭제 성공");
session.invalidate(); // 세션 삭제
}else { // 비번 불일치시
out.println("<script>");
out.println("alert('비번이 일치하지 않습니다.');");
out.println("history.go(-1);");
out.println("</script>");
out.close();
return null;
}
ActionForward forward = new ActionForward();
forward.setRedirect(false);
forward.setPath("/LoginForm.do");
return forward;
}
}
MemberDAO.java
// 회원 1명 정보 구하기 : 수정폼, 수정, 삭제
public MemberDTO getMember(String id) throws Exception{
SqlSession session = getSession();
MemberDTO member = session.selectOne("idcheck", id);
return member;
}
// 회원 탈퇴
public int delete(String id) throws Exception{
int result = 0;
SqlSession session = getSession();
result = session.delete("delete", id);
return result;
}
package service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.MemberDAO;
import model.MemberDTO;
public class MemberInsert implements Action{
@Override
public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
System.out.println("MemberInsert");
request.setCharacterEncoding("utf-8");
MemberDTO member = new MemberDTO();
member.setId(request.getParameter("id"));
member.setPasswd(request.getParameter("passwd"));
member.setName(request.getParameter("name"));
member.setJumin1(request.getParameter("jumin1"));
member.setJumin2(request.getParameter("jumin2"));
member.setMailid(request.getParameter("mailid"));
member.setDomain(request.getParameter("domain"));
member.setTel1(request.getParameter("tel1"));
member.setTel2(request.getParameter("tel2"));
member.setTel3(request.getParameter("tel3"));
member.setPhone1(request.getParameter("phone1"));
member.setPhone2(request.getParameter("phone2"));
member.setPhone3(request.getParameter("phone3"));
member.setPost(request.getParameter("post"));
member.setAddress(request.getParameter("address"));
member.setGender(request.getParameter("gender"));
String h = "";
String[] h1 = request.getParameterValues("hobby");
for(String h2 : h1) {
h += h2+"-"; // 공부-게임-
}
member.setHobby(h);
member.setIntro(request.getParameter("intro"));
MemberDAO dao = MemberDAO.getInstance();
int result = dao.insert(member);
if(result == 1) {
System.out.println("회원가입 성공");
}
ActionForward forward = new ActionForward();
forward.setRedirect(false);
forward.setPath("/member/loginform.jsp");
return forward;
}
}
Idcheck.java
package service;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.MemberDAO;
public class Idcheck implements Action{
@Override
public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
System.out.println("Idcheck");
request.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String id = request.getParameter("id");
System.out.println("id:"+ id);
MemberDAO dao = MemberDAO.getInstance();
int result = dao.idcheck(id);
System.out.println("result:"+ result); // 1 : 중복ID
// -1 : 사용가능한 ID
out.println(result); // 브라우저에 출력되는 값이 callback함수로 리턴된다.
return null;
}
}
DAO Class Sign up / Id Check parts
// 회원가입
public int insert(MemberDTO member) throws Exception{
int result=0;
SqlSession session = getSession();
result = session.insert("insert", member);
System.out.println("result:"+result);
return result;
}
// ID중복검사
public int idcheck(String id) throws Exception{
int result = 0;
SqlSession session = getSession();
MemberDTO member = session.selectOne("idcheck", id);
if(member != null) { // 중복 ID
result = 1;
}else { // 사용가능한 ID
result = -1;
}
return result;
}
Spring Framework was first founded by Rod Johnson in his book <Expert One-one-one J2EE Design and Development> and the sample framework in the book was developed to nowadays' Spring Java Framework. It is developed to lessen the complexity of developing applications.
There are a few characteristics of Spring Framework, such as Inversion of Contro, Dependency Injection, Aspect-Oriented Programming, and Model-View-Controller pattern.
Inversion of Control (IoC) is a design principle thatallows classes to be loosely coupled and, therefore, easier to test and maintain. Dependency Injection(DI) isa fundamental aspect of the Spring framework, through which the Spring container “injects” objects into other objects or “dependencies”. Aspect-Oriented Programming(AOP)helps break down the program's logic into several distinct parts called concerns.
Configuration
For the configuration on Eclipse, we will download Spring Tool Suit(STS) Program instead of adding a plugin.
Click the link below to download Spring Tools 4 for Eclipse.