Java学习1.26————web案例

jsp中提供了el表达式,可以获取服务端域对象中的数据
el表达式语法
${后端域对象中的key}

JSTL
JSP标准标签库,也称为c标签

jsp页面中导入jstl标签库

<%@ taglib prefix=“c” uri=“http://java.sun.com/jsp/jstl/core”%>

用jstl标签对集合内容遍历并排版

jsp语法

<table></table>表格

<tr></tr>  表格中的行

<td></td>    tr的子标签,表示一行中的一个单元

<c:forEach> </c:forEach>   jstl提供的遍历标签

items  要遍历的对象。要遍历对象从域对象中获取,所以要通过el表达式从域对象中获取

var 遍历的每个元素,用来存放当前指向的元素

border 边框,表格的属性

align="center" 表格居中

<th></th> 会对内容进行加粗

<h1 align="center"> 学生管理页面</h1>标题标签
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--导入jstl标签库--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
    <title>学生列表</title>
</head>
<body>

<%--jsp中提供了el表达式,可以获取服务端域对象中的数据--%>
<%--
    el表达式语法
    ${后端域对象中的key}
--%>

<%--在当前jsp页面中导入jstl标签(也称之为c标签)

--%>

<%--${stuList}--%>
<%--items  要遍历的对象。要遍历对象从域对象中获取,所以要通过el表达式从域对象中获取
var 遍历的每个元素
border 边框,表格的属性
align="center" 表格居中
<th></th> 会对内容进行加粗
<h1 align="center"> 学生管理页面</h1>标题标签
--%>
<h1 align="center"> 学生管理页面</h1>
<table border="1px" align="center">

    <tr>
    <th>学生姓名</th>
    <th>学生年龄</th>
    <th>学生性别</th>
    <th>学生地址</th>
    <th>学生生日</th>
    <th>学生爱好</th>

    </tr>
    <c:forEach items="${stuList}" var="stu">
        <tr>
            <td>${stu.sname}</td>
            <td>${stu.age}</td>
            <td>${stu.sex}</td>
            <td>${stu.address}</td>
            <td>${stu.birthday}</td>
            <td>${stu.hobby}</td>

        </tr>

    </c:forEach>
</table>
</body>
</html>


运行结果如图
在这里插入图片描述
web具体代码如下:
Student.java

package com.jy.pojo;

public class Student {

    private Integer sid;

    private String sname;

    private Integer age;

    private Integer sex;

    private String address;

    private String birthday;

    private String hobby;

    public Student(Integer sid, String sname, Integer age, Integer sex, String address, String birthday, String hobby) {
        this.sid = sid;
        this.sname = sname;
        this.age = age;
        this.sex = sex;
        this.address = address;
        this.birthday = birthday;
        this.hobby = hobby;
    }

    public Student() {
    }

    public Integer getSid() {
        return sid;
    }

    public String getSname() {
        return sname;
    }

    public Integer getAge() {
        return age;
    }

    public Integer getSex() {
        return sex;
    }

    public String getAddress() {
        return address;
    }

    public String getBirthday() {
        return birthday;
    }

    public String getHobby() {
        return hobby;
    }

    public void setSid(Integer sid) {
        this.sid = sid;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

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

    public void setSex(Integer sex) {
        this.sex = sex;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    public void setHobby(String hobby) {
        this.hobby = hobby;
    }

    @Override
    public String toString() {
        return "Student{" +
                "sid=" + sid +
                ", sname='" + sname + '\'' +
                ", age=" + age +
                ", sex=" + sex +
                ", address='" + address + '\'' +
                ", birthday='" + birthday + '\'' +
                ", hpbby='" + hobby + '\'' +
                '}';
    }
}

StudentServlet.java

package com.jy.servlet;

import com.jy.pojo.Student;
import com.jy.util.JDBCUtils;
import org.apache.taglibs.standard.tag.common.core.ChooseTag;
import org.omg.CosNaming.NamingContextExtPackage.StringNameHelper;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;

public class StudentServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //处理中文乱码
        request.setCharacterEncoding("utf-8");
        //接收前端传递的标识,决定具体执行的方法
        String flag = request.getParameter("flag");

        if(flag != null && flag.equals("list")){

            getList(request,response);
        }else if(flag != null &&flag.equals("add")){
            getAdd(request,response);
        }else if(flag != null && flag.equals("delete")){
            getDelete(request,response);

    }
    }
/*
* 根据id进行删除
* */
    private void getDelete(HttpServletRequest request, HttpServletResponse response) {


        //接收id值
        String id = request.getParameter("id");

        Connection connection =null;
        PreparedStatement preparedStatement = null;

        //jdbc执行访问数据库执行删除
        try {

            connection = JDBCUtils.getConnection();

            preparedStatement = connection.prepareStatement("delete  feom tb_student  where id= ?");

            preparedStatement.setInt(1,Integer.parseInt(id));

            int i = preparedStatement.executeUpdate();

            if(i>0){
                System.out.println("删除成功");

                response.sendRedirect("http://localhost:8080/managerWeb/stu?flag=list");
            }else{
                System.out.println("删除失败");
            }

        }catch(Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtils.JDBCClose(connection,preparedStatement,null);
        }


    }


