我正在尝试将java servlet中的属性传递给jsp,并在jsp文件中写入此属性。但是它不会重定向到jsp文件URL,但它会写入jsp文件的内容。这是我的相关代码:
Control.java:
@WebServlet("/Control")
public class Control extends HttpServlet{
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Key key = MacProvider.generateKey();
long time = System.currentTimeMillis();
try{
String jwt = Jwts.builder()
.signWith(SignatureAlgorithm.HS256, key)
.setSubject("username")
.setIssuedAt(new Date(time))
.setExpiration(new Date(time+6000000))
.claim("password","password")
.compact();
req.setAttribute("jwt", jwt);
req.getRequestDispatcher("/Home.jsp").forward(req,resp);
}catch (Exception e){
e.printStackTrace();
}
}
}
回到Home.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Welcome</title>
</head>
<body>
${jwt}
</body>
</html>
这里,浏览器停留在http://localhost:8080/Control
上,但它写入了Home.jsp文件的内容,该文件只是一个java Web令牌结果字符串。
2)我的第二个问题是当我尝试将此jwt结果字符串存储在浏览器本地存储中,然后将其写入jsp文件中以检查它是否存储在浏览器中。但它不会打印任何东西。为此,我刚刚更改了Home.jsp
文件,如下所示:
(我从here获取了两个代码段)
回到Home.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<script>
localStorage.setItem("jwt", ${jwt});
console.log(localStorage.getItem("jwt"));
var jjwt = localStorage.getItem("jwt");
document.write(jjwt);
</script>
</body>
</html>
另一次尝试:
<html>
<head>
<script>
function myFunction() {
localStorage.setItem("jwt", ${jwt});
console.log(localStorage.getItem("jwt"));
var jjwt = localStorage.getItem("jwt");
document.getElementById("myText").innerHTML = jjwt;
}
</script>
</head>
<body onload="myFunction()">
<span id="myText"></span>
</body>
</html>
我在哪里做错了?
答案 0 :(得分:0)
1)当您使用RequestDispatcher.forward(请求,响应)时,您的servlet仍然可以控制,但您的jsp页面将被加载,因此无需担心。
如果您希望浏览器URL显示JSP页面URL,请执行 URLConnection cnt = url.openConnection();
InputStream stream = cnt.getInputStream();
if ("gzip".equalsIgnoreCase(cnt.getHeaderField("Content-Encoding"))) {
stream = new GZIPInputStream(stream);
}
BufferedReader read = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
2)由于您使用的是JSP,请尝试访问下面的请求变量并将其打印
response.sendRedirect("URL TO LOAD");
我们需要将其设置为
<% String jwt = (String) request.getAttribute("jwt");%>