<java EE 项目:petstore> 从一个简单项目看 java web 如何在本jsp页面上对用户输入的格式进行限制与验证

项目说明:
在我们写一些类似于登入注册页面,需要用户输入信息时,往往要对用户的输入信息的格式进行验证与限制。一般我们会将表单提交后在另一个Servlet或jsp页面上进行验证,但是一出错页面就会重新刷新,使得之前输入的信息丢失,这样用户体验就会很差。
现在的一些流行的网页,都是在输入未提交之前就会提醒用户,使用户能及时的进行修改。

接下来,我们就通过一个小的练习,来看看 如何实现在本jsp页面上对用户输入信息的格式进行限制与验证。
比如:提醒用户名不能为空,电话格式不对,时间格式不对,或者是通过局部刷新来验证是否用户名重复等等效果。

相关的技术:JQuery ,正则表达式, AJAX (本实验还没有涉及到,这是关于局部刷新的技术)

注意:本博客重点在于后面的add.jsp的实现

项目需求:
这里写图片描述
这里写图片描述

项目实现:

(1)数据库设计:
这里写图片描述
这里写图片描述

(2)效果图:
按种类查找:
这里写图片描述
昵称不能为空:
这里写图片描述
日期不能为空:
这里写图片描述
日期格式验证:
这里写图片描述
正确输入全部信息:
这里写图片描述
插入成功:
这里写图片描述

数据库更新
这里写图片描述

源代码:

(1)项目整体结构:三层结构 数据层,业务层,表示层
这里写图片描述

本文重点
表示层:
这里写图片描述
这里写图片描述

showPet.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>

  </head>

  <body>
    <div id = "pet">
        <form id="pets" action="showPetAction.jsp" method="post">
                <table colspan = "2" align="center" >
                <tr>
                    <td><strong>品种 </strong></td>
                    <td>
                        <select style = "width:150px;" name = "breed" id = "breed">
                            <option value = ""> --请选择--</option>
                            <option value = "狗"></option>
                            <option value = "猫"></option>
                            <option value = "鸟"></option>
                            <option value = "蛇"></option>

                    </td>
                    <td>
                        <input id="btnSubmit" type="submit" name="btnSubmit" value="查询" />
                        <a href="addPet.jsp">新增宠物</a>
                    </td>
                </tr>
                </table>    
        </form>

            <table border = "1" align="center">
                <tr>
                    <td style = "width:150px;"><strong>宠物名称 </strong></td>
                    <td style = "width:150px;"><strong>出生日期</strong></td>
                    <td style = "width:150px;"><strong>性别</strong></td>
                </tr>
                <c:forEach var="pet" items="${pets}">
                    <tr>
                        <td style = "width:150px;"><strong>${pet.pet_Name}</strong></td>
                        <td style = "width:150px;"><strong>${pet.getBirthday()}</strong></td>
                        <td style = "width:150px;"><strong>${pet.pet_Sex}</strong></td>
                    </tr>
                </c:forEach>
            </table>

    </div>
  </body>
</html>

showPetAction.jsp:

<%@page import="com.petstore.biz.impl.PetBizImpl"%>
<%@page import="com.petstore.biz.PetBiz"%>
<%@page import="com.petstore.entity.Pet"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>


<%
    request.setCharacterEncoding("utf-8");
    String breed = request.getParameter("breed");
    List<Pet> pets = new ArrayList<Pet>();
    PetBiz petBiz = new PetBizImpl();
    pets = petBiz.getPetsByBreed(breed);
    if(pets.size() > 0)
    {
        request.setAttribute("pets", pets);
        request.getRequestDispatcher("showPet.jsp").forward(request, response);

    }
    else 
    {
        request.getRequestDispatcher("showPet.jsp").forward(request, response);
    }
 %>

