# Spring 2/25上課內容
###### tags: `Spring`
# 65 Spring動態網站開發(由Java類別(Java-Based-Configuration)提供組裝資訊)
* 方法上註冊@Bean

***

# 66 Spring動態網站開發

***

@Configuration主態設定
# 67 Spring動態網站開發

***

## SpringJavaConfig

用過了DAO


```clike=
package tw.leonchen.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tw.leonchen.model.LoginDao;
import tw.leonchen.model.LoginService;
@Configuration
public class SpringJavaConfig {
@Bean(value = "myAccessDao")
public LoginDao myloginDao() {
LoginDao loginDao = new LoginDao();
return loginDao;
}
@Bean(value = "myAccessService")
public LoginService myLoginService() {
LoginService loginService = new LoginService();
loginService.setLoginDao(myloginDao());
return loginService;
}
}
```
## DemoLoginJavaConfigAction

2個只能存在一個


```clike=
package tw.leonchen.action;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import tw.leonchen.config.SpringJavaConfig;
import tw.leonchen.model.LoginDao;
import tw.leonchen.model.LoginService;
public class DemoLoginJavaConfigAction {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringJavaConfig.class);
LoginDao lDao1 = context.getBean("myAccessDao", LoginDao.class);
boolean status1 = lDao1.checkLogin("john", "test123");
System.out.println("status1:" + status1);
// LoginDao lDao2 = context.getBean("myloginDao", LoginDao.class);
// boolean status2 = lDao2.checkLogin("john2", "test123");
// System.out.println("status2:" + status2);
LoginService lService1 = context.getBean("myAccessService", LoginService.class);
boolean status3 = lService1.checkLogin("mary", "123Test");
System.out.println("status3:" + status3);
context.close();
}
}
```
## DemoAnimalJavaConfigAction

```clike=
package tw.leonchen.action;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import tw.leonchen.config.SpringJavaConfig;
import tw.leonchen.model.AnimalDao;
public class DemoAnimalJavaConfigAction {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringJavaConfig.class);
AnimalDao aDao1 = context.getBean("myAnimalDao", AnimalDao.class);
aDao1.showDetails();
context.close();
}
}
```
## AnimalDao
```clike=
package tw.leonchen.model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
//@Repository(value = "animalDao")
public class AnimalDao {
//@Autowired //@Qualifier(value = "animal2")
private Animal animal;
public void setAnimal(Animal animal) {
this.animal = animal;
}
public void showDetails() {
System.out.println("id:" + animal.getId());
System.out.println("name:" + animal.getName());
System.out.println("continent:" + animal.getContinent());
}
}
```
## SpringJavaConfig
```clike=
package tw.leonchen.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tw.leonchen.model.Animal;
import tw.leonchen.model.AnimalDao;
import tw.leonchen.model.LoginDao;
import tw.leonchen.model.LoginService;
@Configuration
public class SpringJavaConfig {
@Bean(value = "myAccessDao")
public LoginDao myloginDao() {
LoginDao loginDao = new LoginDao();
return loginDao;
}
@Bean(value = "myAccessService")
public LoginService myLoginService() {
LoginService loginService = new LoginService();
loginService.setLoginDao(myloginDao());
return loginService;
}
@Bean
public Animal myAnimal1() {
Animal a1 = new Animal();
a1.setId(1002);
a1.setName("Bird");
a1.setContinent("Europe");
return a1;
}
@Bean
public AnimalDao myAnimalDao() {
AnimalDao aDao = new AnimalDao();
aDao.setAnimal(myAnimal1());
return aDao;
}
}
```
## Animal
```clike=
package tw.leonchen.model;
import org.springframework.stereotype.Component;
//@Component(value="animal")
public class Animal {
private int id;
private String name;
private String continent;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContinent() {
return continent;
}
public void setContinent(String continent) {
this.continent = continent;
}
}
```
# 68 Spring動態網站開發

***

## DemoSpELAction

