SlideShare a Scribd company logo
Spring application
Phiên bản: 0.1 2013-12-10
SPRING APPLICATION
XÂY DỰNG DEMO CHO ỨNG DỤNG SPRING
THUỘC TÍNH TÀI LIỆU
Tiêu đề: Xây dựng demo cho ứng dụng Spring
Chủ đề: Spring application
Tác giả: Laptrinh.vn
Từ khóa: Spring, ibatis
Spring application
Phiên bản: 0.1 2013-12-10
TABLE OF CONTENTS
THUẬT NGỮ...................................................................................................................................................3
GIỚI THIỆU.....................................................................................................................................................3
XÂY DỰNG ỨNG DỤNG...............................................................................................................................3
1.1. Dynamic Web project...................................................................................................................3
1.1.1. Create java web application..........................................................................................3
1.1.2. Xây dựng controller......................................................................................................5
1.1.3. Cấu hình thư mục jsp....................................................................................................6
1.1.4. Sử dụng Sitemap...........................................................................................................6
1.2. Connect Database.........................................................................................................................9
1.2.1. Sử dụng iBatis...............................................................................................................9
1.3. Displaytag, jstl & một số thư viện khác.....................................................................................13
Spring application
Phiên bản: 0.1 2013-12-10
THUẬT NGỮ
This section is intentionally left blank
GIỚI THIỆU
XÂY DỰNG ỨNG DỤNG
1.1. Dynamic Web project
1.1.1. Create java web application
Sử dụng thư viện Spring
Download: http://www.springsource.org/spring-framework
Copy vào thư mục lib
Spring application
Phiên bản: 0.1 2013-12-10
Thêm 2 thư viện để ghi log
log4j-1.2.17.jar commons-logging-1.1.1.jar
Chỉnh sửa file WEB-INFweb.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
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Spring</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-
class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</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>
Spring application
Phiên bản: 0.1 2013-12-10
</web-app>
Thêm file WEB-INFdispatcher-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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="springapp.web.controller" />
</beans>
1.1.2. Xây dựng controller
Tạo package springapp.web.controller
Tạo class: HelloController
package springapp.web.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* Description: Hello controller
* @author DatNH
*
* Detail:
* - @: annotation java
*
*/
@Controller
public class HelloController {
/**
* Nhan request /hello, xu ly thong tin
* @return
*/
@RequestMapping("/hello")
public ModelAndView hello(Model model) {
// set session value
model.addAttribute("name", "DatNH");
return new ModelAndView("hello.jsp");
}
Spring application
Phiên bản: 0.1 2013-12-10
@RequestMapping("/helloworld")
public String helloworld(Model model) {
model.addAttribute("name", "DatNH");
return "hello.jsp";
}
}
Tạo file WebContent/hello.jsp
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h1>Ch ngươ trình đ cượ xây d ngự d aự trên framework MVC Sping 3</h1>
<p>Xin chào: <b>${name}</b></p>
</body>
</html>
Kết quả
1.1.3. Cấu hình thư mục jsp
Thêm vào file dispatcher-servlet.xml
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
Sửa lại file controller
return new ModelAndView("hello");
Tạo thư mục WEB-INF/jsp và copy file hello.jsp vào
1.1.4. Sử dụng Sitemap
Download: http://www.opensymphony.com/sitemesh
Copy lib sitemesh-2.4.x.jar vào thư mục WEB-INF/lib
Spring application
Phiên bản: 0.1 2013-12-10
Thêm filter vào web.xml
<!-- Sitemesh -->
<filter>
<filter-name>sitemesh</filter-name>
<filter-
class>com.opensymphony.module.sitemesh.filter.PageFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>sitemesh</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Tạo một số thư mục trong WebContent/
• decorators : Thư mục gồm tất cả các file decorator (e.g. main.jsp, printable.jsp).
• includes: Thư mục gồm tất cả các file sẽ được include tới các file khác (e.g. header.jsp,
footer.jsp, copyright.jsp).
• images: Thư mục bao gồm tất cả các ảnh (e.g. background.gif, logo.gif).
• styles: Thư mục bao gồm tất cả CSS styles (e.g. ie4.css, ns4.css).
• scripts: Thư mục bao gồm tất cả các scripts (JavaScript, VBScript files).
Tạo file WEB-INF/decorators.xml
<?xml version="1.0" encoding="UTF-8"?>
<decorators defaultdir="/decorators">
<decorator name="main" page="main.jsp">
<pattern>/*</pattern>
</decorator>
</decorators>
Tạo file: /includes/header.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
[HEADER]
<hr/>
Tạo file: /includes/footer.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<hr/>
[FOOTER]
Spring application
Phiên bản: 0.1 2013-12-10
Tạo file: /includes/taglibs.jsp
<%@ taglib prefix="decorator" uri="http://www.opensymphony.com/sitemesh/decorator" %>
Tạo 1 file decorator : /decorators/main.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="/includes/taglibs.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>[springapp] <decorator:title/> </title>
</head>
<body>
<div id="container">
<%@ include file="/includes/header.jsp"%>
<div id="content">
<decorator:body />
</div>
<%@ include file="/includes/footer.jsp"%>
</div>
</body>
</html>
Kết quả
Cấu trúc project
Spring application
Phiên bản: 0.1 2013-12-10
1.2. Connect Database
Tải thư viện JDBC driver phù hợp, ở đây dùng MySQL
Tạo file context.xml trong META-INF
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource
name="jdbc/SpringMySqlDS"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/spring"
removeAbandoned="true"
maxActive="75"
maxIdle="30"
maxWait="-1"
username="root"
password="nguyendat"
validationQuery="select 1 from dual"
/>
</Context>
1.2.1. Sử dụng iBatis
Download: http://code.google.com/p/mybatis/
Spring application
Phiên bản: 0.1 2013-12-10
Project Description Links
MyBatis 3 SQL Mapping Framework for Java download | docs
Generator Code generator for MyBatis and iBATIS download | docs
Trong web.xml, tạo một reference tới resource SpringMySqlDS
<resource-ref>
<description>Chat Datasource</description>
<res-ref-name>jdbc/SpringMySqlDS</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
Tạo các package
• springapp.core.dao
• springapp.core.dao.xml
• springapp.core.model
• springapp.core.service
Copy mybatis-3.2.0-SNAPSHOT.jar vào WEB-INF/lib
Tạo file mybatisConfig.xml trong springapp.core.dao.xml
Cấu hình environments:
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="MANAGED">
<property name="closeConnection" value="true" />
</transactionManager>
<dataSource type="JNDI">
<property name="data_source"
value="java:comp/env/jdbc/SpringMySqlDS" />
</dataSource>
</environment>
</environments>
</configuration>
Tạo file mapping database table và java class
• Khai báo và mapping column table với thuộc tính trong java
• Thực hiện câu lệnh generator
Spring application
Phiên bản: 0.1 2013-12-10
cd /d C:UsersPhoenixworkspacejunoSpringgenerator (tùy thư mục nhé)
java -jar mybatis-generator-core-1.3.1.jar -configfile generatorConfig.xml -overwrite -tables user
Các class đã được generator
UserMapper.java UserMapper.xml User.java
Xử lý dữ liệu
• Tạo service class
o Interface: UserServiceLocal.java
o Class: UserService
• Tạo bean cho UserService
o File web.xml
Thêm cấu hình applicationContext.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-
class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
o File applicationContext.xml
Application context: Khai báo các bean session sử dụng trong chương trình.
<?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:jee="http://www.springframework.org/schema/jee"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-2.5.xsd">
<bean id="userService" class="springapp.core.service.UserService" />
</beans>
Spring application
Phiên bản: 0.1 2013-12-10
o File myBatisConfig.xml
<mapper resource="springapp/core/dao/xml/UserMapper.xml" />
• Xử lý Controller
o File UserController.java
package springapp.web.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import springapp.core.model.User;
import springapp.core.service.UserServiceLocal;
/**
* User controller
* @author DatNh
*
*/
@Controller
public class UserController {
@Autowired
private UserServiceLocal userService;
@RequestMapping("/user")
public String helloworld(Model model) {
User user = userService.selectByPrimaryKey(1);
model.addAttribute("user", user);
return "user";
}
}
o File user.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h1>User demo</h1>
<p>Xin chào: <b>${user.username}</b></p>
</body>
</html>
Spring application
Phiên bản: 0.1 2013-12-10
o File UserServiceLocal.java
package springapp.core.service;
import springapp.core.model.User;
/**
*
* @author DatNH
*
*/
public interface UserServiceLocal {
User selectByPrimaryKey(int id);
}
o File UserService.java
package springapp.core.service;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import springapp.core.dao.UserMapper;
import springapp.core.model.User;
/**
* User service
* @author DatNH
*
*/
public class UserService implements UserServiceLocal {
@Override
public User selectByPrimaryKey(int id) {
SqlSessionFactory sqlMapper = MyBatisService.getSessionFactory();
SqlSession sqlSession = sqlMapper.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.selectByPrimaryKey(id);
sqlSession.close();
return user;
}
}
1.3. Displaytag, jstl & một số thư viện khác
Copy thư viện
Spring application
Phiên bản: 0.1 2013-12-10
displaytag-1.2.jar
jstl.jar javax.servlet.jsp.jstl-1.2.1.jar javax.servlet.jsp.jstl-api-1.2.1.jar
aopalliance-1.0.jar commons-lang-2.6.jar commons-beanutils-1.8.3.jar
File taglibs.jsp
@RequestMapping("/user/list")
public String list(Model model) {
List<User> userList = userService.getAll();
model.addAttribute("userList", userList);
return "userList";
}
File UserServiceLocal.java
List<User> getAll();
File UserService.java
@Override
public List<User> getAll() {
SqlSessionFactory sqlMapper = MyBatisService.getSessionFactory();
SqlSession sqlSession = sqlMapper.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getAll();
sqlSession.close();
return userList;
}
File UserMapper.java
List<User> getAll();
File UserMapper.xml
Spring application
Phiên bản: 0.1 2013-12-10
<select id="getAll" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user
</select>
File userList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="/includes/taglibs.jsp"%>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h1>User List</h1>
<div>
<display:table name="${userList}" class="simple wid100" id="user"
requestURI="" pagesize="15">
<display:column title="STT" class="stt" > <c:out value="$
{user_rowNum}"/> </display:column>
<display:column title="Username" property="username" />
<display:column title="Password" property="password"/>
<display:column title="Timestamp" property="timestamp"/>
<display:column title="Create Date" property="createDate"
format="{0,date,dd/MM/yyyy HH:mm:ss}" />
</display:table>
</div>
</body>
</html>
Kết quả
Ad

