---
# System prepended metadata

title: Spring 2/25上課內容
tags: [Spring]

---

# Spring 2/25上課內容
###### tags: `Spring`

# 65 Spring動態網站開發(由Java類別(Java-Based-Configuration)提供組裝資訊)
* 方法上註冊@Bean

![](https://i.imgur.com/JUkjZzv.png)
***
![](https://i.imgur.com/4uqcgZ8.png)

# 66 Spring動態網站開發
![](https://i.imgur.com/QEmrYdB.png)
***
![](https://i.imgur.com/kZpjo0g.png)
@Configuration主態設定

# 67 Spring動態網站開發
![](https://i.imgur.com/iaNNR53.png)
***
![](https://i.imgur.com/LGctIUb.png)

## SpringJavaConfig
![](https://i.imgur.com/fpHs8nT.png)
用過了DAO
![](https://i.imgur.com/RXl8xQs.png)
![](https://i.imgur.com/jmiWbhH.png)
```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
![](https://i.imgur.com/yUC9QAh.png)
2個只能存在一個
![](https://i.imgur.com/hF1uIVE.png)
![](https://i.imgur.com/TFRqwKZ.png)
```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
![](https://i.imgur.com/o5vfAE2.png)
```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動態網站開發
![](https://i.imgur.com/wW2jkCF.png)
***
![](https://i.imgur.com/DS8w3bH.png)

## DemoSpELAction
![](https://i.imgur.com/HxuY6HK.png)
```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的生命週期)
![](https://i.imgur.com/PZuFW0Y.png)

# 70 Spring動態網站開發
![](https://i.imgur.com/8AeJhPv.png)
***
![](https://i.imgur.com/CKB085b.png)

# 71 Spring動態網站開發
![](https://i.imgur.com/GMDYeK7.png)
* session沒關掉之前都會存在
***
![](https://i.imgur.com/tJwIb5z.png)
* **lazy-init="true"**
    * 不馬上產生

# 72
![](https://i.imgur.com/HlkLhdz.png)

## 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動態網站開發
![](https://i.imgur.com/0Tc1rSu.png)
***
![](https://i.imgur.com/CAqYHZQ.png)

# 74 Spring動態網站開發
![](https://i.imgur.com/0iOXCiE.png)
***
![](https://i.imgur.com/wBPZtw5.png)

# 75 Spring動態網站開發
![](https://i.imgur.com/M6U4OUV.png)
***
![](https://i.imgur.com/rFHTZJe.png)

## opm.xml
![](https://i.imgur.com/r4d7UHx.png)
```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動態網站開發
![](https://i.imgur.com/R1LjuhG.png)
 
## House
![](https://i.imgur.com/j8dty7K.png)
```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
![](https://i.imgur.com/kPREDGm.png)
```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動態網站開發
![](https://i.imgur.com/rQ9nK2s.png)
***
![](https://i.imgur.com/odZZKq3.png)

## HouseDao
![](https://i.imgur.com/DDooCHT.png)
```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動態網站開發
![](https://i.imgur.com/Hf7EWGH.png)
![](https://i.imgur.com/lyJg4XF.png)
[api](https://docs.spring.io/spring-framework/docs/current/javadoc-api/)
![](https://i.imgur.com/w9w1D1p.png)

## HouseService
![](https://i.imgur.com/LXjCIwV.png)
```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動態網站開發
![](https://i.imgur.com/AYgsUYU.png)
***
![](https://i.imgur.com/Poe023E.png)

## 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應用程式的支援)
![](https://i.imgur.com/pml4Srx.png)

# 81 Spring動態網站開發
![](https://i.imgur.com/YfdF82x.png)
***
![](https://i.imgur.com/x0EIqYg.png)

# 82 Spring動態網站開發
![](https://i.imgur.com/pGsE2iK.png)
***
![](https://i.imgur.com/ocYd9A1.png)

# 83 Spring動態網站開發
![](https://i.imgur.com/aKAB7lb.png)
***
![](https://i.imgur.com/n1V5QFZ.png)

## 實作新專案
![](https://i.imgur.com/zIKOatK.jpg)
![](https://i.imgur.com/h8fSSV8.png)
![](https://i.imgur.com/oSwFhi4.png)
![](https://i.imgur.com/1XrNug8.png)
![](https://i.imgur.com/a2DwcZo.png)
![](https://i.imgur.com/qBuor0A.png)
![](https://i.imgur.com/zZJB3Wy.png)
![](https://i.imgur.com/we7pP7D.png)
![](https://i.imgur.com/MdQSZmS.png)
![](https://i.imgur.com/skdU4st.png)
![](https://i.imgur.com/IFHvTMJ.png)
![](https://i.imgur.com/kBphRe2.png)
![](https://i.imgur.com/OnsP6f3.png)
![](https://i.imgur.com/QH6047O.png)
![](https://i.imgur.com/Zb7OBk1.png)
![](https://i.imgur.com/0qNFcP8.png)
![](https://i.imgur.com/8hgxlJ4.png)
![](https://i.imgur.com/dUv1cgE.png)
![](https://i.imgur.com/KmOxXsz.png)
![](https://i.imgur.com/kCHwzgW.png)

# 86 Spring動態網站開發
![](https://i.imgur.com/1AKo8W8.png)
[bean api](https://docs.spring.io/spring-framework/docs/current/javadoc-api/)

# 87 Spring動態網站開發
![](https://i.imgur.com/aclg9Pq.png)

## DemoHouseServletAction
![](https://i.imgur.com/20zY0kF.png)
![](https://i.imgur.com/50zautf.png)
![](https://i.imgur.com/vJWtupG.jpg)
```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的主要工作)
![](https://i.imgur.com/XV4iMPr.png)
***
![](https://i.imgur.com/up8M9Is.png)

# 89 Spring動態網站開發
![](https://i.imgur.com/z9WDfb6.png)
***
![](https://i.imgur.com/miZJ7kY.png)

# 90 Spring動態網站開發
![](https://i.imgur.com/ggortJk.png)
***
![](https://i.imgur.com/8Sh62SU.png)

# 91 Spring動態網站開發
![](https://i.imgur.com/QfNaTfq.png)
## 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動態網站開發
![](https://i.imgur.com/v5qTJKE.png)
***
![](https://i.imgur.com/R17M78c.png)

# 93 Spring動態網站開發
![](https://i.imgur.com/k1ORkbh.png)

## HouseBeanDao
![](https://i.imgur.com/vLdWzmb.png)
![](https://i.imgur.com/wyPeDvC.png)
```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
![](https://i.imgur.com/zq0DDjD.png)
```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動態網站開發
![](https://i.imgur.com/ocPg3U1.png)



##  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
![](https://i.imgur.com/Dl5xBaC.png)
```click=
<prop key="hibernate.current_session_context_class">thread</prop>
```
## HouseBeanDao
![](https://i.imgur.com/DDJCYVV.png)
@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動態網站開發
![](https://i.imgur.com/5Wj0h21.png)

# 99 Spring動態網站開發
![](https://i.imgur.com/6sJSvhr.png)
***
![](https://i.imgur.com/dII9kV5.png)

# 100 Spring動態網站開發
![](https://i.imgur.com/QCdQBAb.png)
***
![](https://i.imgur.com/UI6VW33.png)

# 101 Spring動態網站開發
![](https://i.imgur.com/m1FhNu7.png)

# 101 (重點)Spring動態網站開發
![](https://i.imgur.com/jkJHJXk.png)

# 102 Spring動態網站開發 
* 偵測有沒有錯
![](https://i.imgur.com/lYgwv4C.png)
***
![](https://i.imgur.com/FdrF821.png)

# 103 Spring動態網站開發 
![](https://i.imgur.com/Z8corgP.png)
***
![](https://i.imgur.com/yOWJ1Rb.png)
* /* 掌握所有的網址

# 104 Spring動態網站開發 
![](https://i.imgur.com/tCkxQFP.png)

# 105 Spring動態網站開發 
![](https://i.imgur.com/OZE4iZ2.png)
***
![](https://i.imgur.com/PbkvtoW.png)
執行前 執行後

## OpenSessionInViewFilter
![](https://i.imgur.com/jM6FuJv.png)
![](https://i.imgur.com/MIVQPfu.png)
```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) 
![](https://i.imgur.com/jRQizkk.png)

# 113 Spring動態網站開發
![](https://i.imgur.com/isBB73I.png)
***
![](https://i.imgur.com/8oMhMcz.png)

# 114 Spring動態網站開發
![](https://i.imgur.com/UvixyrA.png)
***
![](https://i.imgur.com/CHB8Hx4.png)

# 115 Spring動態網站開發
![](https://i.imgur.com/PqWgQjd.png)

# 116 Spring動態網站開發
![](https://i.imgur.com/qjrZD8K.png)

# 117 Spring動態網站開發
![](https://i.imgur.com/9ruzHTs.png)
***
* 定義
![](https://i.imgur.com/rbejAgd.png)

# 118 Spring動態網站開發
* 定義完準備切入
![](https://i.imgur.com/NbwPPuE.png)
***
* aop 切入點
* checkLogin* 切入位址
![](https://i.imgur.com/ZEBdE7f.png)
