'MVC'에 해당되는 글 4건

  1. 2022.04.07 [Springboot+Ajax] 데이터 통신
  2. 2020.07.21 [Spring] viewResolver return types...
  3. 2018.05.02 [Spring Framework] SpringMVC + Gradle 템플릿 + Tomcat 연동
  4. 2012.03.13 4. Spring MVC 에 Hibernate 적용해 보기.

[Springboot+Ajax] 데이터 통신

ITWeb/개발일반 2022. 4. 7. 15:43

Spring Domain, VO, Model

@Setter
@Getter
@ToString
public class SearchRequestModel {

    private PageModel pageModel;
    private long id;
}

@Setter
@Getter
@ToString
public class PagetModel {

    private int page;
    private int size;
    private String sort;
}

 

Spring RestController

@ResponseBody
@RequestMapping(
    value = "/api/search",
    method = RequestMethod.POST,
    produces = { MediaType.APPLICATION_JSON_VALUE }
)
public String search(
	@RequestBody SearchRequestModel m
) {
	return service.search(m)
}

 

Ajax

$.ajax({
    type: "POST",
    url: "/api/search",
    dataType: "json",
    contentType: "application/json",
    data: JSON.stringify({
        "pageModel": {
            "page": 1,
            "size": 20,
            "sort": "asc"
        },
        "id": 1
    }),
    success: function(res) {
    },
    error: function(res, status, e) {
    }
});

 

Ajax 요청 시 dataType, contentType 선언 없이 + @RequestBody 선언 없이 사용할 경우,

일반적인 POJO 스타일의 Data Binding 으로 처리가 됩니다. (Spring 에서는 자동으로 처리가 됩니다.)

또는

@RequestParam 을 이용해서 값을 전달 받을 수 있습니다.

 

오랜만에 화면 작업 하다 보니 이런것도 기억이 가물 가물 합니다.

:

[Spring] viewResolver return types...

ITWeb/개발일반 2020. 7. 21. 10:45

[참고문서]

https://docs.spring.io/spring/docs/4.3.12.RELEASE/spring-framework-reference/htmlsingle/#mvc-ann-return-types

https://docs.spring.io/spring/docs/3.0.0.M3/spring-framework-reference/html/ch16s03.html

 

Spring mvc framework 에서 Controller 에서 사용하는 return type 에 따른 viewResolver 적용방법이 다릅니다.

위 문서를 보시면 이해 하실 수 있습니다.

 

가장 많이 사용 하는 몇 개만 뽑아 왔습니다.

 

  • A ModelAndView object, with the model implicitly enriched with command objects and the results of @ModelAttribute annotated reference data accessor methods.
  • A Model object, with the view name implicitly determined through a RequestToViewNameTranslator and the model implicitly enriched with command objects and the results of @ModelAttribute annotated reference data accessor methods.
  • A Map object for exposing a model, with the view name implicitly determined through a RequestToViewNameTranslator and the model implicitly enriched with command objects and the results of @ModelAttribute annotated reference data accessor methods.
  • A View object, with the model implicitly determined through command objects and @ModelAttribute annotated reference data accessor methods. The handler method may also programmatically enrich the model by declaring a Model argument (see above).
  • A String value that is interpreted as the logical view name, with the model implicitly determined through command objects and @ModelAttribute annotated reference data accessor methods. The handler method may also programmatically enrich the model by declaring a Model argument (see above).
  • void if the method handles the response itself (by writing the response content directly, declaring an argument of type ServletResponse / HttpServletResponse for that purpose) or if the view name is supposed to be implicitly determined through a RequestToViewNameTranslator (not declaring a response argument in the handler method signature).
  • If the method is annotated with @ResponseBody, the return type is written to the response HTTP body. The return value will be converted to the declared method argument type using HttpMessageConverters. See the section called “Mapping the response body with the @ResponseBody annotation”.

제가 실수한 부분은 void 로 선언을 해 놓고 template 수정 후 반영이 되지 않아 cache 를 의심 했었는데 역시 원인은 제가 선언을 잘 못 했기 때문 이였습니다.

 

void 로 선언 시 해석은 

@GetMapping("/hello")
public void helloworld() {...}

hello.html 을 template 으로 찾게 됩니다.

 

:

[Spring Framework] SpringMVC + Gradle 템플릿 + Tomcat 연동

