首页 > 代码库 > java:JSP(JSPWeb.xml的配置,动态和静态导入JSP文件,重定项和请求转发,使用JSP实现数据库的增删改查实例)

java:JSP(JSPWeb.xml的配置,动态和静态导入JSP文件,重定项和请求转发,使用JSP实现数据库的增删改查实例)

1.JSP的配置:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP ‘register.jsp‘ starting page</title>
</head>

<body>
    <pre>
        JSP:java servlet page
            jsp也是一个servlet:要继承HttpServlet--->service方法
            jsp当被访问的时候,tomcat会自动把它编译成Java class,会生成一个遵循某个命名规则的clas和Java文件(以login.jsp为例,首先会把.转换为_,然后进行连接--->login_jsp.java/class,这里的命名规则并不遵循Java的驼峰命名规则)
            这个class继承了--->org.apache.jasper.runtime.HttpJspBase--->拥有_jspService
            org.apache.jasper.runtime.HttpJspBase继承了---->HttpServlet--->重写了service方法---->调用了这个class的_jspService方法
            也就是相当于tomcat把jsp文件生成Java类继承了httpservlet
            所以说jsp也就是一个servlet
            ---->必须要配置
            <servlet>
                <servlet-name></servlet-name>
                <servlet-class></servlet-class>
            </servlet>
            
            <servlet-mapping>
                <servlet-name></servlet-name>
                <url-pattern></url-pattern>
            </servlet-mapping>
            
            jsp在tomcat的conf文件下web.xml进行配置
             <servlet>
                <servlet-name>jsp</servlet-name>
                <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
                <init-param>
                    <param-name>fork</param-name>
                    <param-value>false</param-value>
                </init-param>
                <init-param>
                    <param-name>xpoweredBy</param-name>
                    <param-value>false</param-value>
                </init-param>
                <load-on-startup>3</load-on-startup>
            </servlet>
             <servlet-mapping>
                <servlet-name>jsp</servlet-name>
                <url-pattern>*.jsp</url-pattern>
                <url-pattern>*.jspx</url-pattern>
                </servlet-mapping>
               所以org.apache.jasper.servlet.JspServlet来处理以jsp为结尾的路径
               JspServlet-->就是一个servlet--->重写了service方法--->把jsp(warrper)文件转换为class文件
    </pre>
</body>
</html>

2.动态导入和静态导入JSP文件:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%-- errorPage只能保护运行时异常(404,405,401),不能保护检查时异常(500,600) --%>
<%@ page isErrorPage="true" %><%-- 标记本页面是否为错误页面,提供后来人观看代码 --%>
<%@ page errorPage="error.jsp" %>
<%-- <%@ page import="cn.zzsxt.lee.servlet.*" %> --%><%-- 导入servlet包下的所有Java文件 --%>
<%@ page import="cn.zzsxt.lee.servlet.Test" %><%-- 导入Test.java --%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<title>My JSP ‘login.jsp‘ starting page</title>

</head>

<body>
    
    <pre>
          jsp即可以写html代码,也可以写Java代码
          jsp第一个语法:
          <!-- 是把两个jsp文件合并成了一个jsp文件 -->
          <!-- 静态导入:首先会把两个jsp文件合成一个,然后再通过tomcat进行编译,所以只编译了一次,高耦合,所以效率也会提高 -->
          <%@ include file="top.jsp" %><!-- 无论定位到页面的某一个位置,都能进行导入jsp文件,说白了也就是无论放在任何位置,就把导入的jsp放在哪里 -->
              <%
                String name = "zhangsan";
                System.out.println(name);
                // String name2 = "lisi1";// 如果使用<%@ include file="top.jsp" %>导入,报两个变量名不能相同
                String name3;
                /* int x = 1/0; */
                //System.out.println(name3);
                // 运行时异常
                    // 提示错误信息
                    // 只有运行时异常,才会被errorpage保护
                // 检查时异常
                    // 直接强行中断正在运行的程序
                    Test test = new Test();
                    test.getName();
            %>
              <%=name%>
              <%=name2%>
              <%-- <%=x%> --%>
      </pre>
      
    <a href="register.jsp">我是跳转页面用的</a>
    <!-- 动态导入,会生成两个class文件,从而tomcat编译了两次 -->
    <jsp:include page="footer.jsp"></jsp:include>
</body>
</html>

 

3.重定向和请求转发:

 