More Related Content

What's hot (20)

JEE Programming - 05 JSP
JEE Programming - 05 JSPJEE Programming - 05 JSP
JEE Programming - 05 JSP
Danairat Thanabodithammachari
 
JSF basics
JSF basicsJSF basics
JSF basics
airbo
 
Servlets lecture1
Servlets lecture1Servlets lecture1
Servlets lecture1
Tata Consultancy Services
 
A Complete Tour of JSF 2
A Complete Tour of JSF 2A Complete Tour of JSF 2
A Complete Tour of JSF 2
Jim Driscoll
 
JEE Programming - 04 Java Servlets
JEE Programming - 04 Java ServletsJEE Programming - 04 Java Servlets
JEE Programming - 04 Java Servlets
Danairat Thanabodithammachari
 
Sprint Portlet MVC Seminar
Sprint Portlet MVC SeminarSprint Portlet MVC Seminar
Sprint Portlet MVC Seminar
John Lewis
 
Jsp and Servlets
Jsp and ServletsJsp and Servlets
Jsp and Servlets
Raghu nath
 
JSF Component Behaviors
JSF Component BehaviorsJSF Component Behaviors
JSF Component Behaviors
Andy Schwartz
 
JSF 2 and beyond: Keeping progress coming
JSF 2 and beyond: Keeping progress comingJSF 2 and beyond: Keeping progress coming
JSF 2 and beyond: Keeping progress coming
Andy Schwartz
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - Components
Kaml Sah
 
