tomcat学习笔记

◎使用tomcat bin下的start方法在tomcat出现错误时,不会留有任何调试信息,而且dos窗口关闭
使用tomcat bin下的run方法则在tomcat出现错误时,会留有任何调试信息,而且dos窗口仍打开
◎可以通过httpservletrequest的方法getServletContext获得servletcontext,然后通过servletcontext的getRequestDispatcher来获得RequestDispatch对象,通过该对象的forward使得当前的servlet将控制权转向其他jsp或者servlet
//forward的使用
具体代码:
public void doPost(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {

    // Get the username from the request
    String username = request.getParameter("username");
    // Get the password from the request
    String password = request.getParameter("password");

    // Add the  user to the request
    request.setAttribute("USER", username);
    request.setAttribute("PASSWORD", password);

    // Forward the request to the target named
    ServletContext context = getServletContext();

    System.out.println("Redirecting to " + target);
    RequestDispatcher dispatcher =
      context.getRequestDispatcher(target);
    dispatcher.forward(request, response);
  }
流程:httpservletrequest->servletContext->RequestDispatcher
◎一个taglib的开发实例
1。定义taglib
2。定义jsp tag
3。web.xml文件中定义taglib语句
4。定义tag文件
1.
package mypack;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.TagSupport;

public class HelloTag extends TagSupport
{
    public  HelloTag() {

    }

    // Method called when the closing hello tag is encountered
    public int doEndTag() throws JspException {

        try {

            // We use the pageContext to get a Writer
            // We then print the text string Hello
            pageContext.getOut().print("Hello");
        }
        catch (Exception e) {

            throw new JspTagException(e.getMessage());
        }
        // We want to return SKIP_BODY because this Tag does not support
        // a Tag Body
        return SKIP_BODY;
    }

    public void release() {

        // Call the parent's release to release any resources
        // used by the parent tag.
        // This is just good practice for when you start creating
        // hierarchies of tags.
        super.release();
     
    }
}

2.
<%@ taglib uri="/mytaglib" prefix="mm" %>
<html>
<head>
  <title>helloapp</title>
</head>
<body>
  <b><mm:hello/> : <%= request.getAttribute("USER") %></b>
</body>
</html>
3.
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app PUBLIC
  '-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN'
  'http://java.sun.com/j2ee/dtds/web-app_2_3.dtd'>

<web-app>

 <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>mypack.DispatcherServlet</servlet-class>
   </servlet>

   <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/dispatcher</url-pattern>
   </servlet-mapping>


 <taglib>
    <taglib-uri>/mytaglib</taglib-uri>
    <taglib-location>/WEB-INF/mytaglib.tld</taglib-location>
  </taglib>

</web-app>
4.
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
        PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
 "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

<!-- a tag library descriptor -->

<taglib>
  <tlibversion>1.0</tlibversion>
  <jspversion>1.1</jspversion>
  <shortname>mytaglib</shortname>
  <uri>/mytaglib</uri>

  <tag>
    <name>hello</name>
    <tagclass>mypack.HelloTag</tagclass>
    <bodycontent>empty</bodycontent>
    <info>Just Says Hello</info>
  </tag>


</taglib>


◎编译servlet需要在classpath中添加servlet-api.jar
jidi查找datasource的方法:
流程Context.lookup()->datasource.getConnection()->connection->preparestatement()
并且要根据一下步骤进行必要的配置:
1.配置server.xml
2.配置web.xml
->1.
<!-- configure DataSource. Add the following code into server.xml -->

<Context path="/bookstore" docBase="bookstore" debug="0"
reloadable="true" >


  <Resource name="jdbc/BookDB"
               auth="Container"
               type="javax.sql.DataSource" />

  <ResourceParams name="jdbc/BookDB">
    <parameter>
      <name>factory</name>
      <value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
    </parameter>

    <!-- Maximum number of dB connections in pool. Make sure you
         configure your mysqld max_connections large enough to handle
         all of your db connections. Set to 0 for no limit.
         -->
    <parameter>
      <name>maxActive</name>
      <value>100</value>
    </parameter>

    <!-- Maximum number of idle dB connections to retain in pool.
         Set to 0 for no limit.
         -->
    <parameter>
      <name>maxIdle</name>
      <value>30</value>
    </parameter>

    <!-- Maximum time to wait for a dB connection to become available
         in ms, in this example 10 seconds. An Exception is thrown if
         this timeout is exceeded.  Set to -1 to wait indefinitely.
        Maximum time to wait for a dB connection to become available
         in ms, in this example 10 seconds. An Exception is thrown if
         this timeout is exceeded.  Set to -1 to wait indefinitely.
         -->
    <parameter>
      <name>maxWait</name>
      <value>10000</value>
    </parameter>

    <!-- MySQL dB username and password for dB connections  -->
    <parameter>
     <name>username</name>
     <value>dbuser</value>
    </parameter>
    <parameter>
     <name>password</name>
     <value>1234</value>
    </parameter>

    <!-- Class name for mm.mysql JDBC driver -->
    <parameter>
       <name>driverClassName</name>
       <value>com.mysql.jdbc.Driver</value>
    </parameter>

    <!-- The JDBC connection url for connecting to your MySQL dB.
         The autoReconnect=true argument to the url makes sure that the
         mm.mysql JDBC Driver will automatically reconnect if mysqld closed the
         connection.  mysqld by default closes idle connections after 8 hours.
         -->
    <parameter>
      <name>url</name>
      <value>jdbc:mysql://localhost:3306/BookDB?autoReconnect=true</value>
    </parameter>
  </ResourceParams>

</Context>
->2.
  <!-- add the following code into <webapp> in web.xml -->


 <resource-ref>
       <description>DB Connection</description>
       <res-ref-name>jdbc/BookDB</res-ref-name>
       <res-type>javax.sql.DataSource</res-type>
       <res-auth>Container</res-auth>
   </resource-ref>

3.源文件实例:
<!--首先导入一些必要的packages-->
<%@ page import="java.io.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.sql.*"%>
<%@ page import="javax.sql.*"%>
<%@ page import="javax.naming.*"%>
<%@ page import="com.mysql.jdbc.Connection"%>
<!--设置中文输出-->
<%@ page contentType="text/html; charset=GB2312" %>
<html>
<head>
  <title>DbJsp1.jsp</title>
</head>
<body>
<%
//以try开始
try
{
java.sql.Connection con;
Statement stmt;
ResultSet rs;

//建立数据库连接
Context ctx = new InitialContext();
DataSource ds =(DataSource)ctx.lookup("java:comp/env/jdbc/BookDB");
con = ds.getConnection();
//创建一个JDBC声明
stmt = con.createStatement();
//增加新记录
stmt.executeUpdate("INSERT INTO books (id,name,title,price) VALUES ('999','Tom','Tomcat Bible',44.5)");
//查询记录
rs = stmt.executeQuery("SELECT id,name,title,price from books");
//输出查询结果
out.println("<table border=1 width=400>");
while (rs.next())
{
String col1 = rs.getString(1);
String col2 = rs.getString(2);
String col3 = rs.getString(3);
float col4 = rs.getFloat(4);

//convert character encoding
col1=new String(col1.getBytes("ISO-8859-1"),"GB2312");
col2=new String(col2.getBytes("ISO-8859-1"),"GB2312");
col3=new String(col3.getBytes("ISO-8859-1"),"GB2312");

//打印所显示的数据
out.println("<tr><td>"+col1+"</td><td>"+col2+"</td><td>"+col3+"</td><td>"+col4+"</td></tr>");
}
out.println("</table>");

//删除新增加的记录
stmt.executeUpdate("DELETE FROM books WHERE id='999'");

//关闭数据库连结
rs.close();
stmt.close();
con.close();
}

//捕获错误信息
catch (Exception e) {out.println(e.getMessage());}

%>
</body>
</html>



















































































































































----------------------------------
{
◎如何设置dns,进行虚拟主机的配置






























































































































 

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值