728x90

출처 : 

환경설정

MyBatis 관련 환경파일 import

iot-servlet.xml 파일에 아래 내용 추가

	<!-- ========================= Import Definitions ========================= -->
	<import resource="iot-datasource.xml" />
	<import resource="iot-mybatis.xml" />

JDBC 설정

iot-datasource.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:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:security="http://www.springframework.org/schema/security"
       xsi:schemaLocation="http://www.springframework.org/schema/aop       http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
                           http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                           http://www.springframework.org/schema/context   http://www.springframework.org/schema/context/spring-context-2.5.xsd
                           http://www.springframework.org/schema/jee       http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
                           http://www.springframework.org/schema/tx        http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
                           http://www.springframework.org/schema/security  http://www.springframework.org/schema/security/spring-security-2.0.xsd">

	<!-- ========================= Resource Definitions ========================= --> 
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" >
		<property name="driverClassName" value="org.gjt.mm.mysql.Driver"/>
		<property name="url" value="jdbc:mysql://localhost:5614/iot_db?user=HR&useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull"/>
		<property name="username" value="HR"/>
		<property name="password" value="111111"/>
		<property name="maxActive" value="20"/>
		<property name="maxIdle" value="5"/>
		<property name="maxWait" value="2000"/>
		<!-- validationQuery:유효 검사용 쿼리( 1개 이상의 row를 반환하는 쿼리를 넣어주면 된다. ) -->
		<property name="validationQuery" value="select 1"/>
		<!-- testWhileIdle:컨넥션이 놀고 있을때 -_-; validationQuery 를 이용해서 유효성 검사를 할지 여부. -->
		<property name="testWhileIdle" value="true"/>
		<!-- timeBetweenEvictionRunsMillis:해당 밀리초마다 validationQuery 를 이용하여 유효성 검사 진행 -->
		<property name="timeBetweenEvictionRunsMillis" value="7200000"/>        
	</bean>
	
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"/>
	</bean>	

	<tx:annotation-driven transaction-manager="transactionManager" />

	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="transactionFactory">
			<bean class="org.apache.ibatis.transaction.managed.ManagedTransactionFactory" />
		</property>
	</bean>

	<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg index="0" ref="sqlSessionFactory" />
	</bean>
	
</beans>

MyBatis 설정

iot-mybatis.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:aop="http://www.springframework.org/schema/aop"
     xmlns:tx="http://www.springframework.org/schema/tx"
     xmlns:jdbc="http://www.springframework.org/schema/jdbc"
     xmlns:context="http://www.springframework.org/schema/context"
     xsi:schemaLocation="
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    <!-- enable component scanning (beware that this does not enable mapper scanning!) -->    
    <context:component-scan base-package="com.iot.service" />
 		
    <!-- enable autowire -->
    <context:annotation-config />

    <!-- enable transaction demarcation with annotations -->
    <tx:annotation-driven />

    <!-- define the SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="typeAliasesPackage" value="com.iot.domain" />
    </bean>

    <!-- scan for mappers and let them be autowired -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.iot.persistence" />
    </bean>
</beans>

Domain 객체

출처 : 혹시 DTO(VO) 작성하시나요? - SLiPP

프레임워크마다 VO, Command, Domain, DTO, TO 여러가지 이름으로 부르지만, MyBatis에서는 Domain이라고 부르고, Domain객체는 데이터베이스에서 조회된 데이터를 객체에 담아서 jsp에 실어 사용자에게 전달합니다.

package com.iot.domain;

import java.sql.Timestamp;

public class TbluserDomain {

	// pk
	private int seq;

	private String user_id;
	private String pass;
	private String nick;
	private Timestamp joindate;
	private String email;
	private String sex;

	private String delete_flag = "N";

	public void setSeq(int seq) {
		this.seq = seq;
	}

	public int getSeq() {
		return this.seq;
	}

	public void setUser_id(String user_id) {
		this.user_id = user_id;
	}

	public String getUser_id() {
		return this.user_id;
	}

	public void setPass(String pass) {
		this.pass = pass;
	}

	public String getPass() {
		return this.pass;
	}

	public void setNick(String nick) {
		this.nick = nick;
	}

	public String getNick() {
		return this.nick;
	}

	public void setJoindate(Timestamp joindate) {
		this.joindate = joindate;
	}