Component Framework Primer for JSF Users
Component Framework Primer for JSF UsersComponent Framework Primer for JSF Users
Component Framework Primer for JSF Users
Andy Schwartz
 
JavaEE6 my way
JavaEE6 my wayJavaEE6 my way
JavaEE6 my way
Nicola Pedot
 
Lecture 10 - Java Server Faces (JSF)
Lecture 10 - Java Server Faces (JSF)Lecture 10 - Java Server Faces (JSF)
Lecture 10 - Java Server Faces (JSF)
Fahad Golra
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
Kasun Madusanke
 
Jsp servlets
Jsp servletsJsp servlets
Jsp servlets
Rajavel Dhandabani
 
1 java servlets and jsp
1   java servlets and jsp1   java servlets and jsp
1 java servlets and jsp
Ankit Minocha
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
Vikas Jagtap
 
Struts,Jsp,Servlet
Struts,Jsp,ServletStruts,Jsp,Servlet
Struts,Jsp,Servlet
dasguptahirak
 
Ch 04 asp.net application
Ch 04 asp.net application Ch 04 asp.net application
Ch 04 asp.net application
Madhuri Kavade
 
JSF basics
JSF basicsJSF basics
JSF basics
airbo
 
A Complete Tour of JSF 2
A Complete Tour of JSF 2A Complete Tour of JSF 2
A Complete Tour of JSF 2
Jim Driscoll
 
