# SpringMVC 3/3上課內容
###### tags: `SpringMVC`
[老師云端](https://1drv.ms/u/s!Ans47I9-PkivwH8KqgNszZ8OKcZe)
# 39 SpringMVC動態網站開發實務

### 框架

#### DemoDispatcherServletInitializer


```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動態網站開發實務(框架如何產生回應)


* id=邏輯名稱 name=網址
# 41 SpringMVC動態網站開發實務

* **View**
* 原來的資料表有隱密性
* 對開發者比較安全
***

# 42 SpringMVC動態網站開發實務

#### 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

* 原本

* 放入pages


### profiles.jsp

* 移入 須從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動態網站開發實務

***

#### 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();
}
}
```
### 執行畫面網址

黃色地方改成網址

執行成功

# 44 SpringMVC動態網站開發實務

#### 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動態網站開發實務(存取資料庫與應用程式的架構)

# 46 SpringMVC動態網站開發實務


***

# 47 SpringMVC動態網站開發實務

***

#### 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 />
<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動態網站開發實務

***

# 49 SpringMVC動態網站開發實務

* 嚴格檢查javaBean跟資料表還有tabel的大小寫有沒有一樣(太嚴格)
***

* xml 映射關係
# 50 SpringMVC動態網站開發實務

***

#### 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動態網站開發實務

***

# 52 SpringMVC動態網站開發實務

# 53 SpringMVC動態網站開發實務

***

* Service Layer服務層
# 54 SpringMVC動態網站開發實務(交易Transactional)



# 55 SpringMVC動態網站開發實務

***

#### 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動態網站開發實務

***

# 57 SpringMVC動態網站開發實務


***

# 58 SpringMVC動態網站開發實務

***

#### loginSystem.jsp
* 帳號密碼post 不會是get

```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

```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動態網站開發實務

***

# 60 SpringMVC動態網站開發實務

***

#### sql table Account

```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

```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動態網站開發實務

***


#### 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();
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

```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

```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

```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)

* InternalResourceView : 内部资源视图
***

# 64 SpringMVC動態網站開發實務

***

# 65 SpringMVC動態網站開發實務

***

# 66 SpringMVC動態網站開發實務



***

# 67 SpringMVC動態網站開發實務

***

# 68 SpringMVC動態網站開發實務

***

# 69 SpringMVC動態網站開發實務

***

# 70 SpringMVC動態網站開發實務

# 71 SpringMVC動態網站開發實務

# 72 SpringMVC動態網站開發實務(表單綁定)


***

* 藍字:方法名子
* 橘字:某個物件的名子
# 73 SpringMVC動態網站開發實務

***

#### 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">
<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

```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動態網站開發實務

#### MembersController

```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>
```

## members聯繫





# 76 SpringMVC動態網站開發實務

#### 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動態網站開發實務
