完成JDBC的登录操作,JDBC注册用户的操作,并且对功能和业务进行分层,用户登录成功后跳转到主页并且展示数据库的商品信息。

Servlet+JSP+JavaBean开发模式(MVC)介绍

Servlet+JSP+JavaBean模式(MVC)适合开发复杂的web应用,在这种模式下,servlet负责处理用户请求,jsp负责数据显示,javabean负责封装数据。 Servlet+JSP+JavaBean模式程序各个模块之间层次清晰,web开发推荐采用此种模式。

这里以一个最常用的用户登录注册程序来讲解Servlet+JSP+JavaBean开发模式,通过这个用户登录注册程序综合案例,把之前的学过的XML、Xpath、Servlet、jsp的知识点都串联起来。

创建MVC架构的Web项目

在MyEclipse中新创建一个webmvcframework项目,导入项目所需要的开发包(jar包),创建项目所需要的包,在java开发中,架构的层次是以包的形式体现出来的

项目所需要的开发包(jar包)

序号

开发包名称

描述

一,JDBC的登录操作

1,先写两个Goods,User类

public class Goods {
    private Integer gid;
    private String gname;
    private double  price;
    private String mark;


    public Integer getGid() {
        return gid;
    }

    public String getGname() {
        return gname;
    }

    public double getPrice() {
        return price;
    }

    public String getMark() {
        return mark;
    }


    public void setGid(Integer gid) {
        this.gid = gid;
    }

    public void setGname(String gname) {
        this.gname = gname;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public void setMark(String mark) {
        this.mark = mark;
    }


    @Override
    public String toString() {
        return "Goods{" +
                "gid=" + gid +
                ", gname='" + gname + '\'' +
                ", price=" + price +
                ", mark='" + mark + '\'' +
                '}';
    }
}
public class User {
    private Integer uid;
    private String username;
    private String  password;
    private String  phone;
    private String address;


    public Integer getUid() {
        return uid;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public String getPhone() {
        return phone;
    }

    public String getAddress() {
        return address;
    }


    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "uid=" + uid +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", phone='" + phone + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

2,再去写mysql数据库,启动MySQql8.0.12

#判断存在即删除数据库
drop database if exists mydb;
#创建数据库
create database mydb;
#使用数据库
use mydb;


#创建表
create table t_user
(
	uid int primary key auto_increment,
	username varchar(20),
	password varchar(20),
	phone varchar(11),
	address varchar(50)
);


insert into t_user(username,password,phone,address) values('张三','666','18965423548','南阳');
insert into t_user(username,password,phone,address) values('李四','333','18754263548','许昌');
insert into t_user(username,password,phone,address) values('小美','123','18565234759','信阳');

select * from t_user where username=? and password=?
select * from t_user;


create table t_goods
(
	gid int primary key auto_increment,
	gname varchar(20),
	price double,
	mark varchar(100)
);

insert into t_goods(gname,price,mark) values('泡面',4.5,'够香够辣就是这个味!');
insert into t_goods(gname,price,mark) values('火腿',8.5,'肉质细腻Q弹!');
insert into t_goods(gname,price,mark) values('雪碧',3.5,'清爽冰凉随心爽!');

select * from t_goods;

运行后的结果为:

 

 3,再写servlet Login登录,连接数据库

public class Login extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Login-get...");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Login-post...");
        //1.根据请求和响应的编码格式,以及响应的格式
        request.setCharacterEncoding("utf-8");//设置请求的编码格式为中文
        response.setCharacterEncoding("utf-8");//请求响应的编码格式
        response.setContentType("text/html;charset=UTF-8");//以什么样的格式(文本/网页)响应

        //2.获取请求的参数
        String username = request.getParameter("username");//根据表单的name属性获取用户输入的值
        String password = request.getParameter("password");