Sprint Portlet MVC Seminar
Sprint Portlet MVC SeminarSprint Portlet MVC Seminar
Sprint Portlet MVC Seminar
John Lewis
 
Jsp and Servlets
Jsp and ServletsJsp and Servlets
Jsp and Servlets
Raghu nath
 
JSF Component Behaviors
JSF Component BehaviorsJSF Component Behaviors
JSF Component Behaviors
Andy Schwartz
 
JSF 2 and beyond: Keeping progress coming
JSF 2 and beyond: Keeping progress comingJSF 2 and beyond: Keeping progress coming
JSF 2 and beyond: Keeping progress coming
Andy Schwartz
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - Components
Kaml Sah
 
Component Framework Primer for JSF Users
Component Framework Primer for JSF UsersComponent Framework Primer for JSF Users
Component Framework Primer for JSF Users
Andy Schwartz
 
Lecture 10 - Java Server Faces (JSF)
Lecture 10 - Java Server Faces (JSF)Lecture 10 - Java Server Faces (JSF)
Lecture 10 - Java Server Faces (JSF)
Fahad Golra
 
1 java servlets and jsp
1   java servlets and jsp1   java servlets and jsp
1 java servlets and jsp
Ankit Minocha
 
Ch 04 asp.net application
Ch 04 asp.net application Ch 04 asp.net application
Ch 04 asp.net application
Madhuri Kavade
 

Similar to [Laptrinh.vn] lap trinh Spring Framework 3 (20)

Oracle Endeca Developer's Guide
Oracle Endeca Developer's GuideOracle Endeca Developer's Guide
Oracle Endeca Developer's Guide
Keyur Shah
 
JavaServer Pages
JavaServer PagesJavaServer Pages
JavaServer Pages
Abdalla Mahmoud
 
JavaDo#09 Spring boot入門ハンズオン
JavaDo#09 Spring boot入門ハンズオンJavaDo#09 Spring boot入門ハンズオン
JavaDo#09 Spring boot入門ハンズオン
haruki ueno
 
