javaweb之JSP+Servlet

javaweb之JSP+Servlet

使用java开发web项目时,可以在后端使用Servlet,前端使用JSP,下面就介绍一下这两者的配合使用。

  • Servlet

Servlet的概念其实很简单,本质是一个遵从Servlet开发出来的java类。运行在 Web 服务器或应用服务器,它是作为来自 Web 浏览器或其他 HTTP 客户端的请求和 HTTP 服务器上的数据库或应用程序之间的中间层。

Servlet 生命周期

图片来自https://www.runoob.com

  • JSP

JSP(全称Java Server Pages)是由 Sun Microsystems 公司倡导和许多公司参与共同创建的一种使软件开发者可以响应客户端请求,而动态生成 HTML、XML 或其他格式文档的Web网页的技术标准。JSP 技术是以 Java 语言作为脚本语言的,JSP 网页为整个服务器端的 Java 库单元提供了一个接口来服务于HTTP的应用程序。

特点:可以混杂Html和java代码!

其实JSP也是一种Servlet,JSP被编译后是Servlet类文件。而通常JSP更注重页面的显示,而Servlet更注重逻辑控制。

img

一个完整的网络请求:

  • 就像其他普通的网页一样,您的浏览器发送一个 HTTP 请求给服务器。
  • Web 服务器识别出这是一个对 JSP 网页的请求,并且将该请求传递给 JSP 引擎。通过使用 URL或者 .jsp 文件来完成。
  • JSP 引擎从磁盘中载入 JSP 文件,然后将它们转化为 Servlet。这种转化只是简单地将所有模板文本改用 println() 语句,并且将所有的 JSP 元素转化成 Java 代码。
  • JSP 引擎将 Servlet 编译成可执行类,并且将原始请求传递给 Servlet 引擎。
  • Web 服务器的某组件将会调用 Servlet 引擎,然后载入并执行 Servlet 类。在执行过程中,Servlet 产生 HTML 格式的输出并将其内嵌于 HTTP response 中上交给 Web 服务器。
  • Web 服务器以静态 HTML 网页的形式将 HTTP response 返回到您的浏览器中。
  • 最终,Web 浏览器处理 HTTP response 中动态产生的HTML网页,就好像在处理静态网页一样。

下面是一个实际项目中的应用:

一个Servlet:

//GetAllLesson
package intergration.controller.lesson;


import intergration.Service.LessonService;
import intergration.entity.Lesson;
import org.jdom.JDOMException;
import org.xml.sax.SAXException;

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 javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@WebServlet("/lesson/getAllLesson")  //访问Servlet的url
public class GetAllLesson extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //super.doGet(req, resp);
        LessonService lessonService = new LessonService();

        Map<String, Object> modelMap = new HashMap<String, Object>();
        List<Lesson> lessonList = null;
        try {
            lessonList = lessonService.getAllLesson();  //从后台得到数据
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (JDOMException e) {
            e.printStackTrace();
        }
        modelMap.put("lesson", lessonList);
        if(lessonList == null){
            modelMap.put("success", false);
        }else {
            modelMap.put("success", true);
        }

        req.setAttribute("lesson_list",lessonList);  //将数据传回前端
        req.getRequestDispatcher("getAllLesson.jsp").forward(req, resp); //重定向

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //super.doPost(req, resp);
        doGet(req, resp);
    }
}

对应的 getAllLesson.jsp

<%@ page import="java.util.List"%>
<%@ page import="intergration.entity.Lesson" %><%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2019/11/27
  Time: 17:17
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>getAllLesson</title>
    <link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/css/public.css" />
</head>
<body>

<div id = "left_table">
    <form action="getLessonById" method="post">
        <input type="text"  name="id" value="" placeholder="课程号" />
        <button type ="submit">查询</button>
    </form>
</div>
<div id = "table" >
    <div class="add">
        <form action="insertLesson" method="post">
            <input type="text"  name="id" value="" placeholder="ID" />
            <input type="text"  name="name" value="" placeholder="课程名" />
            <input type="text"  name="sex" value="" placeholder="教师" />
            <input type="text"  name="class" value="" placeholder="学时" />
            <select name = "database">
                <option value = "test1">test1</option>
                <option value = "test2">test2</option>
            </select>
            <button type ="submit">新增</button>
        </form>
    </div>

    <table cellpadding="0" cellspacing="0">
        <thead>
        <tr>
            <th>ID</th>
            <th>课程名</th>
            <th>教师</th>
            <th>学时</th>
        </tr>
        </thead>
        <%
            //获取数据
            List<Lesson> lesson_list = (List<Lesson>)request.getAttribute("lesson_list");
        %>

        <%
            for(Lesson lesson:lesson_list){
        %>
        <tbody>
            <tr align="center">
                <td> <%= lesson.getLessonId() %></td>
                <td> <%= lesson.getLessonName() %></td>
                <td> <%= lesson.getTeacherName() %></td>
                <td> <%= lesson.getHours() %></td>

                <td  width="20%">
                    <span class="delete" ><a href="deleteLessonById?id=<%= lesson.getLessonId()%>">删除</a> </span>
                    <span class="edit" onclick="dis( <%= lesson.getLessonId() %>,'<%=lesson.getLessonName() %>',<%= lesson.getTeacherName() %>, <%= lesson.getHours() %>);">编辑</span>

                </td>
            </tr>
        </tbody>
        <%
            }
        %>

    </table>
    <div id="mask">
        <div class="mask">
            <div class="title">
                编辑
                <span onclick = "nodis()">
                            X
                        </span>
            </div>
            <div class="content">
                <form action="updateLesson" method="post">
                    <input type="text"  name="id" id = "update_id"value="" placeholder="ID" />
                    <input type="text"  name="name" id = "update_name" value="" placeholder="课程名" />
                    <input type="text"  name="sex" id = "update_sex"value="" placeholder="教师" />
                    <input type="text"  name="class" id = "update_class"value="" placeholder="学时" />
                    <button type ="submit">更新</button>
                </form>
            </div>
        </div>
    </div>


</div>

</body>

<script>
    function dis(Id,Name,Sex,Class) {
        event.stopPropagation();
        document.getElementById("mask").style.display = "block";
        document.getElementById("update_id").setAttribute("placeholder",Id);
        document.getElementById("update_name").setAttribute("placeholder",Name);
        document.getElementById("update_sex").setAttribute("placeholder",Sex);
        document.getElementById("update_class").setAttribute("placeholder",Class);
        document.getElementById("update_id").setAttribute("value",Id);
        document.getElementById("update_name").setAttribute("value",Name);
        document.getElementById("update_sex").setAttribute("value",Sex);
        document.getElementById("update_class").setAttribute("value",Class);
    }
    function nodis() {
        event.stopPropagation();
        document.getElementById("mask").style.display = "none";
    }
</script>

</html>

猜你喜欢

转载自www.cnblogs.com/lyc1226/p/12142640.html