        //3.执行业务处理
        Connection connection=null;//获取数据库连接
        PreparedStatement pstm=null;//预处理对象
        ResultSet rs=null;//结果集对象
        User login=null;
        try{
            //1.加载驱动程序
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取数据链接
            connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC","root","root");
            //3定义登录的sql语句
            String sql ="select * from t_user where username=? and password=?" ;
            //4.获取预处理对象
            pstm = connection.prepareStatement(sql);
            //5.传参
            pstm.setObject(1,username);
            pstm.setObject(2,password);
            //6.执行查询
            rs = pstm.executeQuery();
            //7.解析结果集
            if(rs.next()){
                login=new User();
                //从结果集中获取数据,封装到实体类对象中
                int uid = rs.getInt("uid");
                login.setUid(uid);
                login.setUsername(rs.getString("username"));
                login.setPassword(rs.getString("password"));
                login.setPhone(rs.getString("phone"));
                login.setAddress(rs.getString("address"));
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //8.关闭资源
            try{
                if(rs!=null){
                    rs.close();
                }
                if(pstm!=null){
                    pstm.close();
                }
                if(connection!=null){
                    connection.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        //判断登录的用户信息是否为空
        if(login!=null){
            //登录成功,跳转到主页
            response.sendRedirect("zhuye.jsp");//指定跳转的页面
        }else {
            //登录失败,跳转到错误页面
            response.sendRedirect("error.jsp");
        }
    }
}

 4,如果登录成功则跳转到主页,跳转失败则跳转到error页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
      <h2>欢迎来到JavaWeb项目</h2>
   <table>
       <thead>
       <tr>
           <td>编号</td>
           <td>名称</td>
           <td>价格</td>
           <td>说明</td>
       </tr>
       </thead>
       <tbody>
       <tr>
           <td>1</td>
           <td>泡面</td>
           <td>3.5</td>
           <td>味道还不错</td>
       </tr>
       <tr>
           <td>2</td>
           <td>火腿肠</td>
           <td>4.5</td>
           <td>好吃</td>
       </tr>
       <tr>
           <td>3</td>
           <td>面包</td>
           <td>5.5</td>
           <td>味道棒极啦</td>
       </tr>
       </tbody>
   </table>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>出错啦</title>
</head>
<body>
<h2>出错啦</h2>
<a href="login.jsp">重新登录</a>
</body>
</html>

 

这样JDBC的登录操作就完成啦!

二,JDBC注册用户的操作

1,写一个注册的jsp

<html>
<head>
    <title>注册</title>
</head>
<body>
      <h2>注册</h2>
      <form action="zhuce" method="post">
          请输入你的账号:<input type="text" name="username" value="" /><br/>
          请输入你的密码:<input type="password" name="password" value="" /><br/>
          请输入你的手机号:<input type="text" name="phone" value="" /><br/>
          请输入你的地址:<input type="text" name="address" value="" /><br/>
          <input type="submit" value="注册">
          <a href="login.jsp">已有账号?请登录</a>
      </form>
</body>
</html>

 2,在servlet中写Zhuce的代码

@WebServlet("/zhuce")
public class Zhuce extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       doPost(request, response);
    }

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

        //1.根据请求和响应的编码格式,以及响应的格式
        request.setCharacterEncoding("utf-8");//设置请求的编码格式为中文
        response.setCharacterEncoding("utf-8");//请求响应的编码格式
        response.setContentType("text/html;charset=UTF-8");//以什么样的格式(文本/网页)响应

        //2.获取请求的参数
        String username = request.getParameter("username");//根据表单的name属性获取用户输入的值
        String password = request.getParameter("password");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");


        User user=new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setPhone(phone);
        user.setAddress(address);

        UserDaoImpl userDao = new UserDaoImpl();
        int row=userDao.zhuce(user);
        if (row>0){
            response.sendRedirect("login.jsp");
        }else {
            response.sendRedirect("zhuce.jsp");
        }
    }
}

 3,这样JDBC的注册操作就完成啦!

 

 

 三,功能和业务进行分层

1,创建一个dao包,里面写UserDaoImpl代码

public class UserDaoImpl implements UserDao {
    Connection con = null;
    PreparedStatement pstm=null;
    ResultSet rs=null;
    User login=null;
    private int row=0;
    public User login(String username,String password){
        User login=null;
        try{
            con= JDBCUtil.getCon();
            String sql="select * from t_user where username=? and password=?";
            pstm=con.prepareStatement(sql);
            pstm.setObject(1,username);
            pstm.setObject(2,password);
           rs=pstm.executeQuery();
           if(rs.next()){
               login=new User();
               login.setUsername(rs.getString("username"));
               login.setPassword(rs.getString("password"));
               login.setPhone(rs.getString("phone"));
               login.setAddress(rs.getString("address"));
           }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.close(rs,pstm,con);
        }
        return login;
    }

    public int zhuce(User user){
        try{
            con= JDBCUtil.getCon();
            String sql="insert into t_user(username,password,phone,address) values(?,?,?,?)";
            pstm=con.prepareStatement(sql);
            pstm.setObject(1,user.getUsername());
            pstm.setObject(2,user.getPassword());
            pstm.setObject(3,user.getPhone());
            pstm.setObject(4,user.getAddress());
            row=pstm.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.zhuce(pstm,con);
        }
         return row;
    }
}

2,再写一个UserDao接口

public interface UserDao {
    User login(String username,String password);
    int zhuce(User user);
}

 3,再创建util工具包,写JDBCUtil代码

public class JDBCUtil {
    private static String driver="com.mysql.cj.jdbc.Driver";
    private static String url="jdbc:mysql://localhost:3306/mydb";
    private static String username="root";
    private static String password="root";

    private static Connection connection=null;

    public static Connection getCon(){
        try{
            Class.forName(driver);
            connection = DriverManager.getConnection(url,username,password);
        }catch (Exception e){
            e.printStackTrace();
        }
        return connection;
    }

