用Struts2來完成一個學生註冊介面
框架模型採用:MVC的思想;domain-dao-service
資料庫採用:Mysql;
連線池採用:DBCP,會簡歷一個DBCPUtil的工具類來完成;
動作類Action:繼承ActionSupport,實現 ModelDriven<>,即採用動作與模型分開的方式;
寫regist.jsp註冊頁面是可以用struts2的標籤庫來寫表單的頁面;
在頁面書寫時關於checkbox型別的寫法,愛好型別的書寫,頁面-javabean類-action類;
//struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.devMode" value="true"></constant>
<package name="student" extends="struts-default" namespace="/student" >
<action name="regist" class="com.lzy.action.RegistAction" method="regist">
<result name="success" type="dispatcher">/success.jsp</result>
<result name="error" type="dispatcher">/error.jsp</result>
</action>
</package>
</struts>
//dbcpconfig.properties
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/day28
username=lzy
password=
initialSize=10
maxActive=50
maxIdle=20
minIdle=5
maxWait=60000
connectionProperties=useUnicode=true;characterEncoding=utf8
defaultAutoCommit=true
defaultReadOnly=
defaultTransactionIsolation=REPEATABLE_READ
//DBCPUtil.java 配置一個DBCP的工具類 裡面設計到資料來源的方式
package com.lzy.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
public class DBCPUtil {
private static DataSource dataSource;
static{
//讀取配置檔案
ClassLoader cl = DBCPUtil.class.getClassLoader();
InputStream in = cl.getResourceAsStream("dbcpconfig.properties");
Properties props = new Properties();
try {
props.load(in);
//System.out.println(props.getClass());
//System.out.println(props.getProperty("url"));
//System.out.println(props.getProperty("username"));
dataSource = BasicDataSourceFactory.createDataSource(props);
} catch (Exception e) {
e.printStackTrace();
}
}
public static DataSource getDataSource(){
return dataSource;
}
public static Connection getConnection(){
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException("獲取連線失敗");
}
}
}
//Student.java
package com.lzy.domain;
/*
資料庫用mysql,上面要定義一個連線池。
建立資料庫
create database day28;
use day28;
create table students(
id int primary key auto_increment,
studentname varchar(100) not null unique,
password varchar(10) not null,
gender varchar(10) not null,
hobby varchar(100),
birthday date,
email varchar(100),
grade int
);
*/
import java.io.Serializable;
public class Student implements Serializable {
private int id;
private String studentname;
private String password;
private String gender;
private String hobby;//吃飯 睡覺 學java
private String birthday;
private String email;
private String grade;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStudentname() {
return studentname;
}
public void setStudentname(String studentname) {
this.studentname = studentname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
}
//StudentDaoImpl dao的實現,主要涉及向資料庫插入資料和查詢資料 用到了DBUtile工具類裡面的QueryRunner
package com.lzy.dao.impl;
import java.sql.SQLException;
import java.util.Arrays;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import com.lzy.dao.StudentDao;
import com.lzy.domain.Student;
import com.lzy.util.DBCPUtil;
public class StudentDaoImpl implements StudentDao {
QueryRunner queryRunner = new QueryRunner(DBCPUtil.getDataSource());
public void save(Student s) {
try {
queryRunner.update(DBCPUtil.getConnection(),"insert into students " +
"(studentname,password,gender,hobby,birthday,email,grade) " +
"values (?,?,?,?,?,?,?)", s.getStudentname(),s.getPassword(),s.getGender(),s.getHobby(),s.getBirthday(),s.getEmail(),s.getGrade());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void find(Student s) {
//ArrayHandler把結果集中的第一行資料轉換成物件陣列
String sql = "select *from students";
try {
Object result[] = queryRunner.query(DBCPUtil.getConnection(), sql,
new ArrayHandler());
System.out.println(Arrays.asList(result));
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//BusinnessServiceImpl .java 服務實現類
package com.lzy.service.impl;
import com.lzy.dao.StudentDao;
import com.lzy.dao.impl.StudentDaoImpl;
import com.lzy.domain.Student;
import com.lzy.service.BusinnessService;
public class BusinnessServiceImpl implements BusinnessService {
private StudentDao studentDao = new StudentDaoImpl();
public void registStudent(Student s) {
studentDao.save(s);
}
public void findStudent(Student s){
studentDao.find(s);
}
}
//RegistAction .java 定義Action類,繼承了ModeDriven 實現動作與模型分開
在這裡面要注意:hobbies,它與Student裡面的hobby不一樣,需要特殊處理。
package com.lzy.action;
import com.lzy.domain.Student;
import com.lzy.service.BusinnessService;
import com.lzy.service.impl.BusinnessServiceImpl;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class RegistAction extends ActionSupport implements ModelDriven<Student> {
private String[] hobbies; //表單與模型不匹配 可以在action裡面進行設計
Student student = new Student();
BusinnessService bs = new BusinnessServiceImpl();
public String[] getHobbies() {
return hobbies;
}
public void setHobbies(String[] hobbies) {
this.hobbies = hobbies;
}
public String regist(){
try {
//對愛好進行單獨處理,主要是在jsp設計時與Student類沒有對應
//最後通過setHobby函式可以將hobbies的值與hobby值對應起來
if(hobbies!=null && hobbies.length>0){
StringBuffer sb = new StringBuffer();
for(int i=0;i<hobbies.length;i++){
if(i>0){
sb.append(",");
}
sb.append(hobbies[i]);
}
student.setHobby(sb.toString());
}
bs.registStudent(student);
return SUCCESS;
} catch (Exception e) {
e.printStackTrace();
return ERROR;
}
}
public Student getModel() {
return student;
}
}
//regist.jsp 頁面 在這裡面要注意:hobbies,它與Student裡面的hobby不一樣,需要特殊處理。hobbies的處理
</head>
<!-- 愛好這一欄的設計與其他不一樣,這裡的name屬性與Studeng類裡面的屬性不對應,主要是這裡的愛好說多選
的,所以需要在Action類裡面重新宣告一個hobbies這樣一個屬性,並且設定它的getter和setter方法
-->
<body>
<h1>學生資訊註冊介面</h1>
<form action="${pageContext.request.contextPath}/student/regist.action" method="post">
<table border="1" width="400">
<tr>
<td>學生姓名:</td>
<td>
<input type="text" name="studentname"/>
</td>
</tr>
<tr>
<td>密碼:</td>
<td>
<input type="password" name="password"/>
</td>
</tr>
<tr>
<td>性別:</td>
<td>
<input type="radio" name="gender" value="male" checked="checked"/>男
<input type="radio" name="gender" value="female"/>女
</td>
</tr>
<tr>
<td>愛好:</td>
<td>
<input type="checkbox" name="hobbies" value="吃飯"/>吃飯
<input type="checkbox" name="hobbies" value="睡覺"/>睡覺
<input type="checkbox" name="hobbies" value="學Java"/>學Java
</td>
</tr>
<tr>
<td>生日(yyyy-MM-dd):</td>
<td>
<input type="text" name="birthday"/>
</td>
</tr>
<tr>
<td>郵件:</td>
<td>
<input type="text" name="email"/>
</td>
</tr>
<tr>
<td>成績:</td>
<td>
<input type="text" name="grade"/>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="註冊"/>
</td>
</tr>
</table>
</form>
</body>
//regist.jsp 頁面 可以用struts2的標籤庫來寫表單,這樣更加簡單,而且程式碼量小。
首先要引入一個編譯指令:tablib。<%@ taglib uri=”/struts-tags” prefix=”s”%>
用struts標籤寫在輸入錯誤是還可以有回顯與提示。
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>title</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<s:head/><!-- 引入了一些css和js -->
</head>
<body>
<!-- 推薦使用Struts2的標籤庫 -->
<s:form action="regist" namespace="/student">
<s:textfield name="username" label="使用者名稱" requiredLabel="true" requiredPosition="left"></s:textfield>
<s:password name="password" label="密碼" requiredLabel="true" requiredPosition="left"></s:password>
<!-- list的取值是一個ONGL表示式,建立了一個Map物件。必須有name -->
<s:radio name="gender" list="#{'male':'男性','female':'女性'}" label="性別" requiredLabel="true" requiredPosition="left"></s:radio>
<!-- list的取值是一個ONGL表示式,建立了一個List物件。必須有name -->
<s:checkboxlist name="hobbies" list="{'吃飯','睡覺','學java'}" label="愛好"></s:checkboxlist>
<s:textfield name="birthday" label="出生日期:yyyy-MM-dd"></s:textfield>
<s:textfield name="email" label="郵箱"></s:textfield>
<s:textfield name="grade" label="成績"></s:textfield>
<s:submit value="註冊"></s:submit>
</s:form>
<br/>
<form action="${pageContext.request.contextPath}/student/regist" method="post">
<table border="1" width="438">
<tr>
<td>使用者名稱:</td>
<td>
<input type="text" name="username"/>
</td>
</tr>
<tr>
<td>密碼:</td>
<td>
<input type="password" name="password"/>
</td>
</tr>
<tr>
<td>性別:</td>
<td>
<input type="radio" name="gender" value="male" checked="checked"/>男性
<input type="radio" name="gender" value="female"/>女性
</td>
</tr>
<tr>
<td>愛好:</td>
<td>
<input type="checkbox" name="hobbies" value="吃飯"/>吃飯
<input type="checkbox" name="hobbies" value="睡覺"/>睡覺
<input type="checkbox" name="hobbies" value="學java"/>學java
</td>
</tr>
<tr>
<td>出生日期:(yyyy-MM-dd)</td>
<td>
<input type="text" name="birthday"/>
</td>
</tr>
<tr>
<td>郵箱:</td>
<td>
<input type="text" name="email"/>
</td>
</tr>
<tr>
<td>成績:</td>
<td>
<input type="text" name="grade"/>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="註冊"/>
</td>
</tr>
</table>
</form>
</body>
</html>