1. 程式人生 > >Javaweb項目 利用JSP響應瀏覽器

Javaweb項目 利用JSP響應瀏覽器

while delet 使用 lose getattr Language upd boolean day01

一、javaweb 數據訪問流程?

1.瀏覽器 http 訪問服務器 找到 servlet(HttpServeltDemo.java文件)

2.servle 通過dao 訪問數據庫 數據庫將數據返回給servlet

3.servlet找尋指定的JSP文件 將student數據傳送給JSP

4.JSP獲得數據,展示在網頁上。將數據返回給servlet

5.servlet將數據 傳送給瀏覽器。

二、將數據庫中的student 展示在http頁面 。代碼體現 ?

  裝備工作建立四個包。

1.dao

package com.aaa.dao;

import com.aaa.entity.Student;

import java.util.List; import java.util.Map; public interface IStudentDAO { boolean add(Student s); boolean delete(int id); boolean update(Student s); Map<String ,Object> getStudent(int id); List<Map<String,Object>> getAllStudent(); }

dao.Impl 實現一個 供測試使用。

package com.aaa.dao.Impl;

import com.aaa.dao.IStudentDAO;
import com.aaa.entity.Student;
import com.aaa.util.DBUtil;

import java.util.List;
import java.util.Map;

public class StudentDAOImpl implements IStudentDAO {
    @Override
    public boolean add(Student s) {
        return false
; } @Override public boolean delete(int id) { return false; } @Override public boolean update(Student s) { return false; } @Override public Map<String, Object> getStudent(int id) { return null; } @Override public List<Map<String, Object>> getAllStudent() { String sql="select * from student "; return DBUtil.executeQuery(sql); } }

2.entity 實體類

package com.aaa.entity;

public class Student {
    private int id;
    private String name;
    private int age;

    public Student(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Student() {
        super();
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name=‘" + name + ‘\‘‘ +
                ", age=" + age +
                ‘}‘;
    }
}

3.封裝工具類

package com.aaa.util;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DBUtil {
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    public  static Connection getConnetion(){
        try {
          return   DriverManager.getConnection("jdbc:mysql://localhost:3306/qy66?characterEnconding=UTF-8","root","root");
        } catch (SQLException e) {
            e.printStackTrace();
        }
       return null;
    }
    public  static boolean executeUpdate(String sql,Object... args){
        Connection con=null;
        PreparedStatement ps=null;

        try {
            con=DBUtil.getConnetion();
            ps=con.prepareStatement(sql);

            for (int i = 0; i <args.length ; i++) {
                ps.setObject(i+1,args[i]);
            }
            int i=ps.executeUpdate();
            return  i>0;

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            close(con,ps,null);
        }
        return  false;
    }

    public static List<Map<String, Object>>  executeQuery(String sql, Object... args){
        Connection con=null;
        PreparedStatement ps=null;
        ResultSet rs=null;


        try {
            con=getConnetion();
            ps=con.prepareStatement(sql);

            for (int i = 0; i <args.length ; i++) {
                ps.setObject(i+1,args[i]);
            }
           rs=ps.executeQuery();

            List<Map<String,Object>>list=new ArrayList<>();

            int count=rs.getMetaData().getColumnCount();

            while (rs.next()){

                Map<String,Object>map= new HashMap<>();

                for (int i = 0; i < count; i++) {
                    String name = rs.getMetaData().getColumnLabel(i + 1);
                    map.put(name,rs.getObject(name));
                }
                list.add(map);
            }
            return list;

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            close(con,ps,rs);
        }
        return null;
    }

    private static void close(Connection con, PreparedStatement ps, ResultSet rs) {
        if (rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (ps!=null){
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (con!=null){
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

4.servlet 測試。

package com.aaa.servlet;

import com.aaa.dao.IStudentDAO;
import com.aaa.dao.Impl.StudentDAOImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
@WebServlet("/666") //虛擬路徑 不用再配置xml文件  快捷
public class HttpServletDemo extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.獲取數據庫中的數據
        IStudentDAO dao=new StudentDAOImpl();
        List<Map<String, Object>> list = dao.getAllStudent();
        
       /*
            2.請求共享數據 就是需要servlet展示什麽數據 
            req.setattribute("01",list)  展示list數據 名字叫01【關鍵字的作用】 因為這種文件可能
            會有很多  方便servlet找的到  我們所需要的JSP文件
         */
        req.setAttribute("01",list);
        
        //3.請求轉發到某個JSP  3.1 新建JSP文件 day01.jsp
        req.getRequestDispatcher("day01.jsp").forward(req,resp);
    }
}

5.JSP 代碼部分?

<%@ page import="java.util.List" %>
<%@ page import="java.util.Map" %><%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2019/4/15
  Time: 22:57
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <title>Title</title>
</head>
<body>
    <table border="1" cellspacing="0">
        <tr>
            <th>id</th>
            <th>name</th>
            <th>age</th>
        </tr>
                <!--1. 在JSP中獲取數據-->
                <!--6.a:註意JSP寫在 web目錄下  b:lib目錄建立在 WEB-INF下-->
        <% List<Map<String,Object>>list=(List<Map<String,Object>>)request.getAttribute("01");%> <!-- 2.強制裝換-->

        <%     for (Map map:list) {      %>  <!--3. java 代碼在JSP中書寫方式  for循環  獲得每一列中的數據     -->
        <tr>
            <td> <%=map.get("id")%> </td>   <!-- 5.‘=‘等於號 是將java代碼顯示在 網頁上-->
            <td> <%=map.get("name")%>> </td>
            <td> <%=map.get("age")%>> </td>
        </tr>


        <%  }  %> <!--4. for循環的結尾-->
    </table>
</body>
</html>

  

Javaweb項目 利用JSP響應瀏覽器