ITWeb/개발일반 2018. 5. 2. 18:33

매니저 역할을 오래 하다 보면 개발 감각이 떨어 지는건 어쩔수 없는 일인 것 같습니다.

SpringMVC 를 이용한 기본 웹 개발도 이제는 거북이 수준이 되어 가고 있는 것 같아 잊지 않기 위해 기록해 봅니다.


요즘 워낙 좋은 Tool, IDE 들이 많이 나와 있고. Git 검색만 해봐도 찾던 소스가 너무나도 많이 나옵니다.

아래는 Intellij community 버전을 이용해서 웹프로젝트 템플릿을 생성하는 예제 입니다.


각 단계별 코드별 설명은 작성 하지 않았습니다.

이유는 여긴 제가 그냥 혼자 기록하고 공부하는 공간이고, 누구를 가르치기에 너무 많은 무림고수 들이 계셔서 어쭙잖은 설명은 그냥 아래 레퍼런스로 대신 합니다.


References)

https://github.com/HowookJeong/springmvc-gradle-template

https://tomcat.apache.org/tomcat-9.0-doc/config/context.html

https://docs.spring.io/spring/docs/4.3.16.RELEASE/spring-framework-reference/htmlsingle/#spring-web


Step 1)

Intellij 를 실행 하고 매뉴에서 아래와 같이 선택을 합니다.


File -> New -> Project -> Gradle -> Java -> Next


GroupId -> org.project.web

ArtifactId -> springmvc-gradle-template

Next


Step 2)

SpringMVC Framework 틀을 만들기 위해 필요한 폴더와 파일들을 아래와 같이 생성을 합니다.


2-1) Community 버전으로는 gradle webapp 추가가 안되기 때문에 별도로 생성 합니다.

Make webapp directory

src/main/webapp


2-2) Make WEB-INF directory

src/main/webapps/WEB-INF

web.xml

dispatcher-servlet.xml


2-3) jsp template 사용을 위해서 WEB-INF 아래 jsp 폴더를 생성 합니다.

Make jsp directory

src/main/webapps/WEB-INF/jsp


2-4) Resource 구성을 합니다.

Make resources directory

src/main/resources/beans

bo-bean.xml

dao-bean.xml

src/main/resources/context

applicationContext.xml

applicationContext-mybatis.xml

src/main/resources/mybatis

config.xml

jdbc.properties

src/main/resources/sql

example.xml

log4j.xml


2-5) Package 구성을 합니다.

Make packages

org.project.web.bo

org.project.web.controllor

org.project.web.dao

org.project.web.model


여기까지 하셨으면 기본 empty project 생성은 끝났습니다.

이제 필요한 코드와 설정을 해보도록 하겠습니다.


Step 3)

이제 필요한 코드들을 생성해 보도록 하겠습니다.


3-1) web.xml 설정하기



3-2) dispatcher-servlet.xml 설정하기



3-3) log4j.xml 설정하기



3-4) mybatis/config.xml 설정하기



3-5) mybatis/jdbc.properties 설정하기



3-6) build.gradle 설정하기



이제 application 구현을 위한 코드 생성을 해보겠습니다.


3-7) controller/ExampleController


3-8) bo/ExampleBO


3-9) bo/ExampleBOImpl


3-10) dao/ExampleDAO


3-11dao/ExampleDAOImpl


3-12) model/ExampleModel



코드 구현을 했으니 이제 resources 설정을 하도록 하겠습니다.


3-13) beans/bo-bean.xml


3-14) beans/dao-bean.xml


3-15) context/applicationContext.xml


3-16) context/applicationContext-mybatis.xml


3-17) sql/example.xml


화면 구성을 위한 데코레이션으로 jsp 코드를 작성해 보겠습니다.


3-18) WEB-INF/jsp/exampleView.jsp


:

4. Spring MVC 에 Hibernate 적용해 보기.

ITWeb/개발일반 2012. 3. 13. 16:18
※ 아래 코드에 delete 시 동작 안하는 문제가 있어서 코드 수정했습니다.
 

[contact.xml]

<id name="id" type="long"> // int 에서 long 으로 변경

 
[Contact*.java]

private Long id; // 역시 int 에서 Long 으로 변경 당연히 setter/getter/param 다 변경


[ContactDAOImpl.java]

