精品国产乱码久久久久久蜜臀,亚洲日本一区二区三区在线 ,日本一区二区精品视频http://www.aygfsteel.com/jhtchina/zh-cnWed, 09 Jul 2025 13:57:01 GMTWed, 09 Jul 2025 13:57:01 GMT60顯示數據庫中的商品信息(JSTL應用)http://www.aygfsteel.com/jhtchina/articles/382796.htmljhtchinajhtchinaWed, 11 Jul 2012 06:35:00 GMThttp://www.aygfsteel.com/jhtchina/articles/382796.htmlhttp://www.aygfsteel.com/jhtchina/comments/382796.htmlhttp://www.aygfsteel.com/jhtchina/articles/382796.html#Feedback0http://www.aygfsteel.com/jhtchina/comments/commentRss/382796.htmlhttp://www.aygfsteel.com/jhtchina/services/trackbacks/382796.html1 SQL腳本

CREATE TABLE `tb_goods1` (

 `id` int(11) NOT NULL AUTO_INCREMENT,

 `name` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,

 `price` float DEFAULT NULL,

 `unit` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,

 `manufacturer` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,

 PRIMARY KEY (`id`)

)

2 創建網站

3 新建Servlet 名稱是GoodsServlet 包名是com.jht.servlet

4 引用Tomcat, 附加jar包文件 <Build Path菜單>

mysql-connector-java-3.0.16-ga-bin :數據庫操作類

jstl-api-1.2 JSP標準標簽庫

jstl-impl-1.2 JSP標準標簽庫

5 創建實體類 GoodsForm 包名是  com.jht.model

代碼如下:

 

public class GoodsForm {

       private int id = 0; // 編號屬性

       private String name = ""; // 商品名稱屬性

       private float price = 0.0f; // 單價屬性

       private String unit = ""; // 單位屬性

       private String manufacturer = ""; // 廠商屬性

       public void setId(int id) {

              this.id = id;

       }

       public int getId() {

              return id;

       }

       public void setName(String name) {

              this.name = name;

       }

       public String getName() {

              return name;

       }

       public void setPrice(float price) {

              this.price = price;

       }

       public float getPrice() {

              return price;

       }

       public void setUnit(String unit) {

              this.unit = unit;

       }

       public String getUnit() {

              return unit;

       }

       public void setManufacturer(String manufacturer) {

              this.manufacturer = manufacturer;

       }

       public String getManufacturer() {

              return manufacturer;

       }

}

6 編寫數據庫連接與操作類

package com.jht.tools;

import java.io.InputStream;

import java.sql.*;

import java.util.Properties;

public class ConnDB {

    public Connection conn=null;

    public Statement stmt=null;

    public ResultSet rs=null;

    private static String propFileName="connDB.properties";

    private static Properties prop=new Properties();

    private static String dbClassName="com.mysql.jdbc.Driver";

    private static String dbUrl="jdbc:mysql://127.0.0.1:3306/db_Database07?user=root&password=111&characterEncoding=UTF-8";

    public ConnDB() { //定義構造方法

              try {                     //捕捉異常

                     //Properties文件讀取到InputStream對象中

                     InputStream in = getClass().getResourceAsStream(propFileName);

                     prop.load(in); // 通過輸入流對象加載Properties文件

                     dbClassName = prop.getProperty("DB_CLASS_NAME"); // 獲取數據庫驅動

                     dbUrl = prop.getProperty("DB_URL", dbUrl);             //獲取URL

              } catch (Exception e) {

                     e.printStackTrace(); // 輸出異常信息

              }

       }

    public static Connection getConnection() {

              Connection conn = null;

              try {                                                        //連接數據庫時可能發生異常因此需要捕捉該異常

                     Class.forName(dbClassName).newInstance();                   //裝載數據庫驅動

                     //建立與數據庫URL中定義的數據庫的連接

                     conn = DriverManager.getConnection(dbUrl);

              } catch (Exception ee) {

                     ee.printStackTrace();                                                             //輸出異常信息

              }

              if (conn == null) {

                     System.err

                                   .println("警告: DbConnectionManager.getConnection() 獲得數據庫鏈接失敗.\r\n\r\n鏈接類型:"

                                                 + dbClassName

                                                 + "\r\n鏈接位置:"

                                                 + dbUrl);        //在控制臺上輸出提示信息

              }

              return conn;                                                                   //返回數據庫連接對象

       }

   

    /*

        * 功能:執行查詢語句

        */

       public ResultSet executeQuery(String sql) {

              try { // 捕捉異常

                     conn = getConnection(); // 調用getConnection()方法構造Connection對象的一個實例conn

                     stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,

                                   ResultSet.CONCUR_READ_ONLY);

                     rs = stmt.executeQuery(sql);               //執行SQL語句,并返回一個ResultSet對象rs

              } catch (SQLException ex) {

                     System.err.println(ex.getMessage()); // 輸出異常信息

              }

              return rs; // 返回結果集對象

       }

 

       /*

        * 功能:關閉數據庫的連接

        */

       public void close() {

              try { // 捕捉異常

                     if (rs != null) { // ResultSet對象的實例rs不為空時

                            rs.close(); // 關閉ResultSet對象

                     }

                     if (stmt != null) { // Statement對象的實例stmt不為空時

                            stmt.close(); // 關閉Statement對象

                     }

                     if (conn != null) { // Connection對象的實例conn不為空時

                            conn.close(); // 關閉Connection對象

                     }

              } catch (Exception e) {

                     e.printStackTrace(System.err); // 輸出異常信息

              }

       }

}

7 配置文件connDB.properties 內容如下:

DB_CLASS_NAME=com.mysql.jdbc.Driver

DB_URL=jdbc:mysql://127.0.0.1:3306/c2cd?user=root&password=root&characterEncoding=UTF-8

8 web.xml 文件配置如下:

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.5"

    xmlns="http://java.sun.com/xml/ns/javaee"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

 <servlet>

    <servlet-name>GoodsServlet</servlet-name>

    <servlet-class>com.jht.servlet.GoodsServlet</servlet-class>

 </servlet>

 

 <servlet-mapping>

    <servlet-name>GoodsServlet</servlet-name>

    <url-pattern>/GoodsServlet</url-pattern>

 </servlet-mapping>

 <welcome-file-list>

    <welcome-file>index.jsp</welcome-file>

 </welcome-file-list>

</web-app>

9 index.jsp 代碼如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<body>

<c:redirect url="GoodsServlet">

    <c:param name="action" value="query" />

</c:redirect>

</body>

</html>

10 GoodsList.jsp 代碼如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<body>

 <table width="450" height="47" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#333333">

    <tr>

      <td height="30" colspan="5" bgcolor="#EFEFEF">·商品列表</td>

    </tr>

    <tr>

      <td width="36" height="27" align="center" bgcolor="#FFFFFF">編號</td>

      <td width="137" align="center" bgcolor="#FFFFFF">商品名稱</td>

      <td width="85" align="center" bgcolor="#FFFFFF">單價</td>

      <td width="38" align="center" bgcolor="#FFFFFF">單位</td>

      <td width="148" align="center" bgcolor="#FFFFFF">廠商</td>

    </tr>

    <c:forEach var="goods" items="${requestScope.goodsList}">  

    <tr>

      <td height="27" bgcolor="#FFFFFF">&nbsp;

      <c:out value="${goods.id}"/></td>

      <td bgcolor="#FFFFFF">&nbsp;

      <c:out value="${goods.name}"/></td>

      <td bgcolor="#FFFFFF">&nbsp;

      <c:out value="${goods.price}"/>(元)</td>

      <td bgcolor="#FFFFFF">&nbsp;

      <c:out value="${goods.unit}"/></td>

      <td bgcolor="#FFFFFF">&nbsp;

      <c:out value="${goods.manufacturer}"/></td>

    </tr>

    </c:forEach> 

 </table>

</body>

</html>

11 顯示數據庫中的商品信息

 



jhtchina 2012-07-11 14:35 發表評論
]]>
JSP EL表達式語句http://www.aygfsteel.com/jhtchina/articles/382620.htmljhtchinajhtchinaMon, 09 Jul 2012 08:45:00 GMThttp://www.aygfsteel.com/jhtchina/articles/382620.htmlhttp://www.aygfsteel.com/jhtchina/comments/382620.htmlhttp://www.aygfsteel.com/jhtchina/articles/382620.html#Feedback0http://www.aygfsteel.com/jhtchina/comments/commentRss/382620.htmlhttp://www.aygfsteel.com/jhtchina/services/trackbacks/382620.htmlEL:Expression Language的簡稱
作用:
簡化EL表達式語言,可以簡化在JSP開發中對對象的引用,增強程序的可讀性及可維護性。

t1.jsp頁面
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>應用EL表達式訪問JavaBean的屬性</title>
 <link rel="stylesheet" type="text/css" href="CSS/style.css">

  </head>
 
  <body><form name="form1" method="post" action="t2.jsp">
  <table width="403" height="230" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#666666">
    <tr>
      <td height="30" colspan="2" bgcolor="#EFEFEF">·用戶注冊</td>
    </tr>
    <tr>
      <td width="88" align="center" bgcolor="#FFFFFF">用 戶 名:</td>
      <td width="359" bgcolor="#FFFFFF"><input name="username" type="text" id="username"></td>
    </tr>
    <tr>
      <td align="center" bgcolor="#FFFFFF">密&nbsp;&nbsp;&nbsp;&nbsp;碼:</td>
      <td bgcolor="#FFFFFF"><input name="pwd" type="password" id="pwd"></td>
    </tr>
    <tr>
      <td align="center" bgcolor="#FFFFFF">確認密碼:</td>
      <td bgcolor="#FFFFFF"><input name="repwd" type="password" id="repwd"></td>
    </tr>
    <tr>
      <td align="center" bgcolor="#FFFFFF">性&nbsp;&nbsp;&nbsp;&nbsp;別:</td>
      <td bgcolor="#FFFFFF"><input name="sex" type="radio" class="noborder" value="男">
        男
        <input name="sex" type="radio" class="noborder" value="女">
        女</td>
    </tr>
    <tr>
      <td align="center" bgcolor="#FFFFFF">愛&nbsp;&nbsp;&nbsp;&nbsp;好:</td>
      <td bgcolor="#FFFFFF"><input name="affect" type="checkbox" class="noborder" id="affect" value="體育">
體育
<input name="affect" type="checkbox" class="noborder" id="affect" value="美術">
美術
<input name="affect" type="checkbox" class="noborder" id="affect" value="音樂">
音樂
 
<input name="affect" type="checkbox" class="noborder" id="affect" value="旅游">
旅游 </td>
    </tr>
    <tr>
      <td colspan="2" align="center" bgcolor="#FFFFFF">
        <input name="Submit" type="submit" class="btn_grey" value="提交">
&nbsp;
<input name="Submit2" type="reset" class="btn_grey" value="重置"></td>
    </tr>
  </table>
 </form>
  </body>
</html>
編寫保存信息的javaBean
package com.jht.wgh;

public class UserForm {
 private String username="";  //用戶名屬性
 private String pwd="";   //密碼屬性
 private String sex="";   //性別屬性
 private String[] affect=null; //愛好屬性
 public void setUsername(String username) {
  this.username = username;
 }
 public String getUsername() {
  return username;
 }
 public void setPwd(String pwd) {
  this.pwd = pwd;
 }
 public String getPwd() {
  return pwd;
 }
 public void setSex(String sex) {
  this.sex = sex;
 }
 public String getSex() {
  return sex;
 }
 public void setAffect(String[] affect) {
  this.affect = affect;
 }
 public String[] getAffect() {

  return affect;
 }
}
編寫t2.jsp,在該頁中,使用request內置對象的setCharacterEncoding()方法設置請求的編碼方式為UTF-8,然后使用<jsp:userBean>動作指令在頁面中創建一個javaBean實例,再使用<jsp:setProperty>動作指令設置javaBean實例的各種屬性值,最后使用EL表達式將JavaBean的各種屬性顯示到頁面中。
t2.jsp代碼如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%request.setCharacterEncoding("UTF-8");%>
<jsp:useBean id="userForm" class="com.jht.wgh.UserForm" scope="page"/>
<jsp:setProperty name="userForm" property="*"/>
<jsp:setProperty name="userForm" property="affect" value='<%=request.getParameterValues("affect")%>'/>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
  <head>
    <title>應用EL表達式訪問JavaBean的屬性</title>
 <link rel="stylesheet" type="text/css" href="CSS/style.css">

  </head>
 
  <body>
    <table width="403" height="218" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#666666">
    <tr>
      <td height="30" colspan="2" bgcolor="#EFEFEF">·顯示用戶填寫的注冊信息</td>
    </tr>
    <tr>
      <td width="88" align="center" bgcolor="#FFFFFF">用 戶 名:</td>
      <td width="359" bgcolor="#FFFFFF">&nbsp;${userForm.username}</td>
    </tr>
    <tr>
      <td align="center" bgcolor="#FFFFFF">密&nbsp;&nbsp;&nbsp;&nbsp;碼:</td>
      <td bgcolor="#FFFFFF">&nbsp;${userForm.pwd}</td>
    </tr>
    <tr>
      <td align="center" bgcolor="#FFFFFF">性&nbsp;&nbsp;&nbsp;&nbsp;別:</td>
      <td bgcolor="#FFFFFF">&nbsp;${userForm.sex}</td>
    </tr>
    <tr>
      <td align="center" bgcolor="#FFFFFF">愛&nbsp;&nbsp;&nbsp;&nbsp;好:</td>
      <td bgcolor="#FFFFFF">&nbsp;${userForm.affect[0]} ${userForm.affect[1]} ${userForm.affect[2]} ${userForm.affect[3]}</td>
    </tr>
    <tr>
      <td colspan="2" align="center" bgcolor="#FFFFFF">
        <input name="Button" type="button" class="btn_grey" value="返回" onClick="window.location.href='t1.jsp'">
&nbsp;</td>
    </tr>
  </table>
  </body>
</html>




jhtchina 2012-07-09 16:45 發表評論
]]>
jsp+servlet+javabean(錄入商品信息)http://www.aygfsteel.com/jhtchina/articles/382604.htmljhtchinajhtchinaMon, 09 Jul 2012 06:31:00 GMThttp://www.aygfsteel.com/jhtchina/articles/382604.htmlhttp://www.aygfsteel.com/jhtchina/comments/382604.htmlhttp://www.aygfsteel.com/jhtchina/articles/382604.html#Feedback0http://www.aygfsteel.com/jhtchina/comments/commentRss/382604.htmlhttp://www.aygfsteel.com/jhtchina/services/trackbacks/382604.html1 創建一個Dynamic Web Project.
2 創建一個新的servlet(包名是com.jht.controller,類名是:GoodsServlet)
3 修改Build Path(增加Tomcat引用和mysql-connector-java-5.1.6-bin引用)
4 增加web.xml
文件內容如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
 xmlns=" xmlns:xsi=" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
   <servlet>
    <servlet-name>GoodsServlet</servlet-name>
    <servlet-class>com.jht.controller.GoodsServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>GoodsServlet</servlet-name>
    <url-pattern>/GoodsServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

5 index.jsp文件內容如下:
<html>
 <head>
  <title>錄入商品信息</title>
  <style type="text/css">
   *{font-size: 12px;}
  </style>
  <script type="text/javascript">
   function save(form){
    if(form.name.value == ""){
     alert("請輸入商品名稱!");
     return false;
    }
    if(form.price.value == ""){
     alert("請輸入商品價格!");
     return false;
    }
    if(form.description.value == ""){
     alert("請輸入商品描述!");
     return false;
    }
   }
  </script>
 </head>
 <body>
  <form action="GoodsServlet" method="post" onsubmit="return save(this);">
   <table border="1" align="center" width="300">
    <tr>
     <td align="center" colspan="2">
      <br><h1>錄入商品信息</h1>
     </td>
    </tr>
    <tr>
     <td align="right">商品名稱:</td>
     <td><input type="text" name="name"></td>
    </tr>
    <tr>
     <td align="right">價 格:</td>
     <td><input type="text" name="price"></td>
    </tr>
    <tr>
     <td align="right">商品描述:</td>
     <td><textarea name="description" cols="30" rows="3"></textarea></td>
    </tr>
    <tr>
     <td align="center" colspan="2">
      <input type="submit" value="提 交">
      <input type="reset" value="重 置">
     </td>
    </tr>
   </table>
  </form>
 </body>
</html>

6 創建com.jht.model包名
7 在此包下面創建Goods 類和GoodsDao類
Goods內容如下:

package com.jht.model;

public class Goods {
 private String name; // 商品名稱
 private double price; // 單價
 private String description; // 描述信息
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public double getPrice() {
  return price;
 }
 public void setPrice(double price) {
  this.price = price;
 }
 public String getDescription() {
  return description;
 }
 public void setDescription(String description) {
  this.description = description;
 }
}


GoodsDao內如如下:


package com.jht.model;

/*
  * 商品數據庫操作類
 * @author
  */
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class GoodsDao {
 /**
  * 保存商品信息
  * @param goods
  */
 public void saveGoods(Goods goods){
  try {
   // 加載驅動
   Class.forName("com.mysql.jdbc.Driver");
   // 數據庫連接url
   String url = "jdbc:mysql://localhost:3306/c2cd?characterEncoding=UTF-8";
   // 獲取數據庫連接
   Connection conn = DriverManager.getConnection(url, "root", "root");
   // sql語句
   String sql = "insert into tb_goods(name,price,description) values(?,?,?)";
   // 創建PreparedStatement對象
   PreparedStatement ps = conn.prepareStatement(sql);
   // 對sql語句中參數賦值
   ps.setString(1, goods.getName());
   ps.setDouble(2, goods.getPrice());
   ps.setString(3, goods.getDescription());
   ps.executeUpdate();  // 更新操作
   ps.close();  // 關閉ps
   conn.close(); // 關閉conn
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}


8 修改GoodsServlet文件

(注意:在一個Servlet 對象中,最常用的方法是doGet()和doPost()方法,這2個方法分別用于處理HTTP的Get和Post請求。例如,<form>表單對象所聲明的method屬性為"post",提交到Servlet對象處理時,Servlet將調用doPost()方法進行處理。)
package com.jht.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jht.model.Goods;
import com.jht.model.GoodsDao;

/**
 * Servlet implementation class GoodsServlet
 */
@WebServlet("/GoodsServlet")
public class GoodsServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;

    /**
     * Default constructor.
     */
    public GoodsServlet() {
        // TODO Auto-generated constructor stub
    }

 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
 }

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
  // 設置response編碼
    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");
    // 設置request編碼
    request.setCharacterEncoding("UTF-8");
    // 獲取輸出流
    PrintWriter out = response.getWriter();
    // 獲取商品信息
    String name = request.getParameter("name");
    String price = request.getParameter("price");
    String description = request.getParameter("description");
    Goods goods = new Goods(); // 實例化商品對象
    // 對商品對象屬性賦值
    goods.setName(name);
    goods.setPrice(Double.valueOf(price));
    goods.setDescription(description);
    // 實例化GoodsDao
    GoodsDao goodsDao = new GoodsDao();
    goodsDao.saveGoods(goods); // 保存商品信息
    out.print("保存商品信息成功!");
    out.flush();
    out.close();
 }

}
9 數據表腳本如下:

/*
Navicat MySQL Data Transfer
Source Host     : localhost:3306
Source Database : c2cd
Target Host     : localhost:3306
Target Database : c2cd
Date: 2012-07-09 14:41:20
*/

SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for tb_goods
-- ----------------------------
DROP TABLE IF EXISTS `tb_goods`;
CREATE TABLE `tb_goods` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `price` double DEFAULT NULL,
  `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;






jhtchina 2012-07-09 14:31 發表評論
]]>
javaBean作用域代碼http://www.aygfsteel.com/jhtchina/articles/382395.htmljhtchinajhtchinaFri, 06 Jul 2012 08:18:00 GMThttp://www.aygfsteel.com/jhtchina/articles/382395.htmlhttp://www.aygfsteel.com/jhtchina/comments/382395.htmlhttp://www.aygfsteel.com/jhtchina/articles/382395.html#Feedback0http://www.aygfsteel.com/jhtchina/comments/commentRss/382395.htmlhttp://www.aygfsteel.com/jhtchina/services/trackbacks/382395.htmlcounter.java

package com.jht;

public class Counter {
    private int count=0;
    public int getCount()
    {
     return ++count;
    }
}

t5.jsp

<body>
<!-- 創建一個session范圍的counter對象 -->

<jsp:useBean id="counter_session" class="com.jht.Counter" scope="session"/>
<!-- 創建一個application范圍的counter對象 -->
<jsp:useBean id="counter_application" class="com.jht.Counter" scope="application" />
作用域
<br>
session:
<jsp:getProperty name="counter_session" property="count" />


<br>
application:
<jsp:getProperty name="counter_application" property="count"/>

</body>


javaBean的作用域有page,request,session,application




jhtchina 2012-07-06 16:18 發表評論
]]>
servlet (用戶注冊)http://www.aygfsteel.com/jhtchina/articles/382355.htmljhtchinajhtchinaFri, 06 Jul 2012 04:08:00 GMThttp://www.aygfsteel.com/jhtchina/articles/382355.htmlhttp://www.aygfsteel.com/jhtchina/comments/382355.htmlhttp://www.aygfsteel.com/jhtchina/articles/382355.html#Feedback0http://www.aygfsteel.com/jhtchina/comments/commentRss/382355.htmlhttp://www.aygfsteel.com/jhtchina/services/trackbacks/382355.html閱讀全文

jhtchina 2012-07-06 12:08 發表評論
]]>
servlet 2(過濾器Filter)http://www.aygfsteel.com/jhtchina/articles/382260.htmljhtchinajhtchinaThu, 05 Jul 2012 03:57:00 GMThttp://www.aygfsteel.com/jhtchina/articles/382260.htmlhttp://www.aygfsteel.com/jhtchina/comments/382260.htmlhttp://www.aygfsteel.com/jhtchina/articles/382260.html#Feedback0http://www.aygfsteel.com/jhtchina/comments/commentRss/382260.htmlhttp://www.aygfsteel.com/jhtchina/services/trackbacks/382260.htmlservlet 過濾器是客戶端與目標間的中間層組建,用于攔截客戶端的請求與相應信息。
首先先看如下例子:
(1) 創建網站
(2) 創建Servlet, Servlet 名稱是Servletnew ,包名是:com.jht
(3) 增加Apache Tomcat到Library
(4)WebContent/WEB-INF 增加web.xml文件,文件內容如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns=" xmlns:xsi=" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
  <!-- 聲明字符編碼過濾器 -->
 <filter>
  <filter-name>CharacterEncodingFilter</filter-name>
  <filter-class>com.jht.CharacterEncodingFilter</filter-class>
  <!-- 設置初始化參數 -->
  <init-param>
   <param-name>encoding</param-name>
   <param-value>GBK</param-value>
  </init-param>
 </filter>
 <!-- 映射字符編碼過濾器 -->
 <filter-mapping>
  <filter-name>CharacterEncodingFilter</filter-name>
  <!-- 與所有請求關聯 -->
  <url-pattern>/*</url-pattern>
  <!-- 設置過濾器對應的請求方式 -->
  <dispatcher>REQUEST</dispatcher>
  <dispatcher>FORWARD</dispatcher>
 </filter-mapping>
 <!-- Servlet配置 -->
 <servlet>
  <servlet-name>MyServletnew</servlet-name>
  <servlet-class>com.jht.MyServletnew</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>MyServletnew</servlet-name>
  <url-pattern>/MyServletnew</url-pattern>
 </servlet-mapping>
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
</web-app>

(5) 在WebConntent下面增加index.jsp
<%@ page language="java" contentType="text/html; charset=GBK"
    pageEncoding="GBK"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>Insert title here</title>
</head>
<body>
    <form action="MyServletnew" method="post">
  <p>
   請輸入你的中文名字:
   <input type="text" name="name">
   <input type="submit" value="提 交">
  </p>
 </form> 
</body>
</html>
(6) 創建類文件CharacterEncodingFilter,實現過濾。

package com.jht;


import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
 * 字符編碼過濾器
 * @author
 */
public class CharacterEncodingFilter implements Filter{
 // 字符編碼(初始化參數)
    protected String encoding = null;
    // FilterConfig對象
    protected FilterConfig filterConfig = null;
    // 初始化方法
    public void init(FilterConfig filterConfig) throws ServletException {
        // 對filterConfig賦值
     this.filterConfig = filterConfig;
     // 對初始化參數賦值
        this.encoding = filterConfig.getInitParameter("encoding");
    }
    // 過濾器處理方法
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 判斷字符編碼是否有效
     if (encoding != null) {
      // 設置request字符編碼
            request.setCharacterEncoding(encoding);
            // 設置response字符編碼
            response.setContentType("text/html; charset="+encoding);
        }
     // 傳遞給下一過濾器
        chain.doFilter(request, response);
    }
    // 銷毀方法
    public void destroy() {
     // 釋放資源
        this.encoding = null;
        this.filterConfig = null;
    }
}

(7) MyServletnew.java 文件內容如下:

package com.jht;


import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class MyServletnew
 */
@WebServlet("/MyServletnew")
public class MyServletnew extends HttpServlet {
 private static final long serialVersionUID = 1L;

    /**
     * Default constructor.
     */
    public MyServletnew() {
        // TODO Auto-generated constructor stub
    }

 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
 }

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
  PrintWriter out = response.getWriter();
  // 獲取表單參數
  String name = request.getParameter("name");
  if(name != null && !name.isEmpty()){
   System.out.println(name);
   out.print("你好 " + name);
   out.print(",<br>歡迎來到我的主頁。");
  }else{
   out.print("請輸入你的中文名字!");
  }
  out.print("<br><a href=index.jsp>返回</a>");
  out.flush();
  out.close();
 }

}





jhtchina 2012-07-05 11:57 發表評論
]]>
Servlet 學習1http://www.aygfsteel.com/jhtchina/articles/382200.htmljhtchinajhtchinaWed, 04 Jul 2012 08:32:00 GMThttp://www.aygfsteel.com/jhtchina/articles/382200.htmlhttp://www.aygfsteel.com/jhtchina/comments/382200.htmlhttp://www.aygfsteel.com/jhtchina/articles/382200.html#Feedback0http://www.aygfsteel.com/jhtchina/comments/commentRss/382200.htmlhttp://www.aygfsteel.com/jhtchina/services/trackbacks/382200.html1 創建test1 Dynamic Web Project站點

2 創建Servlet 設置java package(com.servlet)class name(MyServlet)

設置:

選擇Add Library
 

選擇tomcat




3 在WebContent/WEB-INF 下面創建web.xml文件。
  Web.xml文件內容如下:
  <?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns=" xmlns:xsi=" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 <servlet>
  <servlet-name>MyServlet</servlet-name>
  <servlet-class>com.servlet.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>MyServlet</servlet-name>
  <url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>MyServlet</welcome-file>
</welcome-file-list>
</web-app>
4 編寫MyServlet.java代碼
import java.io.PrintWriter;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub  
  response.setContentType("text/html");
  response.setCharacterEncoding("GBK");
  PrintWriter out=response.getWriter();
  out.println("<HTML>");
  out.println("<HEAD><TITLE>servlet sample</TITLE></HEAD>");
  out.println("<BODY>");
  out.println("servlet 實例 ");
  out.println(this.getClass());
  out.println("</BODY>");
  out.println("</HTML>");
  out.flush();
  out.close();  
 }
5 WebContent下面創建index.jsp
Body里面增加代碼<jsp:forward page="MyServlet"></jsp:forward>
6 運行結果如下:
servlet 實例 class com.servlet.MyServlet

備注:
MyServlet.java代碼修改
 response.setContentType("text/html");
  response.setCharacterEncoding("GBK");
  PrintWriter out = response.getWriter();
  out.print("<p>上下文路徑:" + request.getServletPath() + "</p>");
  out.print("<p>HTTP請求類型:" + request.getMethod() + "</p>");
  out.print("<p>請求參數:" + request.getQueryString() + "</p>");
  out.print("<p>請求URI:" + request.getRequestURI() + "</p>");
  out.print("<p>請求URL:" + request.getRequestURL().toString() + "</p>");
  out.print("<p>請求Servlet路徑:" + request.getServletPath() + "</p>");
  out.flush();
  out.close();
運行結果:

上下文路徑:/MyServlet
HTTP請求類型:GET
請求參數:null
請求URI:/test1/MyServlet
請求URL:
http://localhost:8080/test1/MyServlet
請求Servlet路徑:/MyServlet
注意:Web Deployment Assembly增加Add,對mysql.jar的引用




jhtchina 2012-07-04 16:32 發表評論
]]>
jsp 內置對象獲取異常信息http://www.aygfsteel.com/jhtchina/articles/382195.htmljhtchinajhtchinaWed, 04 Jul 2012 06:58:00 GMThttp://www.aygfsteel.com/jhtchina/articles/382195.htmlhttp://www.aygfsteel.com/jhtchina/comments/382195.htmlhttp://www.aygfsteel.com/jhtchina/articles/382195.html#Feedback0http://www.aygfsteel.com/jhtchina/comments/commentRss/382195.htmlhttp://www.aygfsteel.com/jhtchina/services/trackbacks/382195.htmlt10.jsp
<%@ page language="java" contentType="text/html; charset=gbk" errorPage="11.jsp"
    pageEncoding="gbk"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
<title>Insert title here</title>
</head>
<body>
<%
    int apple=Integer.parseInt("ghj");
    System.out.println("apple:"+apple);
%>
</body>
</html>
t11.jsp
<%@ page language="java" contentType="text/html; charset=gbk" isErrorPage="true"
    pageEncoding="gbk"%>
<%@ page import="java.util.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
<title>Insert title here</title>
</head>
<body>
    <%=exception.getMessage() %>
</body>
</html>


jhtchina 2012-07-04 14:58 發表評論
]]>
jsp 內置對象 applicationhttp://www.aygfsteel.com/jhtchina/articles/382193.htmljhtchinajhtchinaWed, 04 Jul 2012 06:39:00 GMThttp://www.aygfsteel.com/jhtchina/articles/382193.htmlhttp://www.aygfsteel.com/jhtchina/comments/382193.htmlhttp://www.aygfsteel.com/jhtchina/articles/382193.html#Feedback0http://www.aygfsteel.com/jhtchina/comments/commentRss/382193.htmlhttp://www.aygfsteel.com/jhtchina/services/trackbacks/382193.htmlApplication 提供了對應用程序環境屬性訪問的方法。

在WEB-INF目錄下面新建web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
 xmlns=" xmlns:xsi=" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
  <context-param>    <!-- 定義連接數據庫URL -->
  <param-name>url</param-name>
  <param-value>jdbc:mysql://localhost:3306/db_database15</param-value>
 </context-param>
 <context-param>   <!-- 定義連接數據庫用戶名 -->
  <param-name>name</param-name>
  <param-value>root</param-value>
 </context-param>
 <context-param>   <!-- 定義連接數據庫mim -->
  <param-name>password</param-name>
  <param-value>111</param-value>
 </context-param>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

t9.jsp代碼如下:

<%@ page language="java" contentType="text/html; charset=gbk"
    pageEncoding="gbk"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
<title>Insert title here</title>
<base href="<%=basePath%>">
</head>
<body>
<%
 
   String url = application.getInitParameter("url"); //獲取初始化參數,與web.xml文件中內容對應
   String name = application.getInitParameter("name");
   String password = application.getInitParameter("password");
   out.println("URL: "+url+"<br>");
   out.println("name: "+name+"<br>");
   out.println("password: "+password+"<br>");
%>
</body>
</html>





jhtchina 2012-07-04 14:39 發表評論
]]>
jsp 內置對象cookiehttp://www.aygfsteel.com/jhtchina/articles/382191.htmljhtchinajhtchinaWed, 04 Jul 2012 06:23:00 GMThttp://www.aygfsteel.com/jhtchina/articles/382191.htmlhttp://www.aygfsteel.com/jhtchina/comments/382191.htmlhttp://www.aygfsteel.com/jhtchina/articles/382191.html#Feedback0http://www.aygfsteel.com/jhtchina/comments/commentRss/382191.htmlhttp://www.aygfsteel.com/jhtchina/services/trackbacks/382191.htmlt7.jsp

<%@ page language="java" contentType="text/html; charset=GBK"
    pageEncoding="GBK"%>
<%@ page import="javax.servlet.http.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>Insert title here</title>
</head>
<body>
<%
  String welcome="第一次訪問";
  String[] info=new String[]{"","",""};
  Cookie[] cook=request.getCookies();
  if (cook!=null)
  {
   for(int i=0;i<cook.length;i++)
   {
    if (cook[i].getName().equals("myCookInfo"))
    {
     info=cook[i].getValue().split("#");
     welcome=",歡迎回來!";
    }
   }
  }
%>
<%=info[0]+welcome %>
<form action="t8.jsp" method="post">

 

<ul>
<li>
姓名:<input name="name" type="text" value="<%=info[0] %>" >

</li>
<li>
出生日期:<input name="birthday" type="text" value="<%=info[1] %>">


</li>
<li>
郵箱地址:
<input name="mail" type="text" value="<%=info[2] %>" >
</li>
<li>
<input type="submit" value="提交">
</li>
</ul>
</form>

</body>
</html>


t8.jsp
<%@ page language="java" contentType="text/html; charset=GBK"
    pageEncoding="GBK"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>Insert title here</title>
</head>
<body>
 <%
  String name =new String(request.getParameter("name").getBytes("ISO8859_1"),"GBK");
     String birthday = request.getParameter("birthday");
     String mail = request.getParameter("mail");
     Cookie myCook = new Cookie("myCookInfo",name+"#"+birthday+"#"+mail);
     myCook.setMaxAge(60*60*24*365);
     response.addCookie(myCook);
    %>
    表單提交成功
    <ul style="line-height: 24px">
     <li>姓名:<%= name %>
     <li>出生日期:<%= birthday %>
     <li>電子郵箱:<%= mail %>
     <li><a href="t7.jsp">返回</a>
    </ul>
</body>
</html>


jhtchina 2012-07-04 14:23 發表評論
]]>
主站蜘蛛池模板: 晋城| 中卫市| 河南省| 渭源县| 紫阳县| 乐业县| 岢岚县| 饶阳县| 诸城市| 阿合奇县| 泾川县| 侯马市| 团风县| 石阡县| 府谷县| 独山县| 黄龙县| 南木林县| 鄂托克前旗| 忻城县| 敦煌市| 甘孜县| 岐山县| 金昌市| 日照市| 榆社县| 青海省| 宜宾市| 崇义县| 霍州市| 白水县| 伊春市| 五指山市| 松江区| 新疆| 江都市| 柳江县| 博客| 吴桥县| 抚州市| 通城县|