2016年5月26日 星期四

加入myBatis




加入myBatis
事前設定:
在專案上右鍵>properties>project facets把Java換成1.6以上才能正確處理@Override

【POM】
加入
<!-- com.mysql.jdbc.Driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>

<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.1.1</version>
</dependency>
【SpringConfig】
加入
<!-- sqlSessionFactory -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/cypherswiki?" />
<property name="username" value="kadice" />
<property name="password" value="kadice" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" /><!-- 1、指定數據源 -->
<property name="configLocation" value="/WEB-INF/config/SqlMapConfig.xml" />
</bean>
<bean id="characterDataDao" class="mysite.dao.CharacterDataDao">
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

<!-- 和Ibatis集成方式不同的有如下地方:
SqlMapClient類廢棄,而使用SqlSessionFactory代替 ;
使用SqlSessionFactoryBean進行集成MyBatis。 -->

建立/WEB-INF/config/SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="cacheEnabled" value="false"/>
    </settings>
    <mappers>
        <mapper resource="mysite/sqlMap/characterData.xml"/>
    </mappers>
</configuration>
建立存放資料的DTO(/mysite/model/CharainfoDto.java)
以下僅供參考
package mysite.model;

public class CharainfoDto {
private String id;
private String title;
...其他參數

public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
...其他getter&setter
}

建立與DTO對應的sqlMap檔(/mysite/sqlMap/characterData.xml)

<?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="cypherswiki">

<resultMap id="charainfo" type="mysite.model.CharainfoDto">
<result property="id" column="ID" jdbcType="VARCHAR" />
<result property="title" column="TITLE" jdbcType="VARCHAR" />
...中略
</resultMap>

<select id="getCharainfo" parameterType="String" resultMap="charainfo"
timeout="1000">
    <![CDATA[
    SELECT *
    FROM CYPHERSWIKI.CHARAINFO
    WHERE ID = #{id}
    ]]>
</select>

<select id="getCharaName" parameterType="String" resultType="String" timeout="1000">
    <![CDATA[
    SELECT charaName_ch
    FROM CYPHERSWIKI.CHARAINFO
    WHERE ID = #{id}
    ]]>
</select>
</mapper>

建立存取資料的DAO&interface(/mysite/dao/CharacterDataDao.java、ICharacterDataDao.java)
package mysite.dao;

import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.sql.SQLException;import java.io.IOException;
import mysite.model.CharainfoDto;

public class CharacterDataDao extends SqlSessionDaoSupport implements ICharacterDataDao{
@Override
public CharainfoDto getCharainfoDto(String id) throws SQLException, IOException {
CharainfoDto charainfoDto = getSqlSession().selectOne("getCharainfo", id);
return charainfoDto;
}
@Override
public String getCharaName(String id) throws SQLException, IOException {
String charaName = getSqlSession().selectOne("getCharaName", id);
return charaName;
}
}

建立service&interface (/mysite/service/CypherswikiService.java、ICypherswikiService.java)

package mysite.service;

import java.io.IOException;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import mysite.dao.CharacterDataDao;
import mysite.model.CharainfoDto;

@Service("CypherswikiService")
public class CypherswikiService implements ICypherswikiService {

@Autowired
CharacterDataDao characterDataDao = new CharacterDataDao();

/**
* 根據id取得角色中文名稱
*/
@Override
public String getCharaName(String id) throws SQLException, IOException {
String charaName = characterDataDao.getCharaName("Loras");
return charaName;
}
/**
* 根據id取得角色資料DTO
*/
@Override
public CharainfoDto getCharainfo(String id) throws SQLException, IOException {
CharainfoDto charaInfo = (CharainfoDto) characterDataDao.getCharainfoDto(id);
return charaInfo;
}
}

修改Controller

package mysite.Controller;

import java.io.IOException;
import java.sql.SQLException;
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 mysite.model.CharainfoDto;
import mysite.service.CypherswikiService;

@Controller
public class CypherswikiController {

@Autowired
CypherswikiService cypherswikiService = new CypherswikiService();

@RequestMapping("hello")
    public String to_hello(String user, Model model) throws SQLException, IOException {
model.addAttribute("user", user);

String charaName = cypherswikiService.getCharaName("Loras");
CharainfoDto charainfo =cypherswikiService.getCharainfo("Loras");

model.addAttribute("charaNameFromSqlMapping", charaName);
model.addAttribute("charainfoFromSqlMapping", charainfo);
        return "hello";
    }

@RequestMapping("hello2")
    public String to_hello2(String user, Model model) {
        model.addAttribute("user", user);
        return "hello2";
    }
}
修改hello.jsp
<%@ page contentType = "text/html;charset=UTF-8" %>
<div>
    <h1>Hello ${user}!!</h1>
    <br />