请求转发:
  1.request.getRequestDispatcher("需要跳转的路径").forward(request, response);
  发送一次请求
  地址栏不发生改变
  request可以传递参数(能参数共享)
  请求转发并不能访问到外部资源(外部的地址)

 

重定向:
  2.response.sendRedirect("需要跳转的路径");
  发送两次请求
  地址栏发生改变
  response不能传递参数(不能参数共享),如果想使用response进行参数传递,就得手动加载,自力更生
  重定向可以访问外部资源

 


  请求转发
  当需要传递参数的时候
  访问内部资源的时候建议使用请求转发(服务器内部之间的调用)

  重定向
  访问外部资源
  比较隐私和保密的地址一般推荐使用重定向

 4.使用JSP实现数据库的增删改查实例:

 

   注册:

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<title>My JSP ‘register.jsp‘ starting page</title>


</head>

<body>


    <h1>注册页面</h1>
    <form action="deal_register.jsp" method="post">
        用户名:
        <input type="text" name="username" />
        <br /> 密码:
        <input type="password" name="pwd" /><br />
         重复密码:
         <input type="password" name="repwd" /><br />
          手机号:
          <input type="text" name="phone" /><br />
           爱好:
          <input type="checkbox" name="hobby" value="football" />足球
          <input type="checkbox" name="hobby" value="basketball" />篮球
           <input type="checkbox" name="hobby" value="Pingpong" />乒乓球
          <br />
            性别:
            <input type="radio" name="sex" value="male" /><input type="radio" name="sex" value="female" /><br />
            <input type="submit" value="提交" />
    </form>


</body>
</html>

 

  处理注册信息存入数据库:

<%@ page language="java" import="java.util.*, java.sql.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<title>My JSP ‘deal_register.jsp‘ starting page</title>


</head>

<body>

    <%
        // 第一步:获取input的值(也就是用户注册的信息)
        String username = request.getParameter("username");
        String password = request.getParameter("pwd");
        String phoneNumber = request.getParameter("phone");
        long phone = Long.parseLong(phoneNumber);
        // String hobby1 = request.getParameter("hobby");
        String[] hobby = request.getParameterValues("hobby");
        String[] sex = request.getParameterValues("sex");
        String hobbys= "";// "football,basketball,pingpong"
        //hobby.length为3
        for(int i = 0;i < hobby.length; i++) {
            /* if(hobby.length-1 > i) {
                hobbys +=hobby[i]+",";// 最后一位是,
            } else {
                hobbys +=hobby[i];
            } */
            
            hobbys +=hobby[i]+",";
        }
        hobbys = hobbys.substring(0,hobbys.length()-1);
        
        //String sex1 = request.getParameter("sex");// 如果是单选或者多选的话,使用request.getParameter()--->on,规定无论是单选还是多选或者下拉使用request.getParameterValues();
    
    
        // 第二步:插入数据,id使用UUID
            //1.导入ojdbc6.jar
            //2.加载驱动(反射)
            Class.forName("oracle.jdbc.driver.OracleDriver");
            //3.获取连接
            Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","scott");
            //4.获取预编译的statement(String sql)
            String sql = "insert into students (id, stu_name, stu_age, stu_pwd, stu_hobby, stu_sex, stu_phone) values(?,?,?,?,?,?,?)";
            PreparedStatement ps = conn.prepareStatement(sql);
            //5.设置参数ps.setxxxx
            ps.setString(1,UUID.randomUUID().toString());
            ps.setString(2, username);
            ps.setInt(3, 32);
            ps.setString(4, password);
            ps.setString(5, hobbys);
            ps.setString(6,sex[0]);
            ps.setLong(7, phone);
            //6.调用executeUpdate();--->返回值为受影响的行数
            int result = ps.executeUpdate();
            //7.判断接收的int类型数据,判断是否大于0(大于0成功,小于0失败)
            if(result > 0) {
                // 成功
            } else {
                // 失败
            }
    %>


</body>
</html>

  登录:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<title>My JSP ‘login.jsp‘ starting page</title>


</head>

<body>

    <form action="deal_login.jsp" method="post">
        用户名:
        <input type="text" name="username" />
        <br /> 密码:
        <input type="password" name="pwd" />
        <input type="submit" value="提交" />
    </form>


</body>
</html>

  处理登录,预跳转至主页处理的界面(查询数据库全部数据):

<%@ page language="java"
    import="java.util.*, java.sql.*, cn.zzsxt.lee.web.entity.*"
    pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<title>My JSP ‘deal_login.jsp‘ starting page</title>


</head>

