【原生JavaWeb】网页前端页面如何调用后端Java程序

一、分层结构

【原生JavaWeb】网页前端页面如何调用后端Java程序_第1张图片

分层思想(解耦:高内聚低耦合)
    controller层
        接受请求
        (调用service层,返回结果)
        响应结果
    service层
        业务逻辑
    dao
        mapper.xml mybatis与数据库的相关操作
    pojo
        JavaBean实体

二、网页前端页面如何调用后端Java程序?

前端页面发送请求的方法

action指定发送请求到的servlet类路径
method可指定响应的方法,默认为get方法

<form action="/hello" method="post">
	<button>按下发送请求button>
form>

使用href也可以请求servlet类

href = "/hello"

网页前端通过向Java程序的Servlet类,发送请求,来调用操作。有两种方法

(一)在web.xml文件中定义servlet类的请求路径,例如下:

    <servlet>
        <servlet-name>HelloServletservlet-name>
        <servlet-class>servlet.HelloServletservlet-class>
    servlet>
    <servlet-mapping>
        <servlet-name>HelloServletservlet-name>
        <url-pattern>/hellourl-pattern>
    servlet-mapping>

(二)在Servlet类处,声明路径,例如下:

@WebServlet(“/hello”)

package servlet;

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 java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("");
        out.println("");
        out.println("Hello World!");
        out.println("");
        out.println("");
        out.println("

Hello Servlet Get!

"
); out.println(""); out.println(""); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(""); out.println(""); out.println("Hello World!"); out.println(""); out.println(""); out.println("

Hello Servlet Post!

"
); out.println(""); out.println(""); } }

你可能感兴趣的:(Java,web,后端,java,前端)