	public Timestamp getJoindate() {
		return this.joindate;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getEmail() {
		return this.email;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public String getSex() {
		return this.sex;
	}

	public String getDelete_flag() {
		return delete_flag;
	}

	public void setDelete_flag(String delete_flag) {
		this.delete_flag = delete_flag;
	}
}

Mapper 객체

출처 : mybatis-spring ? 마이바티스 스프링 연동모듈 | 매퍼 주입
MyBatis - MyBatis 3 | Mapper XML 파일

  • cache - 해당 명명공간을 위한 캐시 설정
  • cache-ref - 다른 명명공간의 캐시 설정에 대한 참조
  • resultMap - 데이터베이스 결과데이터를 객체에 로드하는 방법을 정의하는 요소
  • sql - 다른 구문에서 재사용하기 위한 SQL 조각
  • insert - 매핑된 INSERT 구문.
  • update - 매핑된 UPDATE 구문.
  • delete - 매핑된 DELEETE 구문.
  • select - 매핑된 SELECT 구문.

Mapper 인터페이스

package com.iot.persistence;

import java.util.List;
import java.util.Map;

import com.iot.domain.TbluserDomain;

public interface TbluserMapper {

	public TbluserDomain selectTbluser(Map<String, Object> params);

	public void insertTbluser(TbluserDomain tbluser);

	public void updateTbluser(TbluserDomain tbluser);

	public void deleteTbluser(Map<String, Object> params);

	public int getCount();

	public int getCountFormData(Map<String, Object> params);

	public List<TbluserDomain> listTbluser(Map<String, Object> map);

}

Mapper SQL Map 파일

  • cache - 해당 명명공간을 위한 캐시 설정
  • cache-ref - 다른 명명공간의 캐시 설정에 대한 참조
  • resultMap - 데이터베이스 결과데이터를 객체에 로드하는 방법을 정의하는 요소
  • sql - 다른 구문에서 재사용하기 위한 SQL 조각
  • insert - 매핑된 INSERT 구문.
  • update - 매핑된 UPDATE 구문.
  • delete - 매핑된 DELEETE 구문.
  • select - 매핑된 SELECT 구문.
<?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.iot.persistence.TbluserMapper">

  <!-- selectTbluser -->
  <select id="selectTbluser" parameterType="map" resultType="com.iot.domain.TbluserDomain">
    select seq
           ,user_id
           ,pass
           ,nick
           ,joindate
           ,email
           ,sex
      from tbluser
     where seq = #{seq}
  </select>

  <!-- updateTbluser -->
  <update id="updateTbluser" parameterType="com.iot.domain.TbluserDomain" statementType="PREPARED">
      update tbluser
        <trim prefix="SET" suffixOverrides=",">
          <if test="user_id != null">user_id = #{user_id, jdbcType=VARCHAR} ,</if>
          <if test="pass != null">pass = #{pass, jdbcType=VARCHAR} ,</if>
          <if test="nick != null">nick = #{nick, jdbcType=VARCHAR} ,</if>
          <if test="joindate != null">joindate = #{joindate, jdbcType=TIMESTAMP} ,</if>
          <if test="email != null">email = #{email, jdbcType=VARCHAR} ,</if>
          <if test="sex != null">sex = #{sex, jdbcType=VARCHAR} ,</if>
        </trim>
     where seq = #{seq}
  </update>

  <!-- insertTbluser -->
  <insert id="insertTbluser" parameterType="com.iot.domain.TbluserDomain" statementType="PREPARED">
      insert into tbluser(
        <trim suffixOverrides=",">
          <if test="seq != null">seq ,</if>
          <if test="user_id != null">user_id ,</if>
          <if test="pass != null">pass ,</if>
          <if test="nick != null">nick ,</if>
          <if test="joindate != null">joindate ,</if>
          <if test="email != null">email ,</if>
          <if test="sex != null">sex ,</if>
        </trim>
        ) values	(
        <trim suffixOverrides=",">
          <if test="seq != null">#{seq, jdbcType=decimal} ,</if>
          <if test="user_id != null">#{user_id, jdbcType=VARCHAR} ,</if>
          <if test="pass != null">#{pass, jdbcType=VARCHAR} ,</if>
          <if test="nick != null">#{nick, jdbcType=VARCHAR} ,</if>
          <if test="joindate != null">#{joindate, jdbcType=TIMESTAMP} ,</if>
          <if test="email != null">#{email, jdbcType=VARCHAR} ,</if>
          <if test="sex != null">#{sex, jdbcType=VARCHAR} ,</if>
        </trim>
        )
  </insert>

  <!-- deleteTbluser -->
  <delete id="deleteTbluser" parameterType="map" statementType="PREPARED">
      delete from tbluser
     where seq = #{seq}
  </delete>

  <!-- getCount -->
  <select id="getCount" resultType="int">
    select count(*)
      from tbluser
  </select>

  <!-- getCountFormData -->
  <select id="getCountFormData" parameterType="map" resultType="int">
    select count(*)
      from tbluser
      <trim prefix="WHERE" prefixOverrides="AND |OR ">
        <if test="searchstr != null">and user_id like '%${searchstr}%'</if>
      </trim>
  </select>

  <!-- listTbluser -->
  <select id="listTbluser" parameterType="map" resultType="com.iot.domain.TbluserDomain">
    select * 
      from tbluser
      <trim prefix="WHERE" prefixOverrides="AND |OR ">
        <if test="searchstr != null">and user_id like '%${searchstr}%'</if>
      </trim>
     limit #{defaultSize} offset #{offset}
  </select>

</mapper>

Service 객체

package com.iot.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import com.iot.domain.TbluserDomain;
import com.iot.persistence.TbluserMapper;

@Service
public class TbluserService {

  public final static int pagerowcnt = 25;

  @Autowired
  private TbluserMapper tbluserMapper;

  public TbluserDomain selectTbluser(double seq) {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("seq",seq);
    return tbluserMapper.selectTbluser(params);
  }

  public void insertTbluser(TbluserDomain tbluser) {
    tbluserMapper.insertTbluser(tbluser);
  }

  public void updateTbluser(TbluserDomain tbluser) {
    tbluserMapper.updateTbluser(tbluser);
  }

  public void deleteTbluser(double seq) {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("seq",seq);
    tbluserMapper.deleteTbluser(params);
  }

  public void deleteTbluser(Map<String, Object> params) {
    tbluserMapper.deleteTbluser(params);
  }

  public int getCount() {
  	return tbluserMapper.getCount();
  }

  public List<TbluserDomain> listTbluser(int page) throws Exception {
  	Map<String, Object> params = new HashMap<String, Object>();
    params.put("defaultSize", pagerowcnt);
    params.put("offset", pagerowcnt * (page-1));
    return tbluserMapper.listTbluser(params);
  }

}

UserController 클래스

package com.iot.ui.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.iot.domain.TbluserDomain;
import com.iot.service.TbluserService;

@Controller
public class UserController {
	
	@Autowired
	private TbluserService tbluserService;
	
	@RequestMapping(value="/userlist.iot", method = RequestMethod.GET)
	public String userlist(ModelMap modelMap) throws Exception 
	{
		List<TbluserDomain> ausers = tbluserService.listTbluser(1);
		modelMap.addAttribute("ausers", ausers);
		return "/UserList";
	}

	@RequestMapping(value="/userinfo.iot", method = RequestMethod.GET)
	public String userinfo(
			@RequestParam("seq") int seq,
			ModelMap modelMap) throws Exception 
	{
		TbluserDomain cu = tbluserService.selectTbluser(seq);
		modelMap.addAttribute("cu", cu);
		return "/UserInfo";
	}
	
}

사용자 목록 조회 JSP

UserList.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>현재 접속자 목록</h3>
<c:forEach items="${ausers}" var="u">
 <li><a href="<c:url value="/userinfo.iot"/>?seq=${u.seq}">${u.nick}</a></li>

</c:forEach>

</body>
</html>

사용자 조회 JSP

UserInfo.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

	<table border="1" cellspacing="0" cellpadding="0" align="center" >
    <tr>
    <td>닉네임</td><td>이메일</td>
     </tr>
 

		<tr>
			<td>${cu.nick}</td>
			<td>${cu.email}</td>
			<td></td>
		</tr>

	</table>

</body>
</html>
728x90
728x90

출처 : 스프링3(Spring3)MVC 연동 (3) - 서버값 웹페이지로 전송하기 :: 야근싫어하는 개발자

파라미터 전달 (클라이언트 -> 서버)

java 소스

	@RequestMapping(value = "/sum_result1.iot", method = RequestMethod.GET)
	public String sum_result1(
			@RequestParam("param1") int param1,
			@RequestParam("param2") int param2,
			ModelMap modelMap
			)

Get 파라미터 전달

http://localhost:7070/IotWebServer/sum_result1.iot?param1=2&param2=3

서버값 클라이언트에 전달 (서버 -> 클라이언트)

java 소스 - TestController.java

package com.iot.ui.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class TestController {

	@RequestMapping(value = "/sum_result1.iot", method = RequestMethod.GET)
	public String sum_result1(
			@RequestParam("param1") int param1,
			@RequestParam("param2") int param2,
			ModelMap modelMap
			)
	{
		// 결과값
		int sum_value = param1 + param2;
		
		// Model에 값 설정
		modelMap.addAttribute("param1", param1);
		modelMap.addAttribute("param2", param2);
		modelMap.addAttribute("sum_value", sum_value);
		
		// 전달 할 jap 페이지
		return "sum_result1";
	}
}

jsp 소스 - sum_result1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
</head>
<body>
 
스프링 테스트<br/><br/>
 
${param1} 더하기 ${param2} (은/는) ${sum_value} 입니다.
 
</body>
</html>

결과

@ResponseBody 어노테이션

출처 : @ResponseBody 이해하기

@ResponseBody 로 어노테이션이 되어 있다면 메소드에서 리턴되는 값은 View 를 통해서 출력되지 않고 HTTP Response Body 에 직접 쓰여지게 됩니다.

java 소스

	@ResponseBody
	@RequestMapping(value="/sum_result_body.iot", method = RequestMethod.GET)
	public String sum_result_body(
			@RequestParam("param1") int param1, 
			@RequestParam("param2") int param2
			) throws Exception 
	{
		return param1 + " + " + param2 + " = " + (param1 + param2);
	}

결과

@RequestParam 어노테이션

출처 : [Spring 3 - @MVC] @Controller #2 - 파라미터와 리턴 타입의 종류

옵션

  • value : 파라미터명
  • required : 필수 여부
  • defaultValue : required가 false인 경우 값이 없는 경우 기본값

java 소스

	@RequestMapping(value = "/sum_result2.iot", method = RequestMethod.GET)
	public String sum_result2(
			@RequestParam("param1") int param1,
			@RequestParam(value="param2", required=false, defaultValue="0") int param2,
			ModelMap modelMap
			)
	{
		// 결과값
		int sum_value = param1 + param2;
		
		// Model에 값 설정
		modelMap.addAttribute("param1", param1);
		modelMap.addAttribute("param2", param2);
		modelMap.addAttribute("sum_value", sum_value);
		
		// 전달 할 jap 페이지
		return "sum_result1";
	}

결과

domain 객체 클라이언트에 전달 (서버 -> 클라이언트)

출처 : 뜬금없는 도메인 오브젝트의 발전사

java 소스 도메인 객체 - SumValueDomain.java

package com.iot.domain;

public class SumValueDomain {
	
	private int value1;
	private int value2;
}

get, set 메소드 생성

메소드 추가

	public int getSumValue() {
		return this.value1 + this.value2;
	}

java 소스 도메인 객체 최종소스 - SumValueDomain.java

package com.iot.domain;

public class SumValueDomain {
	
	private int value1;
	private int value2;
	
	public int getValue1() {
		return value1;
	}
	
	public void setValue1(int value1) {
		this.value1 = value1;
	}
	
	public int getValue2() {
		return value2;
	}
	
	public void setValue2(int value2) {
		this.value2 = value2;
	}
	
	public int getSumValue() {
		return this.value1 + this.value2;
	}
}

java 소스

	@RequestMapping(value = "/sum_result3.iot", method = RequestMethod.GET)
	public String sum_result3(
			@RequestParam("param1") int param1,
			@RequestParam(value="param2", required=false, defaultValue="0") int param2,
			ModelMap modelMap
			) 
	{
		// 도메일 객체 생성
		SumValueDomain sum_value = new SumValueDomain();
		
		// 값 설정
		sum_value.setValue1(param1);
		sum_value.setValue2(param2);
		
		// Model에 도메일 객체 전달
		modelMap.addAttribute("sum_value", sum_value);
		
		// 전달 할 jap 페이지
		return "sum_result3";
	}

jsp 소스 - sum_result3.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
</head>
<body>

스프링 테스트<br/><br/>

${sum_value.value1} 더하기 ${sum_value.value2} (은/는) ${sum_value.getSumValue()} 입니다.

</body>
</html>

결과

domain 객체 서버에 전달 (클라이언트 -> 서버)

domain 객체를 spring 프레임워크에서 제공되는 form 테그 라이브러리를 사용해서 jsp에 전달했다가 다시 form 테그를 이용해서 서버의 controller에 전달하는 과정

java 소스 - Form jsp 호출

	@RequestMapping(value = "/sum_form.iot", method = RequestMethod.GET)
	public String sum_form(ModelMap modelMap) {
		// 도메일 객체 생성
		SumValueDomain sum_value = new SumValueDomain();
		
		// Model에 도메일 객체 전달
		modelMap.addAttribute("sum_value", sum_value);
		
		// 전달 할 jap 페이지
		return "sum_form";
	}

jsp 소스 - sum_form.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

<html>
<head>
</head>
<body>

<form:form modelAttribute="sum_value" action="sum_result4.iot" method="POST">
	<p>
		값1<br/>
		<form:input path="value1"/>
	</p>
	<p>
		값2<br/>
		<form:input path="value2"/>
	</p>
	<p>
		<input type="submit" value="Submit">
	</p>
</form:form>

</body>
</html>

결과 - Form jsp

java 소스 - Form 에서 submit 호출 받는 메소드

	@RequestMapping(value = "/sum_result4.iot", method = RequestMethod.POST)
	public String sum_result4(SumValueDomain domain, ModelMap modelMap) 
	{
		int sum_value = domain.getValue1() + domain.getValue2();
		
		modelMap.addAttribute("param1", domain.getValue1());
		modelMap.addAttribute("param2", domain.getValue2());
		modelMap.addAttribute("sum_value", sum_value);
		
		// 전달 할 jap 페이지
		return "sum_result1";
	}

결과

728x90
728x90

출처 : Web.xml의 개요, 기능, 활용
web.xml Listener, Filter의 활용
톰캣 web.xml 설명
[Spring] web.xml 기본 설정

파일 위치

%PROJECT_HOME%\WEB-INF\web.xml

기본 web.xml 파일

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="bluexmas" version="3.0">

	<display-name>IotWebServer</display-name>
	
	<context-param>
		<param-name>webAppRootKey</param-name>
		<param-value>com.bluexmas.ui</param-value>
	</context-param>	
	
	<session-config>
		<session-timeout>720</session-timeout>
	</session-config>

	<jsp-config>
		<jsp-property-group>
			<url-pattern>*.jsp</url-pattern>
			<page-encoding>UTF-8</page-encoding>
		</jsp-property-group>
		<jsp-property-group>
			<url-pattern>/servlet/*</url-pattern>
			<page-encoding>UTF-8</page-encoding>
		</jsp-property-group>
	</jsp-config>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>index.html</welcome-file>
	</welcome-file-list>
</web-app>

서블릿 추가

서블릿 파일

package com.iot.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// 출처 : http://dkatlf900.tistory.com/68
// tomcat 7.0부터 지원되는 xml 매핑을 자동 매핑
//@WebServlet("/test")
public class TestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException 
	{
		// request 안의 모든 parameter 확인하기
		// 출처 : http://tmdjcollabo.tistory.com/entry/java-request-%EC%95%88%EC%9D%98-%EB%AA%A8%EB%93%A0-parameter-%ED%99%95%EC%9D%B8%ED%95%98%EA%B8%B0
		Enumeration<String> params = request.getParameterNames();
		System.out.println("----------------------------");
		while (params.hasMoreElements()){
			String name = (String) params.nextElement();
			System.out.println(name + " : " + request.getParameter(name));
		}
		System.out.println("----------------------------");
		
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.println("Iot 서버 입니다.");
	}
}

web-xml 추가

	<servlet>
		<servlet-name>test</servlet-name>
		<servlet-class>com.iot.servlet.TestServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>test</servlet-name>
		<url-pattern>/test</url-pattern>
	</servlet-mapping>

Spring MVC DispatherServlet 설정

출처 : @MVC와 DispatcherServlet에 대해서

디렉토리 구조

web-xml 추가

	<servlet>
		<servlet-name>iot</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>iot</servlet-name>
		<url-pattern>*.iot</url-pattern>
	</servlet-mapping>

iot-servlet.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:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:security="http://www.springframework.org/schema/security"
       xsi:schemaLocation="http://www.springframework.org/schema/aop       http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
                           http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                           http://www.springframework.org/schema/context   http://www.springframework.org/schema/context/spring-context-2.5.xsd
                           http://www.springframework.org/schema/jee       http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
                           http://www.springframework.org/schema/tx        http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
                           http://www.springframework.org/schema/security  http://www.springframework.org/schema/security/spring-security-2.0.xsd">

	<bean id="testController" class="com.iot.ui.controller.TestController"/>
	
	<!-- ========================= JSP View Resolver ========================= -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>		
</beans>

TestController.java

package com.iot.ui.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class TestController {

	@RequestMapping(value = "/test.iot", method = RequestMethod.GET)
	public String test(ModelMap modelMap) {
		return "testjsp";
	}
}

testjsp.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
</head>
<body>

스프링 테스트

</body>
</html>


728x90
728x90

출처 : Spring MVC Checkbox And Checkboxes Example

CodeData.java

public class CodeData {	
	private int itemValue;
	private String itemLabel;
	public CodeData(int itemValue, String itemLabel) {
		super();
		this.itemValue = itemValue;
		this.itemLabel = itemLabel;
	}
	public int getItemValue() {
		return itemValue;
	}
	public void setItemValue(int itemValue) {
		this.itemValue = itemValue;
	}
	public String getItemLabel() {
		return itemLabel;
	}
	public void setItemLabel(String itemLabel) {
		this.itemLabel = itemLabel;
	}	
}

라디오버튼

		List<CODEDATA> typeList = new ArrayList<CODEDATA>();
		typeList.add(new CodeData(1, "남자"));
		typeList.add(new CodeData(2, "여자"));
		modelMap.addObject("typeList", typeList);
<form:radiobuttons path="gender" items="${typeList}" itemValue="itemValue" itemLabel="itemLabel"/>

셀렉트박스

        <form:select path="template_id" style="width: 200px; display:none">
			<form:options items="${listTemplate}" itemLabel="name" itemValue="tid" />
		</form:select>

form action url

출처 : Spring MVC: Relative URL problems
<spring:url var = "action" value='/ruleManagement/save' ... />
<form:form action="${action}" method="post">

- end -

728x90
728x90

출처 : http://pelican7.egloos.com/2584679

Tomcat 7
Spring Framework 3.0.3.RELEASE
Eclipse 3.6

간단하게 브라우저에서 hello.htm을 호출하면 내부에서 hello.jsp를 호출하는 예제입니다.

1. Project 생성



2. jar 복사

경로 : SpringMVC\WebContent\WEB-INF\lib

commons-logging-1.1.1.jar
org.springframework.asm-3.0.4.RELEASE.jar
org.springframework.beans-3.0.4.RELEASE.jar
org.springframework.context-3.0.4.RELEASE.jar
org.springframework.core-3.0.4.RELEASE.jar
org.springframework.expression-3.0.4.RELEASE.jar
org.springframework.web-3.0.4.RELEASE.jar
org.springframework.web.servlet-3.0.4.RELEASE.jar

3. web.xml 파일 작성

경로 : SpringMVC\WebContent\WEB-INF

---------------------------------------
<?xml version="1.0" encoding="UTF-8"?>

<web-app 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_3_0.xsd"
  version="3.0">

  <servlet>
    <servlet-name>springapp</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>springapp</servlet-name>
    <url-pattern>*.htm</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>
      index.jsp
    </welcome-file>
  </welcome-file-list>

</web-app>
---------------------------------------

4. springapp-servlet.xml 파일 작성

경로 : SpringMVC\WebContent\WEB-INF

---------------------------------------
<?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
       http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

  <!-- the application context definition for the springapp DispatcherServlet -->

  <bean name="/hello.htm" class="springapp.web.HelloController"/>

</beans>
---------------------------------------

5. HelloController.java 작성 / 컴파일

---------------------------------------
package springapp.web;

import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;

public class HelloController implements Controller {

    protected final Log logger = LogFactory.getLog(getClass());

    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        logger.info("Returning hello view");

        return new ModelAndView("hello.jsp");
    }
}
---------------------------------------

6. hello.jsp 파일 작성

경로 : SpringMVC\WebContent

---------------------------------------
 <html>
  <head><title>Hello :: Spring Application</title></head>
  <body>
    <h1>Hello - Spring Application</h1>
    <p>Greetings.</p>
  </body>
</html>
---------------------------------------

7. Test

http://localhost:8080/SpringMVC/hello.htm


728x90

+ Recent posts