Toms introtospring mvc
Toms introtospring mvcToms introtospring mvc
Toms introtospring mvc
Guo Albert
 
Spring MVC 3.0 Framework (sesson_2)
Spring MVC 3.0 Framework (sesson_2)Spring MVC 3.0 Framework (sesson_2)
Spring MVC 3.0 Framework (sesson_2)
Ravi Kant Soni ([email protected])
 
Building high performance web apps.
Building high performance web apps.Building high performance web apps.
Building high performance web apps.
Arshak Movsisyan
 
Rest hello world_tutorial
Rest hello world_tutorialRest hello world_tutorial
Rest hello world_tutorial
Aravindharamanan S
 
Servlets
ServletsServlets
Servlets
Abdalla Mahmoud
 
Tomcat + other things
Tomcat + other thingsTomcat + other things
Tomcat + other things
Aravindharamanan S
 
Spring MVC 5 & Hibernate 5 Integration
Spring MVC 5 & Hibernate 5 IntegrationSpring MVC 5 & Hibernate 5 Integration
Spring MVC 5 & Hibernate 5 Integration
Majurageerthan Arumugathasan
 
Spring MVC 5 & Hibernate 5 Integration.pdf
Spring MVC 5 & Hibernate 5 Integration.pdfSpring MVC 5 & Hibernate 5 Integration.pdf
Spring MVC 5 & Hibernate 5 Integration.pdf
Patiento Del Mar
 
Getting started with hot towel spa
Getting started with hot towel spaGetting started with hot towel spa
Getting started with hot towel spa
parth17290
 
Meteor + Ionic Introduction
Meteor + Ionic IntroductionMeteor + Ionic Introduction
Meteor + Ionic Introduction
LearningTech
 
Django 1.10.3 Getting started
Django 1.10.3 Getting startedDjango 1.10.3 Getting started
Django 1.10.3 Getting started
MoniaJ
 
Trustparency web doc spring 2.5 & hibernate
Trustparency web doc   spring 2.5 & hibernateTrustparency web doc   spring 2.5 & hibernate
Trustparency web doc spring 2.5 & hibernate
trustparency
 
Nuxtjs cheat-sheet
Nuxtjs cheat-sheetNuxtjs cheat-sheet
Nuxtjs cheat-sheet
ValeriaCastillo71
 
Adding a view
Adding a viewAdding a view
Adding a view
Nhan Do
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable Applications
Alessandro Molina
 
Web technologies part-2
Web technologies part-2Web technologies part-2
Web technologies part-2
Michael Anthony
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
Bo-Yi Wu
 
Oracle Endeca Developer's Guide
Oracle Endeca Developer's GuideOracle Endeca Developer's Guide
Oracle Endeca Developer's Guide
Keyur Shah
 
JavaDo#09 Spring boot入門ハンズオン
JavaDo#09 Spring boot入門ハンズオンJavaDo#09 Spring boot入門ハンズオン
JavaDo#09 Spring boot入門ハンズオン
haruki ueno
 
Toms introtospring mvc
Toms introtospring mvcToms introtospring mvc
Toms introtospring mvc
Guo Albert
 
Building high performance web apps.
Building high performance web apps.Building high performance web apps.
Building high performance web apps.
Arshak Movsisyan
 
Spring MVC 5 & Hibernate 5 Integration.pdf
Spring MVC 5 & Hibernate 5 Integration.pdfSpring MVC 5 & Hibernate 5 Integration.pdf
Spring MVC 5 & Hibernate 5 Integration.pdf
Patiento Del Mar
 
Getting started with hot towel spa
Getting started with hot towel spaGetting started with hot towel spa
Getting started with hot towel spa
parth17290
 
Meteor + Ionic Introduction
Meteor + Ionic IntroductionMeteor + Ionic Introduction
Meteor + Ionic Introduction
LearningTech
 