    //执行添加的方法
    public void getAdd(HttpServletRequest request, HttpServletResponse response) {

        //接收客户端数据
        String sname = request.getParameter("sname");

        String age = request.getParameter("age");

        String sex = request.getParameter("sex");

        String address = request.getParameter("address");

        String birthday = request.getParameter("birthday");

        //接收多个值
        String[] hobbies = request.getParameterValues("hobby");

        //测试数据
       // System.out.println(sname+" " +age+ " "+sex+" "+ address+" "+birthday);
        String hobbys = "";


        //遍历爱好数组
        for (String hobby : hobbies) {

            hobbys += ","+hobby;

        }
        hobbys=hobbys.substring(1);

        Connection connection = null;
        PreparedStatement preparedStatement = null;

        //使用jdbc保存数据到数据库
        try {
            //获取数据库连接
            connection = JDBCUtils.getConnection();

            //
            String sql = "insert tb_student(sname,age,sex,address,birthday,hobby) values(?,?,?,?,?,?)";
            //获取数据库操作对象
            preparedStatement = connection.prepareStatement(sql);

            //给占位符赋值
            preparedStatement.setString(1,sname);

            preparedStatement.setInt(2,Integer.parseInt(age));

            preparedStatement.setInt(3,Integer.parseInt(sex));

            preparedStatement.setString(4,address);

            preparedStatement.setString(5,birthday);

            int i = preparedStatement.executeUpdate();

            if(i>0){

                System.out.println("success");

                //请求重定向
                response.sendRedirect("http://localhost:8080/managerWeb/stu?flag=list");
            }else {
                System.out.println("defeat");
            }

      } catch (ClassNotFoundException e) {

            e.printStackTrace();

        } catch (SQLException throwables) {

            throwables.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.JDBCClose(connection,preparedStatement,null);
        }


    }

    //具体实现学生列表的方法
    public void getList(HttpServletRequest request, HttpServletResponse response){

        /**
         * 1、通过jdbc访问数据库
         */


        Connection connection =null;

        PreparedStatement preparedStatement = null;

        ResultSet resultSet = null;
        try{

            //注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            //获取数据库连接对象
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_stu?serverTimezone=GMT", "root", "root");

            //获取数据库操作对象,并预编译sql
            preparedStatement = connection.prepareStatement("select * from tb_student");

            //执行SQL语句
            resultSet = preparedStatement.executeQuery();

            ArrayList<Student> stuList = new ArrayList<>();

            //遍历结果集
            while(resultSet.next()){

                //根据表字段取出数据
                String sname = resultSet.getString("sname");

                int age = resultSet.getInt("age");

                int sex = resultSet.getInt("sex");

                String address = resultSet.getString("address");

                String birthday = resultSet.getString("birthday");

                String hobby = resultSet.getString("hobby");

                //取出ID,用于删除与修改
                int id = resultSet.getInt("id");

                System.out.println(sname+ " "+ age+" "+sex+ " "+ address+" "+birthday+" "+hobby);

                //创建学生对象
                Student student = new Student();

                //给对象赋值
                student.setSname(sname);
                student.setAge(age);
                student.setSex(sex);
                student.setBirthday(birthday);
                student.setAddress(address);
                student.setHobby(hobby);

                student.setSid(id);

                //添加学生对象到集合
                stuList.add(student);
            }
            //System.out.println("集合的长度为 "+stuList.size());

            //遍历集合数据
            for (Student student:stuList){

                System.out.println(student);

            }

            /**
             * 二、响应对象到客户端
             * 1、把集合对象存放到域中
             * 2、请求转发跳转资源
             */

            //存放集合对象到域中
            request.setAttribute("stuList",stuList);

            //请求转发
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("/jsp/list.jsp");

            //走向具体的资源
            requestDispatcher.forward(request,response);


        }catch(Exception e){


            e.printStackTrace();
        }finally {
            //关闭数据库资源
            if(resultSet !=null){
                try {
                    resultSet.close();

                } catch (SQLException throwables) {

                    throwables.printStackTrace();
                }
            }

            if(preparedStatement!=null){
                try {
                    preparedStatement.close();

                } catch (SQLException throwables) {

                    throwables.printStackTrace();
                }
            }

            if(connection !=null){
                try {
                    connection.close();

                } catch (SQLException throwables) {

                    throwables.printStackTrace();
                }
            }

        }

    }
}

JDBCUtils.java

package com.jy.util;

import java.sql.*;