經由myBatis取得角色名= ${charaNameFromSqlMapping}<br />
經由myBatis取得角色全名= ${charainfoFromSqlMapping.fullName}<br />
<br />
    <a href="hello2?user=你在第二頁">hello2.html</a>
</div>



2016年5月23日 星期一

加入bootstrap

加入bootstrap
webapp>建立static_res>建立css 與 script 資料夾
下載所需的css和js檔,放置於/static_res/css/與/static_res/script/資料夾中
【SpringConfig.xml】加入:
    <!-- enable transaction demarcation with annotations -->
    <mvc:annotation-driven />
    <!-- Static resource mapping -->
    <mvc:resources mapping="/styles/**" location="/static_res/css/" />
    <mvc:resources mapping="/script/**" location="/static_res/script/" />
【defaultLayout.jsp】

在<!DOCTYPE html>前加入:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://tiles.apache.org/tags-tiles-extras" prefix="tilesx"%>
<tilesx:useAttribute id="csslist" name="csssList" classname="java.util.List" />
<tilesx:useAttribute id="jslist" name="scriptsList" classname="java.util.List" />

在<head>中加入:
    <!-- CSS -->
    <c:forEach var="item" items="${csslist}">
        <link rel="stylesheet" href="${url}${item}" />
    </c:forEach>
    <!-- CSS End-->

在<body>的最末段加入:
    <!-- Script -->
    <c:forEach var="item" items="${jslist}">
        <script type="text/javascript" src="${url}${item}"></script>
    </c:forEach>
    <!-- Script End-->
【defaultTemplate.xml】加入:

<!-- default CSS -->
<put-list-attribute name="csssList" cascade="true">
    <add-attribute value="styles/sb-admin-2.css"/>
</put-list-attribute>

<!-- default Script -->
<put-list-attribute name="scriptsList" cascade="true">
    <add-attribute value="script/jquery.js" />
    <add-attribute value="script/sb-admin-2.js" />
</put-list-attribute>
測試用的hello.jsp修改為:

<div class="container">
  <div class="jumbotron">
  <h1>Hello ${user}!!</h1>
<p>meet bootstrap!</p>
<br />
        <a class="btn btn-primary" href="hello_Tiles">helloTiles.html</a>
</div>
</div>
view>新增testTable.jsp
【testTable.jsp】
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<div class="container">
    <div class="row">
        <div class="col-lg-12">
            <button type="button" id="delete" 
                class="btn btn-primary">delete</button>
            <button type="button" id="add" 
                class="btn btn-primary">create</button>
            <table class="table table-striped table-bordered table-hover"
                id="dataTables">
                <thead>
                    <tr>
                        <th></th>
                        <th>ID</th>
                        <th>Name</th>
                        <th>JobTitle</th>
                        <th>E-mail</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <th></th>
                        <th>ID</th>
                        <th>Name</th>
                        <th>JobTitle</th>
                        <th>E-mail</th>
                    </tr>
                    <tr>
                        <th></th>
                        <th>ID</th>
                        <th>Name</th>
                        <th>JobTitle</th>
                        <th>E-mail</th>
                    </tr>
                </tbody>
            </table>
            <form name="myform" method="post">
                <input type="hidden" id="userid" name="id" />
                <input type="hidden" id="action" name="action" />
            </form>
        </div>
    </div>
</div>

基本mvc架構 & 加入tiles

基本mvc架構
建立maven project (web-app)
project>右鍵>propeties>ProjectFacets>Runtimes>choose a runable server
【POM.xml】
<properties>
    <org.springframework-version>4.1.6.RELEASE</org.springframework-version>
    <jstl-version>1.2</jstl-version>
    <jstl-servlet-api-version>2.5</jstl-servlet-api-version>
</properties>

<dependencies>
    <!-- Spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>

    <!-- Servlet -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>${jstl-version}</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>${jstl-servlet-api-version}</version>
    </dependency>
</dependencies>
【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:jsp="http://java.sun.com/xml/ns/javaee/jsp"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">

<servlet>
    <servlet-name>SpringServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- if without "init-param", framework will try to load the application
    context from a file named [servlet-name]-servlet.xml in WEB-INF directory. -->
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/config/SpringConfig.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>SpringServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
webapp>WEB-INF>建立config>建立SpringConfig.xml

【SpringConfig.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:mvc="http://www.springframework.org/schema/mvc"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-4.1.xsd">
 
    <!-- basic -->
    <context:component-scan base-package="my.web" />

    <!-- basic -->
    <!-- view , the rules defined to resolve the view names -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- basic -->
        <property name="prefix" value="/WEB-INF/page/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>
