JavaWeb基础学习一无框架项目小练习

一、概述

这个作为javaWeb最基础的部分,往往用框架时间长了就忘了底层是怎样实现的了,在这个文章中我用来帮助自己快速回忆底层部分原理整理了一个简单的demo。

本人前端小白,所以demo中前台部分一笔带过额,见谅哈哈

demo功能就是通过页面按钮操作两张表,player和team表:一个是添加一条记录给数据库,还有一个是查一下表

二、准备

首先最基本的各个jar包要有啊,servlet和mysql驱动和druid连接池

还有别忘记安装mysql还有创建两张表

2.1tomcat概念

tomcat就是一个容器,servlet不是直接与前后台交互,而是放在tomcat中,由tomcat去和前后台发请求。

tomcat通过请求响应模式来访问容器中的servlet程序,如图

2.2servlet概念

servlet本质上就是java程序代码。

主要使用是继承HTTPservlet,重写doGet和doPost方法,然后在web.xml中注册servlet

 2.3servlet生命周期

2.4功能

处理html表单信息读取,设置http请求头、处理cookie、跟踪会话等

2.5与jsp区别

jsp是将java代码镶嵌到html中,是.jsp格式文件,jsp侧重于视图层,servlet侧重控制层。

2.6与tomcat关系

tomcat是容器,servelt不会直接与客户端打交道,而是容器接收请求,根据url解析请求,确定将请求交给哪个servlet,然后创建servlet、初始化方法,service方法,servlet响应的信息返回给tomcat,tomcat再给客户端。

2.7会话跟踪技术

同一台客户端发送的请求,信息可以报存在session中,默认是30分钟,但是不同客户端就无法请求到了。

 2.8转发和重定向

转发:一次请求响应的过程,对于客户端而言,内部经过多少次转发,客户端并不知道(地址栏也未发生变化)

req.getRequestDispatcher("").forward(req,resp);

重定向:两次请求响应,客户端知道url变化

resp.sendRedirect("");

三、操作练习

目录结构

 1.持久层

druid.properties

url=jdbc:mysql://******:3306/loong
username=*****
password=*******
driverClassName=com.mysql.cj.jdbc.Driver
initialSize=8

JDBCUtils

/**
 * @author JLoong
 * @date 2022/3/7 22:38
 */
public class JdbcUtil {

    private static DataSource source;

    static {
        try {
            InputStream is = JdbcUtil.class.getClassLoader().getResourceAsStream("druid.properties");
            Properties prop = new Properties();
            prop.load(is);
            source = DruidDataSourceFactory.createDataSource(prop);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取连接
     *
     * @return
     * @throws Exception
     */
    public static Connection getConnection() throws Exception {
        return source.getConnection();
    }

    /**
     * 关闭资源
     *
     * @param connection
     * @param statement
     */
    public static void closeResource(Connection connection, Statement statement) {
        try {
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void closeResource(Connection connection, Statement statement, ResultSet resultSet) {
        try {
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
            resultSet.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新表内容
     *
     * @param sql
     * @param args
     */
    public static void updateTable(String sql, Object... args) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {

            //获取连接
            conn = getConnection();

            //预加载
            ps = conn.prepareStatement(sql);

            //填充占位符
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }

            //执行
            ps.execute();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            //关闭资源
            closeResource(conn, ps);
        }
    }

    public static <T> List<T> queryTable(Class<T> tClass, String sql, Object... args) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            //获取连接
            conn = JdbcUtil.getConnection();

            //prepareStatement预加载sql
            ps = conn.prepareStatement(sql);

            //填充占位符
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }

            //执行,并返回结果集
            rs = ps.executeQuery();

            //获取结果集的元数据
            ResultSetMetaData rsmd = rs.getMetaData();

            //获取结果集的列数
            int columnCount = rsmd.getColumnCount();

            //new结果集
            ArrayList<T> list = new ArrayList<>();
            while (rs.next()) {
                T t = tClass.newInstance();
                for (int i = 0; i < columnCount; i++) {
                    Object columnValue = rs.getObject(i + 1);
                    String columnLabel = rsmd.getColumnLabel(i + 1);
                    Field field = tClass.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(t, columnValue);
                }
                list.add(t);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.closeResource(conn, ps, rs);
        }
        return null;
    }


}

bean

/**
 * @author JLoong
 * @date 2022/3/9 23:23
 */
public class Team {

    private int id;
    private String name;
    private String city;
    private int money;
    private int cid;

    public Team() {
    }

    public Team(int id, String name, String city, int money, int cid) {
        this.id = id;
        this.name = name;
        this.city = city;
        this.money = money;
        this.cid = cid;
    }

    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 String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

    public int getCid() {
        return cid;
    }

    public void setCid(int cid) {
        this.cid = cid;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        Team team = (Team) o;
        return id == team.id && money == team.money && cid == team.cid && name.equals(team.name) && city.equals(team.city);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name, city, money, cid);
    }

    @Override
    public String toString() {
        return "Team{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", city='" + city + '\'' +
                ", money=" + money +
                ", cid=" + cid +
                '}';
    }
}
/**
 * @author JLoong
 * @date 2022/3/9 23:18
 */

public class Player {
    private int id;
    private String name;
    private String identity;
    private int age;
    private Double avgScore;
    private int fansNum;
    private String nickname;
    private int salary;
    private int tid;

    public Player() {
    }