/**
 *
 * 封装jdbc工具类
 * 1、构造方法私有化,不希望工具类可以实例化对象
 *
 * 2、所有调用的方法都用static关键字修饰
 */

public class JDBCUtils {

    private JDBCUtils(){}

    /**
     *
     * 把注册驱动写在静态代码块,静态代码块在类加载器的时候执行且只执行一次
     */

    static {

        //注册驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

        } catch (ClassNotFoundException e) {

            e.printStackTrace();
        }

    }
    /**
     * 获取数据库连接
     */

    public static Connection getConnection() throws ClassNotFoundException, SQLException {



        //获取连接
        Connection connection =
                DriverManager.getConnection("jdbc:mysql://localhost:3306/test_stu?serverTimezone=GMT","root","root");


        return connection;
    }

    /**
     *
     * 关闭数据库资源
     */

    public static void JDBCClose(Connection connection, Statement statement, ResultSet resultSet)  {

        //关闭结果集对象
        if(resultSet !=null){

            try {
                resultSet.close();

            } catch (SQLException throwables) {

                throwables.printStackTrace();
            }
        }
        //关闭数据库操作对象
        if(statement != null){
            try {
                statement.close();

            } catch (SQLException throwables) {

                throwables.printStackTrace();
            }
        }

        //关闭数据库连接对象
        if(connection != null){
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }

}


list.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--导入jstl标签库--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
    <title>学生列表</title>
</head>
<body>

<%--jsp中提供了el表达式,可以获取服务端域对象中的数据--%>
<%--
    el表达式语法
    ${后端域对象中的key}
--%>

<%--在当前jsp页面中导入jstl标签(也称之为c标签)

--%>

<%--${stuList}--%>
<%--items  要遍历的对象。要遍历对象从域对象中获取,所以要通过el表达式从域对象中获取
var 遍历的每个元素,用来存放当前指向的元素
border 边框,表格的属性
align="center" 表格居中
<th></th> 会对内容进行加粗
<h1 align="center"> 学生管理页面</h1>标题标签
<a></a>超链接标签
href=""要跳转的地址,属于a标签属性
colspan合并单元格
--%>


<h1 align="center"> 学生管理页面</h1>
<table border="1px" align="center">

    <tr>
        <td colspan="8" align="center">
            <a href="http://localhost:8080/managerWeb/jsp/add.jsp">添加学生</a></td>
    </tr>
    <tr>
    <th>学生姓名</th>
    <th>学生年龄</th>
    <th>学生性别</th>
    <th>学生地址</th>
    <th>学生生日</th>
    <th>学生爱好</th>
    <th>操作</th>

    </tr>
    <c:forEach items="${stuList}" var="stu">
        <tr>
            <td>${stu.sname}</td>
            <td>${stu.age}</td>
            <td>${stu.sex}</td>
            <td>${stu.address}</td>
            <td>${stu.birthday}</td>
            <td>${stu.hobby}</td>
            <td>
                <a href="http://localhost:8080/managerWeb/stu?flag=delete&id=${stu.sid}">删除记录</a>
                <a href="http://localhost:8080/managerWeb/stu?flag=delete">编辑</a>
            </td>

        </tr>

    </c:forEach>
</table>
</body>
</html>


add.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>添加学生</title>
</head>
<body>
<h1 align="center"> 学生添加页面</h1>
<%--
<input type="radio"> 单选框
<input type="checkbox">  多选框
<input type="date"> 日期选择
name 用于分组
文本输入框的name属性将作为获取数据的key
--%>

<form action="http://localhost:8080/managerWeb/stu?flag=add" method="post">
<table align="center">
    <tr>
        <td>学生姓名:</td>
        <td>
            <input type="text" name="sname">
        </td>
    </tr>
    <tr>
        <td>学生年龄:</td>
        <td>
            <input type="text" name="age">
        </td>
    </tr>
    <tr>
    <td>学生性别:</td>
    <td>:<input type="radio" name="sex" value="1">:<input type="radio" name="sex" value="2">
    </td>
    </tr>
    <tr>
    <td>学生住址:</td>
    <td>
        <input type="text" name="address">
    </td>
    </tr>
    <tr>
    <td>生日:</td>
    <td>
        <input type="date" name="birthday">
    </td>
    </tr>
    <tr>
    <td>爱好:</td>
    <td>
        下棋:<input type="checkbox" name="hobby" value="下棋">
        舞剑:<input type="checkbox" name="hobby" value="舞剑">
        论道:<input type="checkbox" name="hobby" value="论道">
        布阵:<input type="checkbox" name="hobby" value="布阵">
        弄枪:<input type="checkbox" name="hobby" value="弄枪">
    </td>
    </tr>

   <tr align="center">
        <td colspan="10"><input type="submit" value="添加" ></td>
    </tr>
</table>
</form>

</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值