addPet.jsp:
请注意head中的script中的JQuery函数的申明与注册:
要想运行JQuery的函数,需要添加一下内容:
这里写图片描述

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
    <link type="text/css" rel="Stylesheet" href="style/front.css"/>
    <script type="text/javascript" src="script/jquery-1.4.1.js"></script>
    <script type="text/javascript">

        function checkPetName()
        {
            var pet_name = $("#pet_name").val();
            if(pet_name == "")
            {
                $("#pet_name").next(".error").text("昵称不能为空!");
                alert("昵称不能为空!");
                return false;
            }
            else 
            {
                $("#pet_name").next(".error").text("");
                return true;
            }

        }
        function checkBirthday()
        {
            var birthday = $("#birthday").val();
            if(birthday == "")
            {
                $("#birthday").next(".error").text("birthday不能为空");
                return false;
            }
            else 
            {
                $("#birthday").next(".error").text("");
                var reg = /^[1-9][0-9][0-9][0-9]-[0-1][0-9]-[0-3][0-9]$/;
                if(reg.test(birthday)) //验证格式是否匹配
                {
                    $("birthday").next(".error").text("");
                    return true;
                }
                else 
                {
                    alert("birthday格式不正确");
                    return false;
                }
            }
        }
        $(function(){
            $("#pet_name").blur(checkPetName);
            $("#birthday").blur(checkBirthday);
        });

    </script>

    </head>
  <body >
    <form id="" action="AddServlet" method="post" >
        <table border = "1" align="center" style = "width:420px;">
            <tr>
                <td align="center" colspan = "2"><strong>宠物的基本信息</strong></td>
            </tr>
            <tr>
                <td><strong>昵称:</strong></td>
                <td><input class="txt" type="text" id="pet_name" name="pet_name" style = "width:180px;"/> <label class="error"></label></td>
            </tr>
            <tr>
                <td><strong>品种:</strong></td>
                <td>
                        <select style = "width:180px;" name = "pet_breed" id = "pet_breed">
                            <option value = ""> --请选择--</option>
                            <option value = "狗"></option>
                            <option value = "猫"></option>
                            <option value = "鸟"></option>
                            <option value = "蛇"></option>

                </td>
            </tr>
            <tr>
                <td><strong>性别:</strong></td>
                <td><input  type="radio" name="pet_sex" value="雄" />雄 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input  type="radio" name="pet_sex" value="雌" /></td>

            </tr>
            <tr>
                <td>出生日期:</td>
                <td><input class="txt" type="text" id="birthday" name="birthday" style = "width:180px;"/> 日期格式:yyyy-mm-dd  <label class="error"></label></td>
            </tr>
            <tr>
                <td>宠物描述:</td>
                <td><textarea  id="description" name="description" style = "width:350px;"> </textarea> <label class="error"></label></td>
            </tr>
            <tr>
                <td></td>
                <td >
                    <input id="btnSubmit" type="submit" name="btnSubmit" value="提交" /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <input type="reset" name="reset" id="reset" value="重置" />
                </td>
            </tr>
            <tr>
                    <td colspan="2" align="center" ><label class="error">${error}</label>
                    </td>
            </tr>
        </table>

    </form>
  </body>

</html>

AddServlet:

package com.petstore.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.SimpleAttributeSet;

import com.petstore.biz.PetBiz;
import com.petstore.biz.impl.PetBizImpl;
import com.petstore.entity.Pet;

public class AddServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset = utf-8");
        request.setCharacterEncoding("utf-8");
        String pet_name = request.getParameter("pet_name");
        String pet_breed = request.getParameter("pet_breed");
        String pet_sex = request.getParameter("pet_sex");
        String description = request.getParameter("description");
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = sdf.parse(request.getParameter("birthday"));
            Pet pet = new Pet(pet_name,pet_breed,pet_sex,date,description);
            PetBiz petBiz = new PetBizImpl();
            int count = petBiz.addPet(pet);
            if(count > 0)
            {
                request.setAttribute("error", "插入新的宠物!");
                request.getRequestDispatcher("addPet.jsp").forward(request, response);
            }
            else {
                request.setAttribute("error", "插入失败!");
                request.getRequestDispatcher("addPet.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doGet(request, response);

    }

}

业务层:

接口:PetBiz.java:

package com.petstore.biz;

import java.util.List;

import com.petstore.entity.Pet;

public interface PetBiz {
    List<Pet> getPetsByBreed(String breed);
    int addPet(Pet pet);
}

实现:PetBizImpl.java:

package com.petstore.biz.impl;

import java.util.List;

import com.petstore.biz.PetBiz;
import com.petstore.dao.PetDao;
import com.petstore.dao.impl.PetDaoImpl;
import com.petstore.entity.Pet;

public class PetBizImpl implements PetBiz{
    PetDao petDao = new PetDaoImpl();

    public List<Pet> getPetsByBreed(String breed) {

        return petDao.getPetsByBreed(breed);
    }

    public int addPet(Pet pet) {

        return petDao.addPet(pet);
    }

}

数据层:

实体 Pet.java:

package com.petstore.entity;

import java.util.Date;

public class Pet {
    private int pet_Id;
    private String pet_Name;
    private String pet_Breed;
    private String pet_Sex;
    private Date Birthday;
    private String description;

    public Pet(){}

    public Pet(String pet_Name, String pet_Breed, String pet_Sex,
            Date birthday, String description) {
        super();
        this.pet_Name = pet_Name;
        this.pet_Breed = pet_Breed;
        this.pet_Sex = pet_Sex;
        Birthday = birthday;
        this.description = description;
    }