src>main>建立java>建立package(my.web.Controller)>建立MainController.java

【MainController.java】
package my.web.Controller;

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

@Controller
public class MainController {
  @RequestMapping("hello")
  public String to_hello(String user, Model model) {
        model.addAttribute("user", user);
  return "hello";
  }
}
測試用的hello.jsp
放置於WEB-INF/page/目錄下
<%@ page contentType = "text/html;charset=UTF-8" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Hello page</title>
</head>
<body>
    <div>
        <h1>Hello ${user}!!</h1>
    </div>
</body>
</html>
其他:
在專案上右鍵>MAVEN>update project
如果無法升級至Dynamic Web Module 2.5
在專案上右鍵>properties>project facets把Dynamic Web Module 取消勾選,再update一次


將eclipse的window>preference>General>Workspace>Text file encoding改為UTF-8




加入tiles
【POM.xml】

<properties>
    <tiles-version>3.0.5</tiles-version>
</properties>

<dependencies>
    <!-- Tiles basic -->
    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-jsp</artifactId>
        <version>${tiles-version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-servlet</artifactId>
        <version>${tiles-version}</version>
    </dependency>
    <!-- Tiles others -->
    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-template</artifactId>
        <version>${tiles-version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-el</artifactId>
        <version>${tiles-version}</version>
    </dependency>
</dependencies>
【SpringConfig.xml】

更改 viewResolver.order:
<!-- 因為使用了其他的ViewResolver(ex:tiles),因此必須設定解析順序 -->
<property name="order" value="#{tilesViewResolver.order+1}" />

加入:
<!-- Tiles View -->
<bean id="tilesViewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
        value="org.springframework.web.servlet.view.tiles3.TilesView" />
<property name="order" value="1" />
</bean>
<!-- 加載tiles配置文件 -->
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list> <!-- 設定檔路徑 -->
<value>/WEB-INF/config/defaultTemplate.xml</value>
<value>/WEB-INF/config/tiles-definitions.xml</value>
</list>
  </property>
<!-- 定義preparerFactory的種類(有2種: SimpleSpring & SpringBean) -->
<property name="preparerFactoryClass"
value="org.springframework.web.servlet.view.tiles3.SimpleSpringPreparerFactory" />
</bean>
WEB-INF>config>建立tiles-definitions.xml

【tiles-definitions.xml】

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

<!-- XML reading definitions for tiles -->
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN"
"http://tiles.apache.org/dtds/tiles-config_3_0.dtd">

<tiles-definitions>

  <definition name="default" extends="defaultTemplate">
  </definition>

  <definition name="hello" extends="defaultTemplate">
  <put-attribute name="content" value="/WEB-INF/page/hello.jsp" />
  </definition>

</tiles-definitions>
WEB-INF>config>建立defaultTemplate.xml

【defaultTemplate.xml】

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

<!DOCTYPE tiles-definitions PUBLIC
        "-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN"
        "http://tiles.apache.org/dtds/tiles-config_3_0.dtd">

<tiles-definitions>
  <definition name="defaultTemplate"
        template="/WEB-INF/page/defaultview/defaultLayout.jsp">
  <!-- put-attribute name="navigation_bar" value="/WEB-INF/page/navigation_bar.jsp" / -->
  <put-attribute name="header" value="/WEB-INF/page/defaultview/defaultHeader.jsp" />
  <put-attribute name="content" value="/WEB-INF/page/defaultview/defaultContent.jsp"/>

  <!-- default CSS -->
  <!-- put-list-attribute name="csssList" cascade="true">
  <add-attribute value="styles/datepicker.css"/>
  </put-list-attribute -->

  <!-- default Script -->
    <!-- put-list-attribute name="scriptsList" cascade="true" >
  <add-attribute value="script/jquery.js" / >
  </put-list-attribute -->
  </definition>
</tiles-definitions>
WEB-INF>page>建立defaultview>建立defaultLayout.jsp/defaultHeader.jsp/defaultContent.jsp

【defaultLayout.jsp】
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<tiles:insertAttribute name="header" />
<tiles:insertAttribute name="content" />
</body>
</html>

【defaultHeader.jsp】
<%@ page contentType = "text/html;charset=UTF-8" %>
<div>
<h1>Default Header</h1>
</div>

【defaultContent.jsp】
<%@ page contentType = "text/html;charset=UTF-8" %>
<div>
<h1>Default Content</h1>
</div>
【hello.jsp】修改為:
<%@ page contentType = "text/html;charset=UTF-8" %>
<div>
    <h1>Hello ${user}!!</h1>
    <br />
    <a href="hello_Tiles">helloTiles.html</a>
</div>