// ...delete(contact); 가 정상적으로 동작하지 않아 아래 처럼 변경.
this.sessionFactory.getCurrentSession().createQuery("delete Contact where id=:id").setLong("id", id).executeUpdate();


[수정된 Project]
 proto.orm.zip





Spring MVC 에 다른 사이트의 HIbernate 예제 코드로 작성하였습니다.
- 해당 예제 코드를 그대로 사용할경우 안되는 부분이 있어서 직접 수정하여 반영합니다.

[Hibernate 예제코드]


[소스코드]

- Eclipse import 하시면 프로젝트 확인 가능 합니다.


※ import/export 방법은 아래 글 참고하세요.
http://jjeong.tistory.com/564 


1. Spring MVC 구성해 보기.
2. Spring MVC 에 MyBatis 적용해 보기.
3. Spring MVC 에 Spring Security 적용해 보기. 
4. Spring MVC 에 Hibernate 적용해 보기. 
5. 2+3번 적용해 보기.
6. 3+4번 적용해 보기. 


- 소스코드를 첨부 하였으므로 요약 정보만 기술 합니다.

[Table 생성]

Database : Mysql.protodb

CREATE TABLE CONTACTS

(

    id              INT PRIMARY KEY AUTO_INCREMENT,

    firstname    VARCHAR(30),

    lastname    VARCHAR(30),

    telephone   VARCHAR(15),

    email         VARCHAR(30),

    created     TIMESTAMP DEFAULT NOW()

); 



[pom.xml]

        <!-- spring framework jdbc 설정 -->

        <dependency>

            <groupId>org.springframework</groupId>

            <artifactId>spring-jdbc</artifactId>

            <version>${org.springframework-version}</version>

        </dependency>


        <!-- spring framework transaction 설정 -->

        <dependency>

            <groupId>org.springframework</groupId>

            <artifactId>spring-tx</artifactId>

            <version>${org.springframework-version}</version>

        </dependency>


        <!-- spring framework orm 설정 -->

        <dependency>

            <groupId>org.springframework</groupId>

            <artifactId>spring-orm</artifactId>

            <version>${org.springframework-version}</version>

        </dependency>


        <!-- hibernate dependency 설정 start -->

        <dependency>

            <groupId>org.hibernate</groupId>

            <artifactId>hibernate-core</artifactId>

            <version>3.6.9.Final</version>

        </dependency>


        <dependency>

            <groupId>dom4j</groupId>

            <artifactId>dom4j</artifactId>

            <version>1.6.1</version>

        </dependency>

        <dependency>

            <groupId>commons-collections</groupId>

            <artifactId>commons-collections</artifactId>

            <version>3.2.1</version>

        </dependency>


        <dependency>

            <groupId>org.javassist</groupId>

            <artifactId>javassist</artifactId>

            <version>3.15.0-GA</version>

        </dependency>


        <dependency>

            <groupId>cglib</groupId>

            <artifactId>cglib</artifactId>

            <version>2.2.2</version>

        </dependency>


        <dependency>

            <groupId>org.apache.commons</groupId>

            <artifactId>commons-lang3</artifactId>

            <version>3.1</version>

        </dependency>

        <!-- hibernate dependency 설정 end -->


        <!-- mysql -->

        <dependency>

            <groupId>mysql</groupId>

            <artifactId>mysql-connector-java</artifactId>

            <version>5.1.18</version>

        </dependency>


        <!-- apache commons dbcp -->

        <dependency>

            <groupId>commons-dbcp</groupId>

            <artifactId>commons-dbcp</artifactId>

            <version>1.2.2</version>

        </dependency>

- dependency 관련 파일들은 이제 어느 정도 설정 하는데 무리가 없으시죠. 자세한 내용은 아래 링크에


[web.xml]

 <context-param>

        <param-name>contextConfigLocation</param-name>

        <param-value>

            /WEB-INF/spring/root-context.xml

            classpath:context/**/applicationContext*.xml

        </param-value>

    </context-param>
