JSPjsp:useBean介紹

twilight0402發表於2017-04-17

版權宣告:本文為博主原創文章,轉載請註明出處。 https://blog.csdn.net/twilight_karl/article/details/70214763

建立JavaBean例項:

<jsp:useBean id=”name” class=”” scope=”page/session/request/application”/>

id為類的另一個名字,class指定具體的類,scope表示範圍,在scope的範圍內查詢是否有指定的屬性存在

賦值

  1. 指定引數和值
    <jsp:setProperty name="user" property="password" value="123" />
  2. 將指定引數的值賦值給JavaBean的屬性
    <jsp:setProperty name="user" param="pwd" property="password" />
  3. 通過自省機制自動匹配
    <jsp:setProperty name="user" property="*" />

使用jsp:useBean的目的是減少Script的使用
一個典型的javabean: JavaBean.java

package Bean;
import java.io.Serializable;
public class JavaBean implements Serializable {
    private String name ;
    private String password;


    public JavaBean(String name, String password) {
        super();
        this.name = name;
        this.password = password;
    }
    public JavaBean() {
        super();
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    } 
    public boolean isValid(){
        if(name.equals("tom") && password.equals("123")){
            return true;
        }
        return false;
    }
}

使用jsp:Bean標籤

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<jsp:useBean id="user" class="Bean.JavaBean" scope="page" />
<jsp:setProperty name="user" property="*" />

<html>
  <body>
  <font color=`red`>
    <jsp:getProperty property="name" name="user"/>
    </font>
  </body>
</html>

web容器翻譯後的Java程式碼

      Bean.JavaBean user = null;
      user = (Bean.JavaBean) _jspx_page_context.getAttribute("user", javax.servlet.jsp.PageContext.PAGE_SCOPE);
      if (user == null){
        user = new Bean.JavaBean();
        _jspx_page_context.setAttribute("user", user, javax.servlet.jsp.PageContext.PAGE_SCOPE);
      }

採用傳統方式的做法:

<%@ page language="java" import="java.util.*,Bean.JavaBean" pageEncoding="UTF-8"%>
<html>
  <body>
    <%
    JavaBean user = (JavaBean)request.getAttribute("user");
    if(user == null){
        user = new JavaBean();
    }
    user.setName(request.getParameter("name"));
    user.setPassword(request.getParameter("pwd"));
    if(user.isValid()){
        out.println("登入成功");
    }else{
        out.println("登入失敗");
    }
    %>
  </body>
</html