• jsp+servlet+javabean开发web项目


    一.介绍:

      项目依赖包:jdbc数据库包

      jsp+servlet+javabean开发web项目,是最接近web项目原生运行原理的。

      但是,jsp内容混乱,项目结构复杂时,代码会混乱


    二.运行原理:

      jsp发出请求到web--

      web接收请求并匹配请求对应的servlet--

      servlet调用数据库dao层操作数据库--

      如果有数据传递,放到request或者session中

      重点:servlet会执行doService()方法来判断调用doGet()或者doPost()

    三.开发步骤:

    1.新建web项目

    2.新建实体类  User.java

     1 package com.mart.bean;
     2 
     3 public class User {
     4     
     5     //属性
     6     private Integer id;
     7     private String uname;
     8     private String upass;
     9     private String tname;
    10     private String utype;
    11     //属性访问
    12     public Integer getId() {
    13         return id;
    14     }
    15     public void setId(Integer id) {
    16         this.id = id;
    17     }
    18     public String getUname() {
    19         return uname;
    20     }
    21     public void setUname(String uname) {
    22         this.uname = uname;
    23     }
    24     public String getUpass() {
    25         return upass;
    26     }
    27     public void setUpass(String upass) {
    28         this.upass = upass;
    29     }
    30     public String getTname() {
    31         return tname;
    32     }
    33     public void setTname(String tname) {
    34         this.tname = tname;
    35     }
    36     public String getUtype() {
    37         return utype;
    38     }
    39     public void setUtype(String utype) {
    40         this.utype = utype;
    41     }
    42     
    43     //构造
    44     public User() {
    45         super();
    46         // TODO Auto-generated constructor stub
    47     }
    48     public User(Integer id, String uname, String upass, String tname,
    49             String utype) {
    50         super();
    51         this.id = id;
    52         this.uname = uname;
    53         this.upass = upass;
    54         this.tname = tname;
    55         this.utype = utype;
    56     }
    57     public User(String uname, String upass, String tname, String utype) {
    58         super();
    59         this.uname = uname;
    60         this.upass = upass;
    61         this.tname = tname;
    62         this.utype = utype;
    63     }
    64     //更新操作改善,不加name更新
    65     public User(Integer id, String upass, String tname, String utype) {
    66         super();
    67         this.id = id;
    68         this.upass = upass;
    69         this.tname = tname;
    70         this.utype = utype;
    71     }
    72     
    73     //tostring
    74     @Override
    75     public String toString() {
    76         return "User [id=" + id + ", uname=" + uname + ", upass=" + upass
    77                 + ", tname=" + tname + ", utype=" + utype + "]";
    78     }
    79     
    80     
    81 }

    3.编写操作接口  UserDao.java

    package com.mart.dao;
    
    import java.util.List;
    
    import com.mart.bean.User;
    
    public interface UserDao {
        /**
         * @param u 待添加的用户
         * @return 0-添加失败  1-添加成功 
         */
        public Integer addUser(User u);
        /**
         * @param id 待删除用户编号
         * @return 0-删除失败  1-删除成功
         */
        public Integer delUser(Integer id);
        /**
         * @param u 要添加的用户
         * @return 0-更新失败  1-更新成功
         */
        public Integer updUser(User u);
        /**
         * @param id 待查找的用户编号
         * @return 要查找的用户
         */
        public User findUserById(Integer id);
        /**
         * @return 全部用户列表
         */
        public List<User> FindAllUser();
        
        
    }

    4.编写数据库操作工具类  DBUtil.java

    package com.mart.util;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    
    public class DBUtil {
        
        //获取oracle数据库连接
        public Connection getCurrentConnection(){
            //初始返回值
            Connection conn = null;
            
            try {
                //加载驱动
                Class.forName("oracle.jdbc.driver.OracleDriver");
                conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl", 
                                                    "mart", "java");
                
                
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
            
            return conn;
        }
    }

    5.编写接口实现  UserDaoImpl.java

    package com.mart.dao.impl;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
    
    import com.mart.bean.User;
    import com.mart.dao.UserDao;
    import com.mart.util.DBUtil;
    
    public class UserDaoImpl implements UserDao{
    
        @Override
        public Integer addUser(User u) {
            // TODO Auto-generated method stub
            int res=-1;
            //连接数据库
            DBUtil dbUtil = new DBUtil();
            Connection conn = dbUtil.getCurrentConnection();
            //添加语句
            PreparedStatement ps = null;
            String sql = "insert into mart_user values(seq_mart_user.nextval,?,?,?,?)";
            
            try {
                ps = conn.prepareStatement(sql);
                ps.setString(1, u.getUname());
                ps.setString(2, u.getUpass());
                ps.setString(3, u.getTname());
                ps.setString(4, u.getUtype());
                //执行
                res = ps.executeUpdate();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                try {
                    if(ps!=null)ps.close();
                    if(conn!=null)conn.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            
            return res;
        }
    
        @Override
        public Integer delUser(Integer id) {
            // TODO Auto-generated method stub
            int res=-1;
            //连接数据库
            DBUtil dbUtil = new DBUtil();
            Connection conn = dbUtil.getCurrentConnection();
            //删除语句
            PreparedStatement ps = null;
            String sql = "delete from mart_user where id=?";
            try {
                ps = conn.prepareStatement(sql);
                ps.setInt(1, id);
                //执行
                res = ps.executeUpdate();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                try {
                    if(ps!=null)ps.close();
                    if(conn!=null)conn.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            
            return res;
        }
    
        @Override
        public Integer updUser(User u) {
            // TODO Auto-generated method stub
            int res=-1;
            //连接数据库
            DBUtil dbUtil = new DBUtil();
            Connection conn = dbUtil.getCurrentConnection();
            //更新语句
            PreparedStatement ps = null;
            String sql = "update mart_user set upass=?,tname=?,utype=? where id=?";
            
            try {
                ps = conn.prepareStatement(sql);
    //            ps.setString(1, u.getUname());--完善更改,不设置名字
                ps.setString(1, u.getUpass());
                ps.setString(2, u.getTname());
                ps.setString(3, u.getUtype());
                ps.setInt(4, u.getId());
                //执行
                res = ps.executeUpdate();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                try {
                    if(ps!=null)ps.close();
                    if(conn!=null)conn.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            
            return res;
        }
    
        @Override
        public User findUserById(Integer id) {
            // TODO Auto-generated method stub
            User u = null;
            //连接数据库
            DBUtil dbUtil = new DBUtil();
            Connection conn = dbUtil.getCurrentConnection();
            //查找语句
            PreparedStatement ps = null;
            ResultSet rs = null;
            String sql = "select * from mart_user where id=?";
            
            try {
                ps = conn.prepareStatement(sql);
                ps.setInt(1, id);
                //获取结果
                rs = ps.executeQuery();
                rs.next();
                u = new User(rs.getInt("id"), rs.getString("uname"), rs.getString("upass"), 
                                rs.getString("tname"), rs.getString("utype"));
                
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                try {
                    if(rs!=null)rs.close();
                    if(ps!=null)ps.close();
                    if(conn!=null)conn.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            
            return u;
        }
    
        @Override
        public List<User> FindAllUser() {
            // TODO Auto-generated method stub
            List<User> uList = new ArrayList<User>();
            //连接数据库
            DBUtil dbUtil = new DBUtil();
            Connection conn = dbUtil.getCurrentConnection();
            //查找语句
            PreparedStatement ps = null;
            ResultSet rs = null;
            String sql = "select * from mart_user";
            
            try {
                ps = conn.prepareStatement(sql);
                rs = ps.executeQuery();
                //获取结果
                while(rs.next()){
                    uList.add(new User(rs.getInt("id"), rs.getString("uname"), rs.getString("upass"), 
                                rs.getString("tname"), rs.getString("utype")));
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                try {
                    if(rs!=null)rs.close();
                    if(ps!=null)ps.close();
                    if(conn!=null)conn.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            
            return uList;
        }
    
    }

     6.编写测试文件,测试是否底层数据操作成功  UserTest.java

    package com.mart.test;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import com.mart.bean.User;
    import com.mart.dao.impl.UserDaoImpl;
    
    public class UserTest {
        //主测试
        public static void main(String[] args) {
            //实例化实现
            UserDaoImpl udi = new UserDaoImpl();
            
    //        addTest(udi);
    //        delTest(udi);
    //        updTest(udi);
    //        findTest(udi);
    //        findAllTest(udi);
            
        }
        
        //添加测试
        private static void addTest(UserDaoImpl udi){
            //设置添加对象
            User u = new User("wangwu", "0002", "王五", "0");
            Integer res = udi.addUser(u);
            if(res>0){
                System.out.println("添加成功");
            }else{
                System.out.println("添加失败");
            }
        }
        //删除测试
        private static void delTest(UserDaoImpl udi){
            //设置删除编号
            int id = 2;
            int res = udi.delUser(id);
            if(res>0){
                System.out.println("删除成功");
            }else{
                System.out.println("删除失败");
            }
        }
        //更新测试
        private static void updTest(UserDaoImpl udi){
            //设置更新对象
            User u = new User(9, "tiqi", "123", "田七", "0");
            Integer res = udi.updUser(u);
            if(res>0){
                System.out.println("更新成功");
            }else{
                System.out.println("更新失败");
            }
        }
        //id查找测试
        private static void findTest(UserDaoImpl udi){
            //设置查找id
            int id = 6;
            User u =udi.findUserById(id);
            System.out.println(u);
        }
        //全部查找
        private static void findAllTest(UserDaoImpl udi){
            //新建保存集
            List<User> uList = new ArrayList<User>();
            uList = udi.FindAllUser();
            for (User user : uList) {
                System.out.println(user);
            }
        }
        
        
    }

    7.编写jsp显示界面,仅以用户显示界面为例  show.jsp

    <%@page import="com.mart.bean.User"%>
    <%@page import="com.mart.dao.impl.UserDaoImpl"%>
    <%@page import="com.mart.dao.UserDao"%>
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <html>
      <head>
        <title>用户显示</title>    
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">    
      </head>
      
      <body>
        <div class="top" style=" 800px;height: 50px">
            <h3>用户显示界面</h3>
        </div>
        <div class="center" style=" 800px;height: auto;">
            <table border="1">
                <tr>
                    <th>用户编号</th>
                    <th>用户账户</th>
                    <th>用户密码</th>
                    <th>真实名字</th>
                    <th>用户类型</th>
                    <th>用户操作</th>
                </tr>
                <tr>
                   <%
                       //实例化接口
                       UserDao udi = new UserDaoImpl();
                       List<User> uList = new ArrayList<User>();
                       uList = udi.FindAllUser();
                       for(User u : uList){
                    %>
                        <tr>
                            <td>
                                <%=u.getId() %>
                            </td>
                            <td>
                                <%=u.getUname() %>
                            </td>
                            <td>
                                <%=u.getUpass() %>
                            </td>
                            <td>
                                <%=u.getTname() %>
                            </td>
                            <td>
                                <%=u.getUtype().equals("0")?"普通":"管理员" %>
                            </td>
                            <td>
                                <a href="upd.jsp?id=<%=u.getId() %>&uname=<%=u.getUname()%>&
                                                upass=<%=u.getUpass() %>&tname=<%=u.getTname()%>&
                                                utype=<%=u.getUtype() %>">更新</a>
                                /<a href="../del.do?id=<%=u.getId() %>">删除</a>
                            </td>
                        </tr>
                    <%
                       }
                    %>
                </tr>
                <tr>
                    <td colspan="6" align="center">
                        <a href="./add.jsp">用户添加</a>
                    </td>
                </tr>
            </table>
        </div>
        
      </body>
    </html>

    8.编写servlet文件  ShowAction.java

    package com.mart.controller;
    
    import java.io.IOException;
    import java.util.List;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.mart.bean.User;
    import com.mart.dao.UserDao;
    import com.mart.dao.impl.UserDaoImpl;
    
    public class ShowAction extends HttpServlet {
    
        //解析请求方法
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            
            System.out.println("用户展示界面:com.mart.controller.show");
            //获取用户列表
            UserDao udi = new UserDaoImpl();
            List<User> uList = udi.FindAllUser();
            //传递用户列表到前断
            //此处用session则服务器过载
            request.setAttribute("uList", uList);
            //转到显示界面
            //不能重定向,会丢失数据
            response.sendRedirect("user/show.jsp");
            
        }
    
        //响应请求方法
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            /**
             * get和post行为相同时,直接设置内部调用即可
             */
            this.doGet(request, response);
        }
    
    }

     8.在web.xml里注册servlet

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" 
        xmlns="http://java.sun.com/xml/ns/javaee" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
      <display-name>淘宝商城servlet-xml配置</display-name>
      <servlet>
        <description>这是我的用户显示界面,显示全部用户</description>
        <display-name>user_show</display-name>
        <servlet-name>ShowAction</servlet-name>
        <servlet-class>com.mart.controller.ShowAction</servlet-class>
      </servlet>
      <servlet>
        <description>这是我的用户添加界面</description>
        <display-name>user_add</display-name>
        <servlet-name>AddAction</servlet-name>
        <servlet-class>com.mart.controller.AddAction</servlet-class>
      </servlet>
      <servlet>
        <description>这是我的用户删除界面</description>
        <display-name>user_delete</display-name>
        <servlet-name>DeleteAction</servlet-name>
        <servlet-class>com.mart.controller.DeleteAction</servlet-class>
      </servlet>
      <servlet>
        <description>这是我的用户更新界面</description>
        <display-name>user_update</display-name>
        <servlet-name>UpdateAction</servlet-name>
        <servlet-class>com.mart.controller.UpdateAction</servlet-class>
      </servlet>
    
    
    
    
      <servlet-mapping>
        <servlet-name>ShowAction</servlet-name>
        <url-pattern>/show.do</url-pattern>
      </servlet-mapping>
      <servlet-mapping>
        <servlet-name>AddAction</servlet-name>
        <url-pattern>/add.do</url-pattern>
      </servlet-mapping>
      <servlet-mapping>
        <servlet-name>DeleteAction</servlet-name>
        <url-pattern>/del.do</url-pattern>
      </servlet-mapping>
      <servlet-mapping>
        <servlet-name>UpdateAction</servlet-name>
        <url-pattern>/upd.do</url-pattern>
      </servlet-mapping>    
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
    </web-app>
  • 相关阅读:
    Sum Root to Leaf Numbers [LeetCode]
    Symmetric Tree [LeetCode]
    Combination Sum II [LeetCode]
    Maximal Rectangle [LeetCode]
    Trapping Rain Water [LeetCode]
    Combination Sum [LeetCode]
    05 如何“响铃”
    04 八进制
    03 关键字?保留字?预留字?
    020 函数之变量的作用域
  • 原文地址:https://www.cnblogs.com/hackxiyu/p/7073850.html
Copyright © 2020-2023  润新知