可以使用 request
传值:
在 Servlet
里的 doGet
或 doPost
使用 req.setAttribute(String name, Object o)
方法设置要传值的键值对
继续使用 req.getRequestDispatcher(String path)
得到 RequestDispatcher
对象
使用 requestDispatcher.forward(ServletRequest request, ServletResponse response)
调用指定 jsp
文件
在 jsp
里 使用 el 表达式
或 常量表达式
来获取传递的值
注意:访问时需要访问 Servlet
的路由才行,不能访问 jsp
文件,不然是没法传值的
具体代码如下:
Login.kt
package com.mrx.myservlet import com.mrx.myservlet.been.UserBeen import javax.servlet.annotation.WebServlet import javax.servlet.http.HttpServlet import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse @WebServlet(name = "登录接口", value = ["/login"]) class Login : HttpServlet() { override fun doGet(req: HttpServletRequest?, resp: HttpServletResponse?) { resp?.let { it.contentType = "text/html" it.status = 403 it.writer.println("FuckYOU!") } } override fun doPost(req: HttpServletRequest?, resp: HttpServletResponse?) { req?.characterEncoding = Charsets.UTF_8.toString() val userName = req?.getParameter("u").toString() val passwd = req?.getParameter("p").toString() val user = UserBeen(userName, passwd) println(userName) req?.let { it.setAttribute("result", user) it.getRequestDispatcher("/index.jsp").forward(it, resp) } } }
index.jsp
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%request.setCharacterEncoding("UTF-8");%> <!DOCTYPE html> <html> <head> <title>JSP - Hello World</title> <meta charset="UTF-8"> </head> <body> <form method="post" action="${pageContext.request.contextPath}/login"> <label> 用户名: <input name="u"/> </label> <label> 密码: <input name="p"/> </label> <input type="submit" value="登录"/> </form> <jsp:useBean id="result" scope="request" class="com.mrx.myservlet.been.UserBeen"/> <c:if test="${result!=null}"> <h1>用户名: ${result.userName} </h1> <h1>密码: ${result.passwd} </h1> </c:if> <br/> <a href="hello-servlet">Hello Servlet</a> </body> </html>
运行结果如下
访问地址是
http://localhost:8080/Gradle___com_mrx___MyServlet_1_0_SNAPSHOT_war/
点击 登录
按钮后的访问地址是
http://localhost:8080/Gradle___com_mrx___MyServlet_1_0_SNAPSHOT_war/login