    public Player(int id, String name, String identity, int age, Double avgScore, int fansNum, String nickname, int salary, int tid) {
        this.id = id;
        this.name = name;
        this.identity = identity;
        this.age = age;
        this.avgScore = avgScore;
        this.fansNum = fansNum;
        this.nickname = nickname;
        this.salary = salary;
        this.tid = tid;
    }

    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 String getIdentity() {
        return identity;
    }

    public void setIdentity(String identity) {
        this.identity = identity;
    }

    public int getAge() {
        return age;
    }

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

    public Double getAvgScore() {
        return avgScore;
    }

    public void setAvgScore(Double avgScore) {
        this.avgScore = avgScore;
    }

    public int getFansNum() {
        return fansNum;
    }

    public void setFansNum(int fansNum) {
        this.fansNum = fansNum;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }

    public int getTid() {
        return tid;
    }

    public void setTid(int tid) {
        this.tid = tid;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        Player player = (Player) o;
        return id == player.id && age == player.age && fansNum == player.fansNum && salary == player.salary && tid == player.tid && name.equals(player.name) && identity.equals(player.identity) && avgScore.equals(player.avgScore) && nickname.equals(player.nickname);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name, identity, age, avgScore, fansNum, nickname, salary, tid);
    }

    @Override
    public String toString() {
        return "Player{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", identity='" + identity + '\'' +
                ", age=" + age +
                ", avgScore=" + avgScore +
                ", fansNum=" + fansNum +
                ", nickname='" + nickname + '\'' +
                ", salary=" + salary +
                ", tid=" + tid +
                '}';
    }
}

2.service和dao

/**
 * @author JLoong
 * @date 2022/3/9 23:22
 */
public interface LoongService {

    /**
     * 注册球队
     * @param team
     */
    public void addTeam(Team team) throws Exception;

    /**
     * 查询球员
     * @param id
     */
    public Player getPlayer(int id) throws Exception;
}
/**
 * @author JLoong
 * @date 2022/3/9 23:22
 */
public class LoongServiceImpl implements LoongService {

    TeamDao teamDao = new TeamDaoImpl();

    @Override
    public void addTeam(Team team) throws Exception {
        teamDao.addTeam(team);
    }

    @Override
    public Player getPlayer(int id) throws Exception {

        return teamDao.getPlayer(id);
    }
}
/**
 * @author JLoong
 * @date 2022/3/9 23:45
 */
public interface TeamDao {

    /**
     * 增加球队
     * @param team
     */
    public void addTeam(Team team) throws Exception;

    /**
     * 查询球员
     * @param id
     */
    public Player getPlayer(int id) throws Exception;
}
public class TeamDaoImpl implements TeamDao {
    @Override
    public void addTeam(Team team) throws Exception {
        System.out.println(team);
        String sql = "INSERT INTO team(id,name,city,money,cid) VALUES(?,?,?,?,?)";
        JdbcUtil.updateTable(sql, team.getId(), team.getName(), team.getCity(), team.getMoney(), team.getCid());

    }

    @Override
    public Player getPlayer(int id) throws Exception {
        String sql = "SELECT * FROM player WHERE id = ?";
        return Objects.requireNonNull(JdbcUtil.queryTable(Player.class, sql, id)).get(0);
    }
}

3.servlet

/**
 * @author JLoong
 * @date 2022/3/6 19:56
 */
public class AddTeamServlet extends HttpServlet {

    LoongService loongService = new LoongServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String sId = req.getParameter("id");
        int id = Integer.parseInt(sId);
        String name = req.getParameter("name");
        String city = req.getParameter("city");
        String sMoney = req.getParameter("money");
        int money = Integer.parseInt(sMoney);
        String sCid = req.getParameter("cid");
        int cid = Integer.parseInt(sCid);

        Team team = new Team(id, name, city, money, cid);
        try {
            loongService.addTeam(team);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
@WebServlet("/getPlayer")
public class GetPlayerServlet extends HttpServlet {
    LoongService loongService = new LoongServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        req.setCharacterEncoding("UTF-8");
        String sId = req.getParameter("id");
        int id = Integer.parseInt(sId);
        try {
            PrintWriter pw = resp.getWriter();
          pw.println(loongService.getPlayer(id));
        } catch (Exception e) {
            e.printStackTrace();
        }
        resp.getWriter();
    }
}

4.web.xml

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>
    <servlet>
        <servlet-name>AddTeamServlet</servlet-name>
        <servlet-class>com.jloong.servlets.AddTeamServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>AddTeamServlet</servlet-name>
        <url-pattern>/addTeam</url-pattern>
    </servlet-mapping>

</web-app>

5.前台页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Web001小项目</title>
</head>
<body>
<h1>Hello loong 哥</h1>
<form action="addTeam" method="post">
    编号:<input type="text" name="id"/><br/>
    队名:<input type="text" name="name"/><br/>
    城市:<input type="text" name="city"/><br/>
    工资帽:<input type="text" name="money"/><br/>
    队长:<input type="text" name="cid"/><br/>
    <input type="submit" value="注册球队"/>
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Web001小项目</title>
</head>
<body>
<h1>Hello loong 哥</h1>
<form action="getPlayer" method="get">
    编号:<label>
    <input type="text" name="id"/>
</label><br/>
    <input type="submit" value="查询运动员"/>
</form>
</body>
</html>

  • 8
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿星_Alex

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值