---
# System prepended metadata

title: SpringMVC 3/3上課內容
tags: [SpringMVC]

---

# SpringMVC 3/3上課內容
###### tags: `SpringMVC`

[老師云端](https://1drv.ms/u/s!Ans47I9-PkivwH8KqgNszZ8OKcZe)

# 39 SpringMVC動態網站開發實務
![](https://i.imgur.com/On0JS3W.png)
### 框架
![](https://i.imgur.com/VUdiXjF.png)


#### DemoDispatcherServletInitializer
![](https://i.imgur.com/PTe1aaE.png)
![](https://i.imgur.com/2t8AO9j.png)
```c=
package tw.leonchen.config;

import javax.servlet.Filter;

import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class DemoDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

	@Override
	protected Class<?>[] getRootConfigClasses() {
		return null;
	}

	@Override
	protected Class<?>[] getServletConfigClasses() {
		return new Class[] {SpringMVCJavaConfig.class};
	}

	@Override
	protected String[] getServletMappings() {
		return new String[]{"/"};
	}

	@Override
	protected Filter[] getServletFilters() {
		CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
		characterEncodingFilter.setEncoding("UTF-8");
		characterEncodingFilter.setForceEncoding(true);
		return new Filter[] {characterEncodingFilter};
	}


	
}
```

# 40 SpringMVC動態網站開發實務(框架如何產生回應)
![](https://i.imgur.com/buWqFl5.png)
![](https://i.imgur.com/o7jLi1y.png)
* id=邏輯名稱 name=網址

# 41 SpringMVC動態網站開發實務
![](https://i.imgur.com/9cCFXlz.png)
* **View**
    * 原來的資料表有隱密性 
    * 對開發者比較安全
***
![](https://i.imgur.com/qha8BeP.png)

# 42 SpringMVC動態網站開發實務
![](https://i.imgur.com/geU6NOk.png)

#### mvc-servlet.xml
[InternalResourceViewResolver](https://docs.spring.io/spring-framework/docs/current/javadoc-api/)
```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:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		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"/>
    <mvc:annotation-driven/>

    <bean id="helloControler" name="/hello.controller" class="tw.leonchen.controller.HelloController"/>
    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/WEB-INF/pages/"/>
      <property name="suffix" value=".jsp"/>
    </bean>

</beans>
```
#### pages
![](https://i.imgur.com/RDPTuBn.png)
* 原本
![](https://i.imgur.com/CyRh4jA.png)
* 放入pages
![](https://i.imgur.com/ZejfNWC.png)
![](https://i.imgur.com/gLvvfRK.png)

### profiles.jsp
![](https://i.imgur.com/XAz2K6d.png)
* 移入 須從Controller下手
#### ProfilesController
```clike=
package tw.leonchen.controller;

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

@Controller
public class ProfilesController {
	
	@RequestMapping(path = "/profilesMain.controller", method = RequestMethod.GET)
	public String profilesMainPage() {
		return "profiles";
	}

	@RequestMapping(path = "/profiles.controller", method = RequestMethod.POST)
	public String processAction(@RequestParam(name = "userName") String user, @RequestParam(name = "userAge") String age, Model m) {
        
		m.addAttribute("myUser", user);
        m.addAttribute("myAge", age);
        
        return "profilesResult";
	}
}

```
# 43 SpringMVC動態網站開發實務
![](https://i.imgur.com/wgxNEtp.png)
***
![](https://i.imgur.com/SNVkorV.png)

#### SpringMVCJavaConfig
```clike=
package tw.leonchen.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
//設定檔
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "tw.leonchen")
public class SpringMVCJavaConfig implements WebMvcConfigurer {
	
	@Bean
	public InternalResourceViewResolver viewResolver() {
		InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
		viewResolver.setPrefix("/WEB-INF/pages/");
		viewResolver.setSuffix(".jsp");
		viewResolver.setOrder(2);
		return viewResolver;
		
	}
	
	@Override
	public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
		configurer.enable();
	}
    
}


```
### 執行畫面網址
![](https://i.imgur.com/z5aVyVX.png)
黃色地方改成網址
![](https://i.imgur.com/96UNUSf.png)
執行成功
![](https://i.imgur.com/kL9n3fC.png)

# 44 SpringMVC動態網站開發實務
![](https://i.imgur.com/lheQMAt.png)

#### HelloController2
```clike=
package tw.leonchen.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

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


@Controller
public class HelloController2 {
	
	@RequestMapping(path = "/hello2Main.controller",method = RequestMethod.GET)
	public String processHello2Action() {
		return "form";
	}
	
	@RequestMapping(path = "/hello.controller2", method = RequestMethod.GET)//請求的映射關係
	public String processAction(HttpServletRequest request,HttpServletResponse response, Model m) { //4.
		String userName = request.getParameter("userName");
		Map<String, String> errors = new HashMap<String, String>();
		m.addAttribute("errors", errors); //1.

		
		if(userName==null || userName.length()==0) {
			errors.put("myName", "name is required");
		}
		
		if(errors!=null && !errors.isEmpty()) {
			return "form"; //2.
		}
		
		HttpSession session = request.getSession();
		session.setAttribute("name", userName);
		return "success"; //3.
	
	}
}

```

# 45 SpringMVC動態網站開發實務(存取資料庫與應用程式的架構)
![](https://i.imgur.com/c1nRGdw.png)

# 46 SpringMVC動態網站開發實務
![](https://i.imgur.com/nLLaL6J.png)
![](https://i.imgur.com/LMNteAV.png)
***
![](https://i.imgur.com/fraTLNf.png)

# 47 SpringMVC動態網站開發實務
![](https://i.imgur.com/PQwmbpu.png)
***
![](https://i.imgur.com/ylFGdzc.png)

#### beans.config.xml
![](https://i.imgur.com/MunH2P5.png)
![](https://i.imgur.com/E0KaRvc.png)
![](https://i.imgur.com/YmnRVzj.png)
![](https://i.imgur.com/0aQQ8Jy.png)
* 都選沒有版本的
![](https://i.imgur.com/XhaMyPK.png)

```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:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	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
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

	<context:annotation-config />
	<context:component-scan base-package="tw.leonchen"/>
	<mvc:annotation-driven />
	<tx:annotation-driven />

	<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 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>
	       <prop key="hibernate.current_session_context_class">thread</prop>
	     </props>
	  </property>
	</bean>
	
</beans>
```

# 48 SpringMVC動態網站開發實務
![](https://i.imgur.com/LvE6K2v.png)
***
![](https://i.imgur.com/DZFtqzA.png)

# 49 SpringMVC動態網站開發實務
![](https://i.imgur.com/94H2d4k.png)
* 嚴格檢查javaBean跟資料表還有tabel的大小寫有沒有一樣(太嚴格)
***
![](https://i.imgur.com/2NEReZY.png)
* xml 映射關係

# 50 SpringMVC動態網站開發實務
![](https://i.imgur.com/q3WzSkF.png)
***
![](https://i.imgur.com/g5YawQT.png)

#### beans.config.xml
[HibernateTransactionManager](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/orm/hibernate5/HibernateTransactionManager.html)
```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:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	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
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:annotation-config/>
    <context:component-scan base-package="tw.leonchen"/>
    <mvc:annotation-driven/>
    <tx:annotation-driven/>
    
    <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 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>
	       <prop key="hibernate.current_session_context_class">thread</prop>
	     </props>
	  </property>
	</bean>
	
	<bean id="transactionMamager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
	   <property name="sessionFactory" ref="sessionFactory"/>
	</bean>

</beans>

```

# 51 SpringMVC動態網站開發實務
![](https://i.imgur.com/rVmIuD2.png)
***
![](https://i.imgur.com/xtwu2LL.png)

# 52 SpringMVC動態網站開發實務
![](https://i.imgur.com/8QSXWrS.png)

# 53 SpringMVC動態網站開發實務
![](https://i.imgur.com/rORzGoj.png)
***
![](https://i.imgur.com/LXILqin.png)
* Service Layer服務層

# 54 SpringMVC動態網站開發實務(交易Transactional)
![](https://i.imgur.com/FYxj6aL.png)
![](https://i.imgur.com/5j4PEkK.png)
![](https://i.imgur.com/2aYrdc9.png)

# 55 SpringMVC動態網站開發實務
![](https://i.imgur.com/g2jcKhP.png)
***
![](https://i.imgur.com/PabY3dy.png)

#### beans.config.xml
```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:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	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
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:annotation-config/>
    <context:component-scan base-package="tw.leonchen"/>
    <mvc:annotation-driven/>
    <!-- @EnableTransactionManager功能意義相同  -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
    
    <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 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>
	       <prop key="hibernate.current_session_context_class">thread</prop>
	     </props>
	  </property>
	</bean>
	
	<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
	   <property name="sessionFactory" ref="sessionFactory"/>
	</bean>

</beans>

```

# 56 SpringMVC動態網站開發實務
![](https://i.imgur.com/2nHBF7v.png)
***
![](https://i.imgur.com/5vx6cb7.png)

# 57 SpringMVC動態網站開發實務
![](https://i.imgur.com/X3guOVi.png)
![](https://i.imgur.com/ZcyO8Kd.png)
***
![](https://i.imgur.com/1DhVUd8.png)

# 58 SpringMVC動態網站開發實務
![](https://i.imgur.com/EQwSUBP.png)
***
![](https://i.imgur.com/2pjbd3g.png)

#### loginSystem.jsp
* 帳號密碼post 不會是get
![](https://i.imgur.com/yiB8gXR.png)
```clike=
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>LoginSystem</title>
</head>
<body>
<h3>LoginSystem</h3>
<form action="loginSystem.controller" method="post">
   <table>
     <tr>
       <td>UserName:</td>
       <td><input type="text" name="userName"/></td>
       <td>${errors.name}</td>
     </tr>
     <tr>
       <td>Password:</td>
       <td><input type="password" name="userPwd"/></td>
       <td>${errors.pwd}</td>
     </tr>
     <tr>
       <td><input type="submit" value="Login"></td>
       <td>${errors.msg}</td>
     </tr>
   </table>   
</form>
</body>
</html>
```
#### loginSuccess.jsp
![](https://i.imgur.com/WOvZCRb.png)
```clike=
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login Success</title>
</head>
<body>
Success. ${user}-${pwd}<br/>
</body>
</html>
```

# 59 SpringMVC動態網站開發實務
![](https://i.imgur.com/KvMokFE.png)
***
![](https://i.imgur.com/R9IL2gl.png)

# 60 SpringMVC動態網站開發實務
![](https://i.imgur.com/5JSmLfy.png)
***
![](https://i.imgur.com/c8y5C0M.png)
#### sql table Account
![](https://i.imgur.com/4RKVUld.png)
```clike=
use LeonPower;

create table Account(
	id int not null primary key identity(1,1),
	username nvarchar(50) not null,
	userpwd nvarchar(50) not null
);

Insert Into Account(username,userpwd)Values('mary','test123');
Insert Into Account(username,userpwd)Values('john','123test');

select * from Account;
```

#### Account
![](https://i.imgur.com/zM8MSKO.png)
```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;

@Entity
@Table(name = "Account")
public class Account {
	@Id @Column(name = "ID")
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private int id;
	
	@Column(name = "USERNAME")
	private String username;
	
	@Column(name = "USERPWD")
	private String userpwd;

	public Account() {
	}
	
	public Account(String username, String userpwd) {
		this.username = username;
		this.userpwd = userpwd;
	}
	
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}
	
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}
	
	public String getUserpwd() {
		return userpwd;
	}

	public void setUserpwd(String userpwd) {
		this.userpwd = userpwd;
	}
	
}


```
# 61 SpringMVC動態網站開發實務
![](https://i.imgur.com/E8lGSdW.png)
***
![](https://i.imgur.com/M5KsAgf.png)
![](https://i.imgur.com/rBnIg67.png)

#### AccountDao
![](https://i.imgur.com/3JLbRxP.png)
```clike=
package tw.leonchen.model;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository("accountDao")
@Transactional
public class AccountDao {
    @Autowired
	private SessionFactory sessionFactory;
	private Session session;
    
    public boolean checkLogin(Account account) {
    	session = sessionFactory.getCurrentSession();
    	
    	String hqlstr = "from Account Where username=:user and userpwd=:pwd";
    	Query<Account> query = session.createQuery(hqlstr, Account.class);
    	
    	query.setParameter("user", account.getUsername());
    	query.setParameter("pwd", account.getUserpwd());
    	
    	Account accountResult = query.uniqueResult(); 
    	
    	if(accountResult!=null) {
    		return true;
    	}  
    	
    	return false;
    }
}

```

#### AccountService
![](https://i.imgur.com/s9BEXrm.png)
```clike=
package tw.leonchen.model;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("accountService")
@Transactional
public class AccountService {
	@Autowired
	private AccountDao accountDao;
	
	public boolean checkLogin(Account account) {
		return accountDao.checkLogin(account);

	}
}

```

#### CheckLoginController
![](https://i.imgur.com/shVztMH.png)
```clike=
package tw.leonchen.controller;

import java.util.HashMap;
import java.util.Map;

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 org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import tw.leonchen.model.Account;
import tw.leonchen.model.AccountService;

@Controller
@SessionAttributes(names = {"user", "pwd", "msg"})
public class CheckLoginController {
	
	@Autowired
	private AccountService accountService;
	
	@RequestMapping(path = "/loginSystemMain.controller", method = RequestMethod.GET)
	public String processLoginMainAction() {
		return "loginSystem";
	}
	
	@RequestMapping(path = "/loginSystem.controller", method = RequestMethod.POST)
	public String processLoginAction(@RequestParam(name = "userName") String user, @RequestParam(name = "userPwd") String pwd, Model m) {
       
	   Map<String, String> errors = new HashMap<String, String>();
	   m.addAttribute("errors", errors);
	   
	   if(user==null || user.length()==0) {
		   errors.put("name", "name is required");
       }
	   
	   if(pwd==null || pwd.length()==0) {
		   errors.put("pwd", "pwd is required");
	   }
	   
	   if(errors!=null && !errors.isEmpty()) {
		   return "loginSystem";
	   }
	   
	   boolean checkUser = accountService.checkLogin(new Account(user, pwd));
	   
	   if(checkUser) {
		   m.addAttribute("user", user);
		   m.addAttribute("pwd", pwd);
		   return "loginSuccess";
	   }
	   
	   m.addAttribute("msg", "UserName or Password Is Not Correct");
	   return "loginSystem";
	}
}

```

#### web.xml
![](https://i.imgur.com/86UElUI.png)
```clike=
<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/beans.config.xml</param-value>
	</context-param>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
```

#### AccountDao
```clike=
package tw.leonchen.model;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository("accountDao")
@Transactional
public class AccountDao {
    @Autowired
	private SessionFactory sessionFactory;
	private Session session;
    
    public boolean checkLogin(Account account) {
    	session = sessionFactory.getCurrentSession();
    	
    	session.beginTransaction();
    	
    	String hqlstr = "from Account Where username=:user and userpwd=:pwd";
    	Query<Account> query = session.createQuery(hqlstr, Account.class);
    	
    	query.setParameter("user", account.getUsername());
    	query.setParameter("pwd", account.getUserpwd());
    	
    	Account accountResult = query.uniqueResult(); 
    	
    	session.getTransaction().commit();
    	
    	if(accountResult!=null) {
    		return true;
    	}  
    	
    	return false;
    }
}

```

#### CheckLoginController
```clike=
package tw.leonchen.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import tw.leonchen.model.Account;
import tw.leonchen.model.AccountService;

@Controller
@SessionAttributes(names = {"user", "pwd", "msg"})
@EnableTransactionManagement
public class CheckLoginController {
	
	@Autowired
	private AccountService accountService;
	
	@RequestMapping(path = "/loginSystemMain.controller", method = RequestMethod.GET)
	public String processLoginMainAction() {
		return "loginSystem";
	}
	
	@RequestMapping(path = "/loginSystem.controller", method = RequestMethod.POST)
	public String processLoginAction(@RequestParam(name = "userName") String user, @RequestParam(name = "userPwd") String pwd, Model m) {
       
	   Map<String, String> errors = new HashMap<String, String>();
	   m.addAttribute("errors", errors);
	   
	   if(user==null || user.length()==0) {
		   errors.put("name", "name is required");
       }
	   
	   if(pwd==null || pwd.length()==0) {
		   errors.put("pwd", "pwd is required");
	   }
	   
	   if(errors!=null && !errors.isEmpty()) {
		   return "loginSystem";
	   }
	   
	   boolean checkUser = accountService.checkLogin(new Account(user, pwd));
	   
	   if(checkUser) {
		   m.addAttribute("user", user);
		   m.addAttribute("pwd", pwd);
		   return "loginSuccess";
	   }
	   
	   errors.put("msg", "UserName or Password Is Not Correct");
	   return "loginSystem";
	}
}
```

#### beans.config.xml
[剛剛的問題 支那解答](https://blog.csdn.net/yinjian520/article/details/8666695)

```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:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	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
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:annotation-config/>
    <context:component-scan base-package="tw.leonchen"/>
    <mvc:annotation-driven/>
    <!-- @EnableTransactionManager功能意義相同 -->
    <tx:annotation-driven transaction-manager="transactionMamager"/>
    
    <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 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>
	      <!--   <prop key="hibernate.current_session_context_class">thread</prop>-->
	     </props>
	  </property>
	</bean>
	
	<bean id="transactionMamager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
	   <property name="sessionFactory" ref="sessionFactory"/>
	</bean>

</beans>

```

# 63 SpringMVC動態網站開發實務(視圖View)
![](https://i.imgur.com/t3OS9MQ.png)
* InternalResourceView : 内部资源视图
***
![](https://i.imgur.com/llW04WK.png)

# 64 SpringMVC動態網站開發實務
![](https://i.imgur.com/7OElBw9.png)
***
![](https://i.imgur.com/XkdD7Gl.png)

# 65 SpringMVC動態網站開發實務
![](https://i.imgur.com/knLQ9M4.png)
***
![](https://i.imgur.com/z7fD3h1.png)

# 66 SpringMVC動態網站開發實務
![](https://i.imgur.com/BFLLp9O.png)
![](https://i.imgur.com/i3Voabk.png)
![](https://i.imgur.com/xhphhTi.png)
***
![](https://i.imgur.com/AOKhNra.png)

# 67 SpringMVC動態網站開發實務
![](https://i.imgur.com/QP9NTz4.png)
***
![](https://i.imgur.com/zyUfCSn.png)

# 68 SpringMVC動態網站開發實務
![](https://i.imgur.com/qpNycMy.png)
***
![](https://i.imgur.com/Jj8tF9V.png)

# 69 SpringMVC動態網站開發實務
![](https://i.imgur.com/pHB3O0Y.png)
***
![](https://i.imgur.com/NXM3aLd.png)

# 70 SpringMVC動態網站開發實務
![](https://i.imgur.com/clummhD.png)

# 71 SpringMVC動態網站開發實務
![](https://i.imgur.com/5VtnHrD.png)

# 72 SpringMVC動態網站開發實務(表單綁定)
![](https://i.imgur.com/0v0Bm0N.png)
![](https://i.imgur.com/gegZWKC.png)
***
![](https://i.imgur.com/ZiiBZ1a.png)
* 藍字:方法名子
* 橘字:某個物件的名子

# 73 SpringMVC動態網站開發實務
![](https://i.imgur.com/udVfauD.png)
***
![](https://i.imgur.com/Pd1GZQF.png)

#### members.jsp
![](https://i.imgur.com/DCDeN5f.png)
```clike=
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Welcome Members</title>
</head>
<body>
<h3>Members</h3>
<form:form action="addMembers" modelAttribute="members">
	<tr>
		<td><form:label path="memberName">MemberName:</form:label></td>
		<td><form:input path="memberName"/></td>
	</tr>
	<tr>
		<td><form:label path="gender">Gender:</form:label></td>
		<td><form:input path="gender"/></td>
	</tr>
	<tr>
		<td><form:label path="age">Age:</form:label></td>
		<td><form:input path="age"/></td>
	</tr>
	<tr>
		<td><form:button path="Send">Submit:</form:button></td>
	</tr>
</form:form>
</body>
</html>
```

#### Members.jsp
![](https://i.imgur.com/hyHvajZ.png)
```clike=
package tw.leonchen.model;

public class Members {
	private String memberName;
	private String gender;
	private int age;

	public Members(String memberName, String gender, int age) {
        this.memberName = memberName;
        this.gender = gender;
        this.age = age;
	}

	public String getMemberName() {
		return memberName;
	}

	public void setMemberName(String memberName) {
		this.memberName = memberName;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}	
}

```

# 74 SpringMVC動態網站開發實務
![](https://i.imgur.com/peoyxIc.png)

#### MembersController
![](https://i.imgur.com/MUqcOgY.png)
```clike=
package tw.leonchen.controller;

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

import tw.leonchen.model.Members;

@Controller
public class MembersController {
	@RequestMapping(path = "/showFrom.controller", method = RequestMethod.GET)
	public String showForm(Model m) {
		Members members = new Members();
		m.addAttribute("members",members);
		return "members";
	}
}

```

#### Members 
```clike=
package tw.leonchen.model;

public class Members {
	private String memberName;
	private String gender;
	private int age;
		
	public Members() {
		
	}
	
	
	public Members(String memberName,String gender, int age) {
		this.memberName = memberName;
		this.gender = gender;
		this.age = age;
	}


	public String getMemberName() {
		return memberName;
	}


	public void setMemberName(String memberName) {
		this.memberName = memberName;
	}


	public String getGender() {
		return gender;
	}


	public void setGender(String gender) {
		this.gender = gender;
	}


	public int getAge() {
		return age;
	}


	public void setAge(int age) {
		this.age = age;
	}

}

```

#### members.jsp
```clike=
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Welcome Members</title>
</head>
<body>
<h3>Members</h3>
<form:form action="addMembers" modelAttribute="members" method="POST">
	<table>
	<tr>
		<td><form:label path="memberName">MemberName:</form:label></td>
		<td><form:input path="memberName"/></td>
	</tr>
	<tr>
		<td><form:label path="gender">Gender:</form:label></td>
		<td><form:input path="gender"/></td>
	</tr>
	<tr>
		<td><form:label path="age">Age:</form:label></td>
		<td><form:input path="age"/></td>
	</tr>
	<tr>
		<td colspan="2"><form:button path="Send">Submit:</form:button></td>
	</tr>
	</table>
</form:form>
</body>
</html>
```
![](https://i.imgur.com/4bO3I8E.png)

## members聯繫
![](https://i.imgur.com/gc2Uztu.png)
![](https://i.imgur.com/pyntZmI.png)
![](https://i.imgur.com/1BH8j1R.png)
![](https://i.imgur.com/HRabdw2.png)
![](https://i.imgur.com/0ANqT9A.png)

# 76 SpringMVC動態網站開發實務
![](https://i.imgur.com/EjLNCfP.png)

#### MembersController
```clike=
package tw.leonchen.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import tw.leonchen.model.Members;

@Controller
public class MembersController {
	@RequestMapping(path = "/showFrom.controller", method = RequestMethod.GET)
    public String showForm(Model m) {
    	Members members = new Members();
    	m.addAttribute("members", members);
    	return "members";
    }
	
	@RequestMapping(path = "addMembers", method = RequestMethod.POST)
	public String processMembersAction(@ModelAttribute(name = "members") Members members, BindingResult result, Model model) {
		
		if(result.hasErrors()) {
			return "membersError";
		}
		
		model.addAttribute("mName", members.getMemberName());
		model.addAttribute("mGender", members.getGender());
		model.addAttribute("mAge", members.getAge());
		
		return "membersResult";
	}
}

```

#### membersResult.jsp
```clike=
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Members Result</title>
</head>
<body>
MemberName:${mName}<br/>
Gender:${mGender}<br/>
Age:${mAge}<br/>
</body>
</html>
```

#### membersError.jsp
```clike=
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Members Error</title>
</head>
<body>
Please Input Correct Information.<br/>
<a href="showFrom.controller">Retry</a>
</body>
</html>
```
# 77 SpringMVC動態網站開發實務
![](https://i.imgur.com/5tp0M82.png)
