如何使用ApacheTomcatServlets导航到另一个html文件并发送jinja变量?

gkl3eglg  于 2021-10-10  发布在  Java
关注(0)|答案(1)|浏览(327)

使用flask python呈现另一个模板并在get请求时发送jinja变量,您只需执行以下操作:

@app.route("/login", methods=["GET", "POST"])
def login():
    # User reached route via POST (as by submitting a form via POST)
    if request.method == "POST":
        # Ensure username was submitted
        username = request.form.get("username"):
        password = request.form.get("password"):
        # Redirect user to home page
        return render_template("home.html", username=username)

    # User reached route via GET
    else:
        return render_template("login.html")

使用tomcat servlet在java上的等价物是什么?

neekobn8

neekobn81#

使用servlet需要两部分:配置文件(web.xml)和servlet代码。
将配置设置到web.xml中:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Servlet Example</display-name>
  <welcome-file-list>
    <!-- you will want to take a look at jsp as well --> 
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>

  <servlet>
    <servlet-name>Login Servlet</servlet-name>
    <!-- dont forget to put the canonical name, including the package name -->
    <servlet-class>com.example.LoginServlet</servlet-class>
  </servlet>
</web-app>

然后编写servlet代码:

package com.example;
public class LoginServlet extends HttpServlet {

// GET
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
    response.sendRedirect("index.jsp");
}

// POST
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
    String username = request.getParameter("username");
    String password = request.getParameter("password");

    // method credentialsOk validate the user/password
    if(credentialsOk(username, password)){
        response.sendRedirect("home.jsp");
    }else{
        response.sendRedirect("login.jsp");
    }
 }

}
请看这里的servlet介绍:https://www.baeldung.com/intro-to-servlets

相关问题