    public  static void close(ResultSet rs,PreparedStatement pstm, Connection con){
        try{
            if(rs!=null){
                rs.close();
            }
            if(pstm!=null){
                pstm.close();
            }
            if(con!=null){
                pstm.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public  static void zhuce(PreparedStatement pstm, Connection con){
        try{
            if(pstm!=null){
                pstm.close();
            }
            if(con!=null){
                pstm.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}

 这样功能和业务进行分层就完成啦!

四,用户登录成功后跳转到主页并展示数据库的商品信息

1,在dao包中写GoodsDao代码

public class GoodsDao {
    private static String JDBCdriver = "com.mysql.cj.jdbc.Driver";
    private static String JDBCurl = "jdbc:mysql://localhost:3306/mydb";
    private static String JDBCusername = "root";
    private static String JDBCpassword = "root";

    Connection con = null;
    PreparedStatement pstm = null;
    ResultSet rs = null;
    int row = 0;

    public List<Goods> selectAll() {
        List<Goods> goodsList = new ArrayList<>();
        try {
            Class.forName(JDBCdriver);
            con = DriverManager.getConnection(JDBCurl, JDBCusername, JDBCpassword);
            String sql = "select * from t_goods";
            pstm = con.prepareStatement(sql);
            rs = pstm.executeQuery();
            while (rs.next()) {
                //从结果集中获取数据,封装到Goods对象中
                Goods goods = new Goods();
                goods.setGid(rs.getInt("gid"));
                goods.setGname(rs.getString("gname"));
                goods.setPrice(rs.getDouble("price"));
                goods.setMark(rs.getString("mark"));
                //把当前行对应的对象储存到集合中
                goodsList.add(goods);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(rs!=null){
                    rs.close();
                }
                if(pstm!=null){
                    pstm.close();
                }
                if(con!=null){
                    con.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return goodsList;
    }

}

2,在servlet包中写Login代码,SelectAllGoods代码

@WebServlet("/login")
public class Login extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

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

        //1.根据请求和响应的编码格式,以及响应的格式
        request.setCharacterEncoding("utf-8");//设置请求的编码格式为中文
        response.setCharacterEncoding("utf-8");//请求响应的编码格式
        response.setContentType("text/html;charset=UTF-8");//以什么样的格式(文本/网页)响应

        //2.获取请求的参数
        String username = request.getParameter("username");//根据表单的name属性获取用户输入的值
        String password = request.getParameter("password");

        //3,执行业务处理---jdbc操作
        UserDao userDao=new UserDao();
        User login = userDao.login(username,password);

        //4,判断登录的用户信息是否为空
        if(login!=null){
            System.out.println("登录成功");
            //登录成功,当前servlet的业务处理完毕---后续执行查询商品的操作应该由别人来完成---请求转发给别的servlet处理
            request.getRequestDispatcher("selectAllGoods").forward(request,response);
        }else {
            //登录失败,跳转到错误页面
            response.sendRedirect("error.jsp");
        }
    }
}
@WebServlet("/selectAllGoods")
public class SelectAllGoods extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("SelectAllGoods...doPost");
        //查询所有商品信息
        GoodsDao goodsDao = new GoodsDao();
        List<Goods> goodsList = goodsDao.selectAll();
        System.out.println(goodsList);

        //把数据传递到前端页面
        //通过request获取session对象,该对象可以向前端传输数据的容器
        HttpSession session = request.getSession();
        //向session中存入商品信息集合
        session.setAttribute("goodsList",goodsList);
        //登录成功,跳转到主页
        response.sendRedirect("zhuye.jsp");
    }
}

3,在web里面写zhuye.jsp代码

<html>
<head>
    <title>Title</title>
</head>
<body>
      <h2>欢迎来到JavaWeb项目</h2>
<%--      <a href="login.jsp">欢迎来到主页</a>--%>
   <table>
       <thead>
       <tr>
           <td>商品编号</td>
           <td>商品名称</td>
           <td>商品价格</td>
           <td>商品说明</td>
       </tr>
       </thead>
       <tbody id="list">
             <%
                 //获取session
                 HttpSession session1 = request.getSession();
                 //从session中取出数据
                 List<Goods> goodsList = (List<Goods>) session1.getAttribute("goodsList");
                 //遍历集合元素
                 for (Goods goods : goodsList) {
                 %>
             <tr>
                  <td><%=goods.getGid()%></td>
                  <td><%=goods.getGname()%></td>
                  <td><%=goods.getPrice()%></td>
                  <td><%=goods.getMark()%></td>
               </tr>
             <%
                 }
             %>
       </tbody>
   </table>
</body>
</html>

运行结果为:

 这样用户登录成功后跳转到主页并且展示数据库的商品信息就完成啦

猜你喜欢

转载自blog.csdn.net/weixin_69036336/article/details/129096591