Django 1.10.3 Getting started
Django 1.10.3 Getting startedDjango 1.10.3 Getting started
Django 1.10.3 Getting started
MoniaJ
 
Trustparency web doc spring 2.5 & hibernate
Trustparency web doc   spring 2.5 & hibernateTrustparency web doc   spring 2.5 & hibernate
Trustparency web doc spring 2.5 & hibernate
trustparency
 
Adding a view
Adding a viewAdding a view
Adding a view
Nhan Do
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable Applications
Alessandro Molina
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
Bo-Yi Wu
 
Ad

Recently uploaded (20)

Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Ad

[Laptrinh.vn] lap trinh Spring Framework 3

  • 1. Spring application Phiên bản: 0.1 2013-12-10 SPRING APPLICATION XÂY DỰNG DEMO CHO ỨNG DỤNG SPRING THUỘC TÍNH TÀI LIỆU Tiêu đề: Xây dựng demo cho ứng dụng Spring Chủ đề: Spring application Tác giả: Laptrinh.vn Từ khóa: Spring, ibatis
  • 2. Spring application Phiên bản: 0.1 2013-12-10 TABLE OF CONTENTS THUẬT NGỮ...................................................................................................................................................3 GIỚI THIỆU.....................................................................................................................................................3 XÂY DỰNG ỨNG DỤNG...............................................................................................................................3 1.1. Dynamic Web project...................................................................................................................3 1.1.1. Create java web application..........................................................................................3 1.1.2. Xây dựng controller......................................................................................................5 1.1.3. Cấu hình thư mục jsp....................................................................................................6 1.1.4. Sử dụng Sitemap...........................................................................................................6 1.2. Connect Database.........................................................................................................................9 1.2.1. Sử dụng iBatis...............................................................................................................9 1.3. Displaytag, jstl & một số thư viện khác.....................................................................................13
  • 3. Spring application Phiên bản: 0.1 2013-12-10 THUẬT NGỮ This section is intentionally left blank GIỚI THIỆU XÂY DỰNG ỨNG DỤNG 1.1. Dynamic Web project 1.1.1. Create java web application Sử dụng thư viện Spring Download: http://www.springsource.org/spring-framework Copy vào thư mục lib
  • 4. Spring application Phiên bản: 0.1 2013-12-10 Thêm 2 thư viện để ghi log log4j-1.2.17.jar commons-logging-1.1.1.jar Chỉnh sửa file WEB-INFweb.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 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>Spring</display-name> <servlet> <servlet-name>dispatcher</servlet-name> <servlet- class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>*.htm</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>
  • 5. Spring application Phiên bản: 0.1 2013-12-10 </web-app> Thêm file WEB-INFdispatcher-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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="springapp.web.controller" /> </beans> 1.1.2. Xây dựng controller Tạo package springapp.web.controller Tạo class: HelloController package springapp.web.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; /** * Description: Hello controller * @author DatNH * * Detail: * - @: annotation java * */ @Controller public class HelloController { /** * Nhan request /hello, xu ly thong tin * @return */ @RequestMapping("/hello") public ModelAndView hello(Model model) { // set session value model.addAttribute("name", "DatNH"); return new ModelAndView("hello.jsp"); }
  • 6. Spring application Phiên bản: 0.1 2013-12-10 @RequestMapping("/helloworld") public String helloworld(Model model) { model.addAttribute("name", "DatNH"); return "hello.jsp"; } } Tạo file WebContent/hello.jsp <html> <head> <title>Hello World</title> </head> <body> <h1>Ch ngươ trình đ cượ xây d ngự d aự trên framework MVC Sping 3</h1> <p>Xin chào: <b>${name}</b></p> </body> </html> Kết quả 1.1.3. Cấu hình thư mục jsp Thêm vào file dispatcher-servlet.xml <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" /> Sửa lại file controller return new ModelAndView("hello"); Tạo thư mục WEB-INF/jsp và copy file hello.jsp vào 1.1.4. Sử dụng Sitemap Download: http://www.opensymphony.com/sitemesh Copy lib sitemesh-2.4.x.jar vào thư mục WEB-INF/lib
  • 7. Spring application Phiên bản: 0.1 2013-12-10 Thêm filter vào web.xml <!-- Sitemesh --> <filter> <filter-name>sitemesh</filter-name> <filter- class>com.opensymphony.module.sitemesh.filter.PageFilter</filter-class> </filter> <filter-mapping> <filter-name>sitemesh</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> Tạo một số thư mục trong WebContent/ • decorators : Thư mục gồm tất cả các file decorator (e.g. main.jsp, printable.jsp). • includes: Thư mục gồm tất cả các file sẽ được include tới các file khác (e.g. header.jsp, footer.jsp, copyright.jsp). • images: Thư mục bao gồm tất cả các ảnh (e.g. background.gif, logo.gif). • styles: Thư mục bao gồm tất cả CSS styles (e.g. ie4.css, ns4.css). • scripts: Thư mục bao gồm tất cả các scripts (JavaScript, VBScript files). Tạo file WEB-INF/decorators.xml <?xml version="1.0" encoding="UTF-8"?> <decorators defaultdir="/decorators"> <decorator name="main" page="main.jsp"> <pattern>/*</pattern> </decorator> </decorators> Tạo file: /includes/header.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> [HEADER] <hr/> Tạo file: /includes/footer.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <hr/> [FOOTER]
  • 8. Spring application Phiên bản: 0.1 2013-12-10 Tạo file: /includes/taglibs.jsp <%@ taglib prefix="decorator" uri="http://www.opensymphony.com/sitemesh/decorator" %> Tạo 1 file decorator : /decorators/main.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ include file="/includes/taglibs.jsp"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>[springapp] <decorator:title/> </title> </head> <body> <div id="container"> <%@ include file="/includes/header.jsp"%> <div id="content"> <decorator:body /> </div> <%@ include file="/includes/footer.jsp"%> </div> </body> </html> Kết quả Cấu trúc project
  • 9. Spring application Phiên bản: 0.1 2013-12-10 1.2. Connect Database Tải thư viện JDBC driver phù hợp, ở đây dùng MySQL Tạo file context.xml trong META-INF <?xml version="1.0" encoding="UTF-8"?> <Context> <Resource name="jdbc/SpringMySqlDS" auth="Container" type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/spring" removeAbandoned="true" maxActive="75" maxIdle="30" maxWait="-1" username="root" password="nguyendat" validationQuery="select 1 from dual" /> </Context> 1.2.1. Sử dụng iBatis Download: http://code.google.com/p/mybatis/
  • 10. Spring application Phiên bản: 0.1 2013-12-10 Project Description Links MyBatis 3 SQL Mapping Framework for Java download | docs Generator Code generator for MyBatis and iBATIS download | docs Trong web.xml, tạo một reference tới resource SpringMySqlDS <resource-ref> <description>Chat Datasource</description> <res-ref-name>jdbc/SpringMySqlDS</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> Tạo các package • springapp.core.dao • springapp.core.dao.xml • springapp.core.model • springapp.core.service Copy mybatis-3.2.0-SNAPSHOT.jar vào WEB-INF/lib Tạo file mybatisConfig.xml trong springapp.core.dao.xml Cấu hình environments: <configuration> <environments default="development"> <environment id="development"> <transactionManager type="MANAGED"> <property name="closeConnection" value="true" /> </transactionManager> <dataSource type="JNDI"> <property name="data_source" value="java:comp/env/jdbc/SpringMySqlDS" /> </dataSource> </environment> </environments> </configuration> Tạo file mapping database table và java class • Khai báo và mapping column table với thuộc tính trong java • Thực hiện câu lệnh generator
  • 11. Spring application Phiên bản: 0.1 2013-12-10 cd /d C:UsersPhoenixworkspacejunoSpringgenerator (tùy thư mục nhé) java -jar mybatis-generator-core-1.3.1.jar -configfile generatorConfig.xml -overwrite -tables user Các class đã được generator UserMapper.java UserMapper.xml User.java Xử lý dữ liệu • Tạo service class o Interface: UserServiceLocal.java o Class: UserService • Tạo bean cho UserService o File web.xml Thêm cấu hình applicationContext.xml <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/applicationContext.xml </param-value> </context-param> <listener> <listener- class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> o File applicationContext.xml Application context: Khai báo các bean session sử dụng trong chương trình. <?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:jee="http://www.springframework.org/schema/jee" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd"> <bean id="userService" class="springapp.core.service.UserService" /> </beans>
  • 12. Spring application Phiên bản: 0.1 2013-12-10 o File myBatisConfig.xml <mapper resource="springapp/core/dao/xml/UserMapper.xml" /> • Xử lý Controller o File UserController.java package springapp.web.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import springapp.core.model.User; import springapp.core.service.UserServiceLocal; /** * User controller * @author DatNh * */ @Controller public class UserController { @Autowired private UserServiceLocal userService; @RequestMapping("/user") public String helloworld(Model model) { User user = userService.selectByPrimaryKey(1); model.addAttribute("user", user); return "user"; } } o File user.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <html> <head> <title>Hello World</title> </head> <body> <h1>User demo</h1> <p>Xin chào: <b>${user.username}</b></p> </body> </html>
  • 13. Spring application Phiên bản: 0.1 2013-12-10 o File UserServiceLocal.java package springapp.core.service; import springapp.core.model.User; /** * * @author DatNH * */ public interface UserServiceLocal { User selectByPrimaryKey(int id); } o File UserService.java package springapp.core.service; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import springapp.core.dao.UserMapper; import springapp.core.model.User; /** * User service * @author DatNH * */ public class UserService implements UserServiceLocal { @Override public User selectByPrimaryKey(int id) { SqlSessionFactory sqlMapper = MyBatisService.getSessionFactory(); SqlSession sqlSession = sqlMapper.openSession(true); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.selectByPrimaryKey(id); sqlSession.close(); return user; } } 1.3. Displaytag, jstl & một số thư viện khác Copy thư viện
  • 14. Spring application Phiên bản: 0.1 2013-12-10 displaytag-1.2.jar jstl.jar javax.servlet.jsp.jstl-1.2.1.jar javax.servlet.jsp.jstl-api-1.2.1.jar aopalliance-1.0.jar commons-lang-2.6.jar commons-beanutils-1.8.3.jar File taglibs.jsp @RequestMapping("/user/list") public String list(Model model) { List<User> userList = userService.getAll(); model.addAttribute("userList", userList); return "userList"; } File UserServiceLocal.java List<User> getAll(); File UserService.java @Override public List<User> getAll() { SqlSessionFactory sqlMapper = MyBatisService.getSessionFactory(); SqlSession sqlSession = sqlMapper.openSession(true); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> userList = mapper.getAll(); sqlSession.close(); return userList; } File UserMapper.java List<User> getAll(); File UserMapper.xml
  • 15. Spring application Phiên bản: 0.1 2013-12-10 <select id="getAll" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from user </select> File userList.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ include file="/includes/taglibs.jsp"%> <html> <head> <title>Hello World</title> </head> <body> <h1>User List</h1> <div> <display:table name="${userList}" class="simple wid100" id="user" requestURI="" pagesize="15"> <display:column title="STT" class="stt" > <c:out value="$ {user_rowNum}"/> </display:column> <display:column title="Username" property="username" /> <display:column title="Password" property="password"/> <display:column title="Timestamp" property="timestamp"/> <display:column title="Create Date" property="createDate" format="{0,date,dd/MM/yyyy HH:mm:ss}" /> </display:table> </div> </body> </html> Kết quả