JSP——useBean

在前面已介绍了include动作标志和forward跳转解决乱码的方法。在此介绍表单乱码问题,与前面的方法不同了。

//在表单处理页面写useBean。

留言板示例:有两个bean类,分别为:Word.java和myTools.java

在word.jsp页面代码:

<%@ page contentType="text/html;charset=gb2312"%>
<html>
 <body>
 <form action="doword.jsp">
 <table>
  <tr><th>留言者:</th><td><input type="text" name="author"/></tr>
  <tr><th>留言标题:</th><td><input type="text" name="title"/></td></tr>
  <tr><th>留言内容:</th><td><textarea rows="5" cols="30" name="content"></textarea></td></tr>
  <tr><td colspan="2"><input type="submit" value="提交"/></td></tr>
 </table>
 </form>
 </body>
</html>

doword.jsp代码:

<%@ page contentType="text/html;charset=gb2312" %>
<%@ page import="cn.myMindView.bean.*" %>
<jsp:useBean id="myword" class="cn.myMindView.bean.Word" scope="request">
<jsp:setProperty  name="myword" property="*"/>
</jsp:useBean>
<jsp:forward page="show.jsp"></jsp:forward>

show.jsp代码:

<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="cn.myMindView.bean.*" %>
<jsp:useBean id="myword" class="cn.myMindView.bean.Word" scope="request"/>
<html>
 <body>
 <table>
  <tr><th>留言者:</th><td><%=myTools.toChinese(myword.getAuthor()) %></tr>
  <tr><th>留言标题:</th><td><%=myTools.toChinese(myword.getTitle()) %></td></tr>
  <tr><th>留言内容:</th><td><textarea rows="5" cols="30" readonly>
  <%=myTools.toChinese(myword.getContent()) %></textarea></td></tr>
 </table> 
 </body>
</html>

总结:useBean的scope范围只有都为request时才能在show页面中取到表单中的值。

<jsp:useBean>标志被执行时首先会在scope指定的范围内查找指定的bean实例。默认值为page,若该实例已存在,则引用这个实例。在上面留言板的例子里show页面现在reques范围内寻找myword这个实例,发现有这个实例,于是就直接使用myword.getName()方法。若没有实例,则会用new方法重新创建一个。

原文地址:https://www.cnblogs.com/mymindview/p/3497474.html