    public int getPet_Id() {
        return pet_Id;
    }
    public void setPet_Id(int pet_Id) {
        this.pet_Id = pet_Id;
    }
    public String getPet_Name() {
        return pet_Name;
    }
    public void setPet_Name(String pet_Name) {
        this.pet_Name = pet_Name;
    }
    public String getPet_Breed() {
        return pet_Breed;
    }
    public void setPet_Breed(String pet_Breed) {
        this.pet_Breed = pet_Breed;
    }
    public String getPet_Sex() {
        return pet_Sex;
    }
    public void setPet_Sex(String pet_Sex) {
        this.pet_Sex = pet_Sex;
    }
    public Date getBirthday() {
        return Birthday;
    }
    public void setBirthday(Date birthday) {
        Birthday = birthday;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }


}

接口 PetDao.java:

package com.petstore.dao;

import java.util.List;

import com.petstore.entity.Pet;

public interface PetDao {
    List<Pet> getPetsByBreed(String breed);
    int addPet(Pet pet);
}

实现 PetDaoImpl.java:

package com.petstore.dao.impl;


import java.sql.ResultSet;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.petstore.dao.PetDao;
import com.petstore.entity.Pet;

public class PetDaoImpl extends BaseDao implements PetDao{

    public List<Pet> getPetsByBreed(String breed) {
        List<Pet> pets = new ArrayList<Pet>();
        String sql = "select * from pet where Pet_Breed = ?";
        try {
            openConnection();
            ResultSet rs = executeQuery(sql, new Object[]{breed});
            while(rs.next())
            {
                Pet pet = new Pet();
                pet.setPet_Id(rs.getInt("Pet_ID"));
                pet.setPet_Name(rs.getString("Pet_Name"));
                pet.setPet_Sex(rs.getString("Pet_Sex"));
                pet.setPet_Breed(rs.getString("Pet_Breed"));
                pet.setBirthday(rs.getDate("Birthday"));
                pet.setDescription(rs.getString("Description"));
                pets.add(pet);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        finally
        {
            closeResource();
        }
        return pets;
    }

    public static void main(String[] args) {
        PetDao petDao = new PetDaoImpl();
        /*
        Pet pet = new Pet();
        pet.setPet_Name("花花");
        pet.setPet_Breed("狗");
        pet.setPet_Sex("雌");
        DateFormat sdf = new SimpleDateFormat("yyy-MM-dd");
        try {
            Date birthday = sdf.parse("2016-02-02");
            pet.setBirthday(birthday);
            int count = petDao.addPet(pet);
            System.out.println(count);
        } catch (Exception e) {
            e.printStackTrace();
        }
        */

        List<Pet> pets = petDao.getPetsByBreed("狗");
        System.out.println(pets.size());
        for(Pet pet : pets)
        {
            System.out.println(pet.getBirthday());
        }
    }

    public int addPet(Pet pet) {
        int count = 0;
        try {
            String sql = "insert into pet (pet_name,pet_sex,pet_breed,birthday,description) values(?,?,?,?,?)";
            Object[] params = new Object[]{
                pet.getPet_Name(),
                pet.getPet_Sex(),
                pet.getPet_Breed(),
                pet.getBirthday(),
                pet.getDescription()
            };
            openConnection();
            count = executeUpdate(sql, params);
            sql = "select last_insert_id()";
            ResultSet rs = executeQuery(sql, null);
            if(rs.next())
            {
                pet.setPet_Id(rs.getInt(1));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        finally
        {
            closeResource();
        }
        return count;
    }



}

实现 BaseDao.java:数据库函数的封装

package com.petstore.dao.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BaseDao {
    String className = "com.mysql.jdbc.Driver";
    String dbUrl = "jdbc:mysql://localhost:3306/musicdb";
    Connection connection;  //连接
    PreparedStatement statement; //命令
    ResultSet resultSet; //结果集

    //打开连接
    public void openConnection() throws ClassNotFoundException, SQLException 
    {
        //加载驱动类
        Class.forName(className);
        connection = DriverManager.getConnection(dbUrl,"root","root");
    }

    //增
    public int executeUpdate(String sql, Object[] params) throws SQLException
    {
        statement = connection.prepareStatement(sql);
        if(params != null) //追加参数
        {
            int i = 1;
            for(Object object : params){
                statement.setObject(i, object);
                i++;
            }
        }

        //执行sql
        int count = statement.executeUpdate();
        return count;
    }

    //查询
    public ResultSet executeQuery(String sql,Object[] params) throws SQLException
    {
        statement = connection.prepareStatement(sql);
        if(params != null) //追加参数
        {
            int i = 1;
            for(Object object : params){
                statement.setObject(i, object);
                i++;
            }
        }

        resultSet  = statement.executeQuery();
        return resultSet;
    }

    //释放资源
    public void closeResource()
    {
        try {
            if(resultSet != null)
            {
                resultSet.close();
            }
            if(statement != null)
            {
                statement.close();
            }
            if(connection != null)
            {
                connection.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值