用Struts2来完成一个学生注册界面

框架模型采用:MVC的思想;domain-dao-service
数据库采用:Mysql;
连接池采用:DBCP,会简历一个DBCPUtil的工具类来完成;
动作类Action:继承ActionSupport,实现 ModelDriven<>,即采用动作与模型分开的方式;
写regist.jsp注册页面是可以用struts2的标签库来写表单的页面;
在页面书写时关于checkbox类型的写法,爱好类型的书写,页面-javabean类-action类;

用Struts2来完成一个学生注册界面_第1张图片

用Struts2来完成一个学生注册界面_第2张图片

//struts.xml



<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.jspresult>
            <result name="error" type="dispatcher">/error.jspresult>
        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;iif(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>
  
  <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标签写在输入错误是还可以有回显与提示
用Struts2来完成一个学生注册界面_第3张图片

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>

<html>
  <head>
    <title>titletitle>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    
    <s:head/>
  head>

  <body>
    
    <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>
        
        <s:radio name="gender" list="#{'male':'男性','female':'女性'}" label="性别" requiredLabel="true" requiredPosition="left">s:radio>
        
        <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>

你可能感兴趣的:(用Struts2来完成一个学生注册界面)