.... 중략

    <filter>

   <filter-name>openSessionInViewFilter</filter-name>

   <filter-class>

       org.springframework.orm.hibernate3.support.OpenSessionInViewFilter

   </filter-class>

    </filter>


    <filter-mapping>

        <filter-name>openSessionInViewFilter</filter-name>

        <url-pattern>/*</url-pattern>

    </filter-mapping> 



[applicationContext-hibernate.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:context="http://www.springframework.org/schema/context"

    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"

    xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"

    xmlns:util="http://www.springframework.org/schema/util"

    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd

        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd

        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd

        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd

        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd

        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">


    <bean id="messageSource"

        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">

        <property name="basename" value="classpath:messages/message" />

        <property name="defaultEncoding" value="UTF-8" />

    </bean>


    <bean id="localeChangeInterceptor"

        class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">

        <property name="paramName" value="lang" />

    </bean>


    <bean id="localeResolver"

        class="org.springframework.web.servlet.i18n.CookieLocaleResolver">

        <property name="defaultLocale" value="ko" />

    </bean>


    <bean id="handlerMapping"

        class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">

        <property name="interceptors">

            <ref bean="localeChangeInterceptor" />

        </property>

    </bean>


    <bean id="propertyConfigurer"

        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"

        p:location="classpath:configuration/hibernate/config.properties" />


    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"

    destroy-method="close">

    <property name="driverClassName" value="${jdbc.driverClassName}" />

    <property name="url" value="${jdbc.url}" />

    <property name="username" value="${jdbc.username}" />

    <property name="password" value="${jdbc.password}" />

    </bean>


    <bean id="sessionFactory"

        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

        <property name="dataSource" ref="dataSource" />

        <property name="hibernateProperties">

            <props>

                <prop key="hibernate.dialect">${jdbc.dialect}</prop>

                <prop key="hibernate.show_sql">true</prop>

            </props>

        </property>

        <property name="mappingResources">

            <list>

                <value>/sql/hibernate/mapper/contact.xml</value>

            </list>

        </property>

    </bean>


    <bean id="transactionManager"

        class="org.springframework.orm.hibernate3.HibernateTransactionManager">

        <property name="sessionFactory" ref="sessionFactory" />

    </bean>


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


    <bean id="contactDAO" class="proto.orm.board.contact.dao.ContactDAOImpl">

        <property name="sessionFactory" ref="sessionFactory" />

    </bean>

</beans>

- 간혹 아래와 같은 오류가 날때가 있습니다.

org.hibernate.HibernateException: No Session found for current thread

-> 이건 sessionFactory 설정을 잘못해서 나옵니다.

-> sessionFactory 를 중복 선언 하거나 (include 도니 파일 잘 찾아 보세요.)

-> web.xml 에 openSessionInViewFilter 설정이 빠져 있는지 확인 합니다.



Unable to instantiate default tuplizer 

-> 이건 domain 객체에서 setter/getter 설정 오류 이거나 mapping 오류일 경우 발생 합니다.

-> domain 객체를 한번 검토해 보시고 hibernate mapping xml 에 선언한 내용과 일치 하는지도 확인해 보세요.



org.hibernate.hql.ast.QuerySyntaxException: xxxx is not mapped [FROM xxxx]  

-> 이건  createQuery("FROM 도메인객체명") 으로 표기를 해야 하는데 간혹 Table 이른을 넣다 보면 오류가 납니다.

-> 본 예제에서는 Contact Object 이므로 createQuery("FROM Contact") 이라고 써줘야 합니다. 



[config.properties]

jdbc.driverClassName=com.mysql.jdbc.Driver

jdbc.dialect=org.hibernate.dialect.MySQLDialect

jdbc.url=jdbc:mysql://localhost:3306/protodb?autoReconnect=true

jdbc.username=root

jdbc.password=1234



[contact.xml]

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

    <class name="proto.orm.board.contact.domain.Contact" table="contacts">

        <id name="id" type="int">

            <column name="id" />

            <generator class="identity" />

        </id>

        <property name="firstname" type="string">

            <column name="firstname" length="30" not-null="false" />

        </property>

        <property name="lastname" type="string">

            <column name="lastname" length="30" not-null="false" />

        </property>

        <property name="telephone" type="string">

            <column name="telephone" length="15" not-null="false" />

        </property>

        <property name="email" type="string">

            <column name="email" length="30" not-null="false" />

        </property>

        <property name="created" type="timestamp">

            <column name="created" not-null="false" />

        </property>

    </class>

</hibernate-mapping>

- 이 파일은 hibernate ref. 중 mapping 부분 참고하세요.



[ContactController.java]


[ContactServiceImpl.java] 


[ContactDAOImpl.java] 


[Contact.java]


[contact.jsp]


[참고사이트]

: