---
title: "useBean动作元素"
author: "cakin24"
date: "2017-10-04T08:37:14Z"
tags: []
categories: ["编程语言"]
slug: "usebean"
draft: false
lastmod: "2017-10-04T08:37:14Z"
id: 2395324
url: "https://cakin24.iteye.com/blog/2395324"
---

一 &lt;jsp:useBeans&gt;

作用：在jsp页面中实例化或者在指定范围内使用javabean：

&lt;jsp:useBean id="标示符" class="java类全名" scope="作用范围"&gt;

 

二 代码

1、Users.java

package com.po;

/*

 * 用户类

 * \*/

public class Users {

 

        private String username;//用户名

        private String password;//密码

        

        //保留此默认的构造方法

        public Users()

        {

                

        }

 

        public String getUsername() {

                return username;

        }

 

        public void setUsername(String username) {

                this.username = username;

        }

 

        public String getPassword() {

                return password;

        }

 

        public void setPassword(String password) {

                this.password = password;

        }

        

        

}

2、useBean.jsp

&lt;%@ page language="java" import="java.util.\*" contentType="text/html; charset=utf-8"%&gt;

&lt;%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%&gt;

 

&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt;

&lt;html&gt;

  &lt;head&gt;

    &lt;base href="&lt;%=basePath%&gt;"&gt;

   

    &lt;title&gt;My JSP 'index.jsp' starting page&lt;/title&gt;

        &lt;meta http-equiv="pragma" content="no-cache"&gt;

        &lt;meta http-equiv="cache-control" content="no-cache"&gt;

        &lt;meta http-equiv="expires" content="0"&gt;   

        &lt;meta http-equiv="keywords" content="keyword1,keyword2,keyword3"&gt;

        &lt;meta http-equiv="description" content="This is my page"&gt;

        &lt;!--

        &lt;link rel="stylesheet" type="text/css" href="styles.css"&gt;

        --&gt;

  &lt;/head&gt;

 

  &lt;body&gt;

    &lt;jsp:useBean id="myUsers" class="com.po.Users" scope="page"/&gt;

    &lt;h1&gt;使用useBean动作创建javabean的实例&lt;/h1&gt;

    &lt;hr&gt;

       用户名：&lt;%=myUsers.getUsername() %&gt;&lt;br&gt;

       密码：&lt;%=myUsers.getPassword() %&gt;&lt;br&gt;

  &lt;/body&gt;

&lt;/html&gt;

 

三 测试

 

![](http://dl2.iteye.com/upload/attachment/0127/2376/102bc8be-b622-336b-8c05-2c20fb24c7f7.png)