```clike=
package tw.leonchen.action;
import java.util.ArrayList;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import tw.leonchen.model.TruckBean;
public class DemoSpELAction {
public static void main(String[] args) {
ExpressionParser parser1 = new SpelExpressionParser();
Expression express = parser1.parseExpression("'Hola,' + ' Amigo !!'");
String result = express.getValue().toString();
System.out.println("result:" + result);
EvaluationContext ctex = new StandardEvaluationContext();
TruckBean truck1 = new TruckBean(1005,"nissan");
TruckBean truck2 = new TruckBean(1006,"ferrari");
ArrayList<TruckBean> trucks = new ArrayList<TruckBean>();
trucks.add(truck1);
trucks.add(truck2);
ctex.setVariable("trucks", trucks);
String brand = parser1.parseExpression("#trucks[1].brand").getValue(ctex, String.class);
System.out.println("brand:" + brand);
}
}
```
# 69 Spring動態網站開發(ioc容器與Bean的生命週期)

# 70 Spring動態網站開發

***

# 71 Spring動態網站開發

* session沒關掉之前都會存在
***

* **lazy-init="true"**
* 不馬上產生
# 72

## DemoTreeBeanAction
```clike=
package tw.leonchen.action;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import tw.leonchen.model.TreeBean;
public class DemoTreeBeanAction {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.config.xml");
TreeBean tBean1 = context.getBean("tree", TreeBean.class);
System.out.println("Name:" + tBean1.getName());
System.out.println("Age:" + tBean1.getAge());
TreeBean tBean2 = context.getBean("tree", TreeBean.class);
System.out.println("Name:" + tBean2.getName());
System.out.println("Age:" + tBean2.getAge());
System.out.println("tBean1 hashcode:" + tBean1.hashCode());
System.out.println("tBean2 hashcode:" + tBean2.hashCode());
context.close();
}
}
```
## TreeBean
```clike=
package tw.leonchen.model;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component("tree")
@Scope("singleton") //@Scope("prototype")
@PropertySource("classpath:tree.properties")
public class TreeBean {
//@Value("#{props.name}")
@Value("${name}")
private String name;
//@Value("#{props.age}")
@Value("${age}")
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
```
# 73 Spring動態網站開發

***

# 74 Spring動態網站開發

***

# 75 Spring動態網站開發

***

## opm.xml

```clike=
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>JavaProject</groupId>
<artifactId>JavaProject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>8.4.1.jre11</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.28.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.3.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>5.3.4</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.3.4</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<release>11</release>
</configuration>
</plugin>
</plugins>
</build>
</project>
```
# 76 Spring動態網站開發

## House

```clike=
package tw.leonchen.model;
public class House {
private int houseid;
private String housename;
public int getHouseid() {
return houseid;
}
public void setHouseid(int houseid) {
this.houseid = houseid;
}
public String getHousename() {
return housename;
}
public void setHousename(String housename) {
this.housename = housename;
}
}
```
## SQL House

```clike=
use LeonPower;
create table House(
houseid int not null primary key identity(1000,1),
housename nvarchar(50) not null
);
select * from House
Insert Into House(housename) Values('Happy House');
select * from House;
```
* nvarchar 是 varchar 的一倍
# 77 Spring動態網站開發

***

## HouseDao

```clike=
package tw.leonchen.model;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
public class HouseDao {
private DataSource datasource;
private House hBean;
public HouseDao(DataSource datasource) {
this.datasource = datasource;
}
public House select(int houseid) throws SQLException {
Connection conn = datasource.getConnection();
String sqlstr = "Select * From House Where houseid=?";
PreparedStatement preState = conn.prepareStatement(sqlstr);
preState.setInt(1, houseid);
ResultSet rs = preState.executeQuery();
if(rs.next()) {
hBean = new House();
hBean.setHouseid(rs.getInt(1));
hBean.setHousename(rs.getString(2));
}
rs.close();
preState.close();
conn.close();
return hBean;
}
}
```
# 78 Spring動態網站開發