<body>


    <%
        String username = request.getParameter("username");
        String password = request.getParameter("pwd");

        //1.加载驱动
        Class.forName("oracle.jdbc.driver.OracleDriver");
        //2.获取连接
        Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "scott");
        //3.获取预编译的statement
        String sql = "select * from teacher where name=? and password=?";
        PreparedStatement ps = conn.prepareStatement(sql);
        //4.设置参数
        ps.setString(1, username);
        ps.setString(2, password);
        //5.调用executeQuery();-->返回ResultSet
        ResultSet rs = ps.executeQuery();
        //6.遍历结果集
        Teacher teacher = new Teacher();
        while (rs.next()) {
            teacher.setId(rs.getInt("id"));
            teacher.setUsername(rs.getString("name"));
            teacher.setPassword(rs.getString("password"));
            teacher.setDescription(rs.getString("description"));
        }
        //7.判断是否查询出数据
        if (teacher.getUsername() != null && !"".equals(teacher.getUsername())) {// 把“”放在前面,防止空指针
            // 成功,跳转主页面的处理页面
        //    request.getRequestDispatcher("deal_index.jsp").forward(request, response);// 跳转页面
            request.getRequestDispatcher("frameset_index.jsp").forward(request, response);// 跳转页面
        } else {
            // 失败,跳转404
            //response.sendRedirect("404.jsp");
            request.getRequestDispatcher("404.jsp").forward(request, response);
        }
    %>



</body>
</html>

  主页处理界面,预跳转至主页:

<%@ page language="java"
    import="java.util.*, java.sql.*, cn.zzsxt.lee.web.entity.*"
    pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<title>My JSP ‘deal_index.jsp‘ starting page</title>


</head>

<body>


    <%
        //1.加载驱动
        Class.forName("oracle.jdbc.driver.OracleDriver");
        //2.获取连接
        Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "scott");
        //3.获取预编译的statement
        String sql = "select * from students";
        PreparedStatement ps = conn.prepareStatement(sql);
        //4.调用executeQuery();-->返回ResultSet
        ResultSet rs = ps.executeQuery();
        //5.遍历结果集
        // 定义一个泛型为Student的List集合
        List<Student> list = new ArrayList<Student>();
        while (rs.next()) {
            Student student = new Student();
            student.setId(rs.getString("id"));
            student.setStuName(rs.getString("stu_name"));
            student.setStuPassword(rs.getString("stu_pwd"));
            list.add(student);
        }
        //6.判断list的长度大于0
        if(list.size() > 0) {
            // 成功,跳转到主页面
            request.setAttribute("list", list);//--->Map.get("key");--->map.put("name",24);Map<String, Object>
            request.getRequestDispatcher("index.jsp").forward(request, response);
        } else {
            // 失败
        }
    %>



</body>
</html>

  跳转至主页,显示所有数据,及修改和删除的功能:

<%@ page language="java" import="java.util.*, cn.zzsxt.lee.web.entity.*"
    pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<title>My JSP ‘index.jsp‘ starting page</title>

<script type="text/javascript">

    function trueDelete(id) {
        if (confirm("您确定要删除数据么?")) {
            window.location.href = "deal_delete.jsp?id=" + id;
        }
    }
</script>

</head>

<body>


    <table border="1">
        <thead>
            <tr>
                <th>学生编号</th>
                <th>学生姓名</th>
                <th>学生密码</th>
                <th>操作</th>
            </tr>
        </thead>

        <tbody>

            <%
                List<Student> listStudent = (List<Student>) request.getAttribute("list");
                for (int i = 0; i < listStudent.size(); i++) {
                    listStudent.get(i).getId();// 获取student对象的id
            %>
            <%-- jsp的注释 --%>
            <tr>
                <!-- 一个tr代表了一行,说白了就是代表一个student对象 -->
                <td><%=listStudent.get(i).getId()%></td>
                <!-- <%--<%= %>--%>输出页面 -->
                <td><%=listStudent.get(i).getStuName()%></td>
                <td><%=listStudent.get(i).getStuPassword()%></td>
                <td><a href="javascript:void(0);"
                    onclick="trueDelete(‘<%=listStudent.get(i).getId()%>‘);">删除</a>
                    <a href="select_by_id.jsp?id=<%=listStudent.get(i).getId()%>">修改</a>    
                </td>
                <!-- 删除功能(主键id删除)需要传递一个参数,同样需要操作数据库,需要deal_delete.jsp进行处理 -->
            </tr>
            <%
                }
            %>
        </tbody>

    </table>