[api](https://docs.spring.io/spring-framework/docs/current/javadoc-api/)

## HouseService

```clike=
package tw.leonchen.model;
import java.sql.SQLException;
public class HouseService {
private HouseDao houseDao;
public HouseService(HouseDao houseDao) {
this.houseDao = houseDao;
}
public House select(int houseid) throws SQLException {
return houseDao.select(houseid);
}
}
```
## beans
```clike=
<?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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<context:component-scan base-package="tw.leonchen"/>
<bean id="sqlserverDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="url" value="jdbc:sqlserver://localhost:1433;databaseName=LeonPower"/>
<property name="username" value="watcher"/>
<property name="password" value="P@ssw0rd"/>
</bean>
<bean id="animal1" class="tw.leonchen.model.Animal">
<property name="id" value="1001"/>
<property name="name" value="camel"/>
<property name="continent" value="africa"/>
</bean>
<bean id="animal2" class="tw.leonchen.model.Animal">
<property name="id" value="1002"/>
<property name="name" value="panda"/>
<property name="continent" value="asia"/>
</bean>
<!-- LogProvider logProvider = new LogProvider(); -->
<bean id="logProvider" class="tw.leonchen.util.LogProvider"/>
<bean id="string0" name="string1, string2" class="java.lang.String" scope="prototype">
<constructor-arg value="Test Information"/>
</bean>
<!-- LoginDao loginDao = new LoginDao(); -->
<bean id="loginDao" class="tw.leonchen.model.LoginDao"/>
<!-- LoginService loginService2 = new LoginService(loginDao); -->
<bean id="loginService2" class="tw.leonchen.model.LoginService">
<constructor-arg ref="loginDao"/>
</bean>
<!--
LoginService loginService1 = new LoginService();
loginService1.setLoginDao(loginDao);
-->
<bean id="loginService1" class="tw.leonchen.model.LoginService">
<property name="loginDao" ref="loginDao"/>
</bean>
<bean id="myDate" class="java.util.Date"/>
<bean id="dateDao" class="tw.leonchen.model.DateDao">
<constructor-arg ref="myDate"/>
</bean>
<bean id="dateDaoMap" class="tw.leonchen.model.DateDao">
<constructor-arg>
<map>
<entry key="fruit1" value="banana"/>
<entry key="fruit2" value="apple"/>
</map>
</constructor-arg>
</bean>
<bean id="dateDaoMsg1" class="tw.leonchen.model.DateDao">
<property name="msg" value="good day"/>
</bean>
<bean id="dateDaoMsg2" class="tw.leonchen.model.DateDao" p:msg="have a good time"/>
<bean id="truckBean" class="tw.leonchen.model.TruckBean">
<constructor-arg name="id" value="100"/>
<constructor-arg name="brand" value="toyota"/>
</bean>
<bean id="fordTruck" class="tw.leonchen.model.TruckBeanStaticFactory" factory-method="getTruckBean">
<constructor-arg value="1"/>
</bean>
<bean id="teslaTruck" class="tw.leonchen.model.TruckBeanStaticFactory" factory-method="getTruckBean">
<constructor-arg value="2"/>
</bean>
<bean id="truckBeanFactory" class="tw.leonchen.model.TruckBeanFactory">
<property name="map">
<map>
<entry key="1">
<bean class="tw.leonchen.model.TruckBean">
<property name="id" value="5"/>
<property name="brand" value="bmw"/>
</bean>
</entry>
<entry key="2">
<bean class="tw.leonchen.model.TruckBean">
<property name="id" value="6"/>
<property name="brand" value="benz"/>
</bean>
</entry>
</map>
</property>
</bean>
<bean id="bmwTruck" factory-bean="truckBeanFactory" factory-method="getTruckBean">
<constructor-arg value="1"/>
</bean>
<bean id="benzTruck" factory-bean="truckBeanFactory" factory-method="getTruckBean">
<constructor-arg value="2"/>
</bean>
<bean id="props" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location">
<value>classpath:tree.properties</value>
</property>
</bean>
</beans>
```
# 79 Spring動態網站開發

***

## HouseService
```clike=
package tw.leonchen.model;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("houseService")
public class HouseService {
@Autowired
private HouseDao houseDao;
public HouseService(HouseDao houseDao) {
this.houseDao = houseDao;
}
public House select(int houseid) throws SQLException {
return houseDao.select(houseid);
}
}
```
## HouseDao
```clike=
package tw.leonchen.model;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
@Repository("houseDao")
public class HouseDao {
private DataSource datasource;
private House hBean;
@Autowired
public HouseDao(@Qualifier("sqlserverDataSource") DataSource datasource) {
this.datasource = datasource;
}
public House select(int houseid) throws SQLException {
Connection conn = datasource.getConnection();
String sqlstr = "Select * From House Where houseid=?";
PreparedStatement preState = conn.prepareStatement(sqlstr);
preState.setInt(1, houseid);
ResultSet rs = preState.executeQuery();
if(rs.next()) {
hBean = new House();
hBean.setHouseid(rs.getInt(1));
hBean.setHousename(rs.getString(2));
}
rs.close();
preState.close();
conn.close();
return hBean;
}
}
```
## House
```clike=
package tw.leonchen.model;
import org.springframework.stereotype.Component;
@Component("house")
public class House {
private int houseid;
private String housename;
public int getHouseid() {
return houseid;
}
public void setHouseid(int houseid) {
this.houseid = houseid;
}
public String getHousename() {
return housename;
}
public void setHousename(String housename) {
this.housename = housename;
}
}
```
## DemoHouseAction
```clike=
package tw.leonchen.action;
import java.sql.SQLException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import tw.leonchen.model.House;
import tw.leonchen.model.HouseService;
public class DemoHouseAction {
public static void main(String[] args) throws SQLException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.config.xml");
HouseService hService = context.getBean("houseService", HouseService.class);
House hBean = hService.select(1000);
System.out.println("House ID:" + hBean.getHouseid());
System.out.println("House Name:" + hBean.getHousename());
context.close();
}
}
```
# 80 Spring動態網站開發(Spring對Web應用程式的支援)

# 81 Spring動態網站開發

***

# 82 Spring動態網站開發

***

# 83 Spring動態網站開發

***

## 實作新專案




















# 86 Spring動態網站開發

[bean api](https://docs.spring.io/spring-framework/docs/current/javadoc-api/)
# 87 Spring動態網站開發

## DemoHouseServletAction



```clike=
package tw.leonchen.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import tw.leonchen.model.House;
import tw.leonchen.model.HouseService;
@WebServlet("/DemoHouseServletAction.do")
public class DemoHouseServletAction extends HttpServlet {
private static final long serialVersionUID = 1L;
private WebApplicationContext context;
public void init() throws ServletException {
ServletContext application = getServletContext();
context = WebApplicationContextUtils.getWebApplicationContext(application);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processAction(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processAction(request, response);
}
private void processAction(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
HouseService hService = context.getBean("houseService", HouseService.class);
try {
House hBean = hService.select(1000);
out.write("House ID:" + hBean.getHouseid() + "<br/>");
out.write("House Name:" + hBean.getHousename() + "<br/>");
} catch (SQLException e) {
e.printStackTrace();
}
out.close();
}
}
```
# 88 Spring動態網站開發(Spring整合Hibernate的主要工作)

***

# 89 Spring動態網站開發

***

# 90 Spring動態網站開發

***

# 91 Spring動態網站開發

## pom.xml
```clike=
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>SpringWebProject</groupId>
<artifactId>SpringWebProject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>8.4.1.jre11</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.28.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.3.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>5.3.4</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.3.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.3.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.3.4</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<release>11</release>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.3</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
</configuration>
</plugin>
</plugins>
</build>
</project>
```
# 92 Spring動態網站開發

***

# 93 Spring動態網站開發

## HouseBeanDao


```clike=
package tw.leonchen.model;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
@Repository("houseBeanDao")
public class HouseBeanDao {
private SessionFactory sessionFactory;
private Session session;
public HouseBeanDao(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public House select(int houseid) {
session = sessionFactory.getCurrentSession();
House hBean = session.get(House.class, houseid);
return hBean;
}
}
```
## HouseBeanService

```clike=
package tw.leonchen.model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("houseBeanService")
public class HouseBeanService {
@Autowired
private HouseBeanDao houseBeanDao;
public House select(int houseid) {
return houseBeanDao.select(houseid);
}
}
```
# 97 Spring動態網站開發

## beans
[api](https://docs.spring.io/spring-framework/docs/current/javadoc-api/)
org.springframework.orm.hibernate5.LocalSessionFactoryBean
```clike=
<?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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<context:component-scan base-package="tw.leonchen"/>
<!--
<bean id="sqlserverDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="url" value="jdbc:sqlserver://localhost:1433;databaseName=LeonPower"/>
<property name="username" value="watcher"/>
<property name="password" value="P@ssw0rd"/>
</bean>
-->
<bean id="sqlserverDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jndiJdbcConnSQLServer/SpringSystem"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="sqlserverDataSource"/>
<property name="packagesToScan" value="tw.leonchen"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<bean id="animal1" class="tw.leonchen.model.Animal">
<property name="id" value="1001"/>
<property name="name" value="camel"/>
<property name="continent" value="africa"/>
</bean>
<bean id="animal2" class="tw.leonchen.model.Animal">
<property name="id" value="1002"/>
<property name="name" value="panda"/>
<property name="continent" value="asia"/>
</bean>
<bean id="string0" name="string1, string2" class="java.lang.String" scope="prototype">
<constructor-arg value="Test Information"/>
</bean>
<!-- LoginDao loginDao = new LoginDao(); -->
<bean id="loginDao" class="tw.leonchen.model.LoginDao"/>
<!-- LoginService loginService2 = new LoginService(loginDao); -->
<bean id="loginService2" class="tw.leonchen.model.LoginService">
<constructor-arg ref="loginDao"/>
</bean>
<!--
LoginService loginService1 = new LoginService();
loginService1.setLoginDao(loginDao);
-->
<bean id="loginService1" class="tw.leonchen.model.LoginService">
<property name="loginDao" ref="loginDao"/>
</bean>
<bean id="myDate" class="java.util.Date"/>
<bean id="dateDao" class="tw.leonchen.model.DateDao">
<constructor-arg ref="myDate"/>
</bean>
<bean id="dateDaoMap" class="tw.leonchen.model.DateDao">
<constructor-arg>
<map>
<entry key="fruit1" value="banana"/>
<entry key="fruit2" value="apple"/>
</map>
</constructor-arg>
</bean>
<bean id="dateDaoMsg1" class="tw.leonchen.model.DateDao">
<property name="msg" value="good day"/>
</bean>
<bean id="dateDaoMsg2" class="tw.leonchen.model.DateDao" p:msg="have a good time"/>
<bean id="truckBean" class="tw.leonchen.model.TruckBean">
<constructor-arg name="id" value="100"/>
<constructor-arg name="brand" value="toyota"/>
</bean>
<bean id="fordTruck" class="tw.leonchen.model.TruckBeanStaticFactory" factory-method="getTruckBean">
<constructor-arg value="1"/>
</bean>
<bean id="teslaTruck" class="tw.leonchen.model.TruckBeanStaticFactory" factory-method="getTruckBean">
<constructor-arg value="2"/>
</bean>
<bean id="truckBeanFactory" class="tw.leonchen.model.TruckBeanFactory">
<property name="map">
<map>
<entry key="1">
<bean class="tw.leonchen.model.TruckBean">
<property name="id" value="5"/>
<property name="brand" value="bmw"/>
</bean>
</entry>
<entry key="2">
<bean class="tw.leonchen.model.TruckBean">
<property name="id" value="6"/>
<property name="brand" value="benz"/>
</bean>
</entry>
</map>
</property>
</bean>
<bean id="bmwTruck" factory-bean="truckBeanFactory" factory-method="getTruckBean">
<constructor-arg value="1"/>
</bean>
<bean id="benzTruck" factory-bean="truckBeanFactory" factory-method="getTruckBean">
<constructor-arg value="2"/>
</bean>
<bean id="props" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location">
<value>classpath:tree.properties</value>
</property>
</bean>
</beans>
```
## beans

```click=
<prop key="hibernate.current_session_context_class">thread</prop>
```
## HouseBeanDao

@Qualifier("sessionFactory")
## House
```clike=
package tw.leonchen.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.stereotype.Component;
@Component("house")
@Entity
@Table(name = "House")
public class House {
@Id
@Column(name = "HOUSEID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int houseid;
@Column(name="HOUSENAME")
private String housename;
public int getHouseid() {
return houseid;
}
public void setHouseid(int houseid) {
this.houseid = houseid;
}
public String getHousename() {
return housename;
}
public void setHousename(String housename) {
this.housename = housename;
}
}
```
# 98 Spring動態網站開發

# 99 Spring動態網站開發

***

# 100 Spring動態網站開發

***

# 101 Spring動態網站開發

# 101 (重點)Spring動態網站開發

# 102 Spring動態網站開發
* 偵測有沒有錯

***

# 103 Spring動態網站開發

***

* /* 掌握所有的網址
# 104 Spring動態網站開發

# 105 Spring動態網站開發

***

執行前 執行後
## OpenSessionInViewFilter


```clike=
package tw.leonchen.util;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
@WebFilter("/*")
public class OpenSessionInViewFilter implements Filter {
private WebApplicationContext context;
private SessionFactory sessionFactory;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
//String sessionFactoryBeanName = filterConfig.getInitParameter("sessionFactory");
ServletContext application = filterConfig.getServletContext();
context = WebApplicationContextUtils.getWebApplicationContext(application);
sessionFactory = context.getBean("sessionFactory", SessionFactory.class);
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
Session session = sessionFactory.getCurrentSession();
try {
session.beginTransaction();
System.out.println("Transaction Begin");
chain.doFilter(request, response);
System.out.println("Transaction Commit");
session.getTransaction().commit();
} catch (Exception e) {
System.out.println("Transaction Rollback");
session.getTransaction().rollback();
e.printStackTrace();
}
}
@Override
public void destroy() {
}
}
```
## DemoHouseServletAction
```clike=
package tw.leonchen.action;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import tw.leonchen.model.House;
import tw.leonchen.model.HouseBeanService;
@WebServlet("/DemoHouseServletAction.do")
public class DemoHouseServletAction extends HttpServlet {
private static final long serialVersionUID = 1L;
private WebApplicationContext context;
public void init() throws ServletException {
ServletContext application = getServletContext();
context = WebApplicationContextUtils.getWebApplicationContext(application);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processAction(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processAction(request, response);
}
private void processAction(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// HouseService hService = context.getBean("houseService", HouseService.class);
// try {
// House hBean = hService.select(1000);
// out.write("House ID:" + hBean.getHouseid() + "<br/>");
// out.write("House Name:" + hBean.getHousename() + "<br/>");
// } catch (SQLException e) {
// e.printStackTrace();
// }
HouseBeanService hbService1 = context.getBean("houseBeanService", HouseBeanService.class);
House hBean2 = hbService1.select(1000);
out.write("House ID2:" + hBean2.getHouseid() + "<br/>");
out.write("House Name2:" + hBean2.getHousename() + "<br/>");
out.close();
}
}
```
# 112 Spring動態網站開發(Spring框架提供的AOP)

# 113 Spring動態網站開發

***

# 114 Spring動態網站開發

***

# 115 Spring動態網站開發

# 116 Spring動態網站開發

# 117 Spring動態網站開發

***
* 定義

# 118 Spring動態網站開發
* 定義完準備切入

***
* aop 切入點
* checkLogin* 切入位址