</body>
</html>

  删除功能,删除处理界面,预跳转至主页处理界面(查询删除后还剩的数据,即所有数据)

<%@ page language="java" import="java.util.*, java.sql.*"
    pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<title>My JSP ‘deal_delete.jsp‘ starting page</title>


</head>

<body>


    <%
        //所有通过路径传递的参数都要使用request.getParameter()
        String id = request.getParameter("id");
        //1.加载驱动
        Class.forName("oracle.jdbc.driver.OracleDriver");
        //2.获取连接
        Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "scott");
        //3.获取预编译的statement
        String sql = "delete from students where id=?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1, id);
        int result = ps.executeUpdate();
        if (result > 0) {
            //成功
            request.getRequestDispatcher("deal_index.jsp").forward(request, response);
        } else {
            // 失败
        }
    %>

</body>
</html>

  修改功能,首先跳转至查询某一行的界面,预跳转至修改界面

<%@ page language="java"
    import="java.util.*, java.sql.*, cn.zzsxt.lee.web.entity.*"
    pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<title>My JSP ‘select_by_id.jsp‘ starting page</title>


</head>

<body>

    <%
        String id = request.getParameter("id");
        // 进行查询(通过id)
        //1.加载驱动
        Class.forName("oracle.jdbc.driver.OracleDriver");
        //2.获取连接
        Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "scott");
        //3.获取预编译的statement
        String sql = "select * from students where id=?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1, id);
        //4.调用executeQuery();-->返回ResultSet
        ResultSet rs = ps.executeQuery();
        //5.遍历结果集
        Student stu = new Student();
        while (rs.next()) {
            stu.setId(rs.getString("id"));
            stu.setStuName(rs.getString("stu_name"));
            stu.setStuPassword(rs.getString("stu_pwd"));
        }
        if (stu.getId() != null) {
            request.setAttribute("stu", stu);
            request.getRequestDispatcher("update.jsp").forward(request, response);
        } else {
            // 跳转报错页面
        }
    %>




</body>
</html>

  修改界面,以form表单的形式显示让用户动态修改,预提交至修改处理界面

<%@ page language="java" import="java.util.*, cn.zzsxt.lee.web.entity.*"
    pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<title>My JSP ‘update.jsp‘ starting page</title>


</head>

<body>
    <%
        Student stu = (Student) request.getAttribute("stu");
    %>

    <form action="deal_update.jsp" method="post">
        学生编号:
        <input type="text" value="<%=stu.getId()%>" name="id" readonly="readonly" />
        <br /> 学生姓名:
        <input type="text" value="<%=stu.getStuName()%>" name="username" />
        <br /> 学生密码:
        <input type="text" value="<%=stu.getStuPassword()%>" name="pwd" />
        <br />
        <input type="submit" value="修改" />
    </form>



</body>
</html>

  修改界面,修改数据库中的数据,预跳转至主页处理界面(查询修改后的数据,即所有数据)

<%@ page language="java" import="java.util.*, java.sql.*"
    pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<title>My JSP ‘deal_update.jsp‘ starting page</title>


</head>


<body>


    <%
        String id = request.getParameter("id");
        String username = request.getParameter("username");
        String pwd = request.getParameter("pwd");

        //1.加载驱动
        Class.forName("oracle.jdbc.driver.OracleDriver");
        //2.获取连接
        Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "scott");
        //3.获取预编译的statement
        String sql = "update students set stu_name=?, stu_pwd=? where id=?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1, username);
        ps.setString(2, pwd);
        ps.setString(3, id);
        int result = ps.executeUpdate();
        if (result > 0) {
            response.sendRedirect("deal_index.jsp");
            return;
            //request.getRequestDispatcher("deal_index.jsp").forward(request, response);//forward标识了跳转页面的规则,携带着request和response一起跳转页面,所以请求转发才可以传递参数
            //System.out.println("我是转发之后的代码,我被执行了");
            // 如果使用两个response或者request的情况下,就会报错Cannot call sendRedirect() after the response has been committed
            // 但是重定向直接报500,中断程序,请求转发不会中断程序,可以继续运行
            //response.sendRedirect("404.jsp");
        } else {
            //跳转错误页面
            response.sendRedirect("404.jsp");
            return;
        }
    %>


</body>
</html>

 

java:JSP(JSPWeb.xml的配置,动态和静态导入JSP文件,重定项和请求转发,使用JSP实现数据库的增删改查实例)