Java Servlet 开发常用代码、模板、问题
生活随笔
收集整理的這篇文章主要介紹了
Java Servlet 开发常用代码、模板、问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一 空Servlet類模板
import java.io.IOException;mport java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletDemo1 extends HttpServlet {
? ? public void doGet(HttpServletRequest request, HttpServletResponse response)
? ? ? ? ? ? throws ServletException, IOException {
? ? }
? ? public void doPost(HttpServletRequest request, HttpServletResponse response)
? ? ? ? ? ? throws ServletException, IOException {
? ? }
}
二 web.xml配置
? ?<servlet>? ? ?<servlet-name>ServletDemo1</servlet-name>
? ? ?<servlet-class>xxx.yyy.zzz.ServletDemo1</servlet-class>
? ?</servlet>
?
? ?<servlet-mapping>
? ? ?<servlet-name>ServletDemo1</servlet-name>
? ? ?<url-pattern>/servlet/ServletDemo1</url-pattern>
? ?</servlet-mapping>
? ? <servlet-mapping>
? ? ?<servlet-name>ServletDemo1</servlet-name>
? ? ?<url-pattern>/*</url-pattern>
? ?</servlet-mapping>
/abc/*?
/*?
/abc?
*.do?
? ? <servlet>
? ? ? ? <servlet-name>invoker</servlet-name>
? ? ? ? <servlet-class>
? ? ? ? ? ? org.apache.catalina.servlets.InvokerServlet
? ? ? ? </servlet-class>
? ? ? ? <load-on-startup>1</load-on-startup>
? ? </servlet>
如果某個Servlet的映射路徑僅僅為一個正斜杠(/),那么這個Servlet就成為當前Web應用程序的缺省Servlet。?
凡是在web.xml文件中找不到匹配的<servlet-mapping>元素的URL,它們的訪問請求都將交給缺省Servlet處理,
? <servlet>
? ? ?<servlet-name>ServletDemo2</servlet-name>
? ? ?<servlet-class>xxx.yyy.zzz.ServletDemo2</servlet-class>
? ? ?<load-on-startup>1</load-on-startup>
? ?</servlet>
? ?
? ?<!-- 將ServletDemo2配置成缺省Servlet -->
? ?<servlet-mapping>
? ? ?<servlet-name>ServletDemo2</servlet-name>
? ? ?<url-pattern>/</url-pattern>
? ?</servlet-mapping>
在<tomcat的安裝目錄>\conf\web.xml文件中,注冊了一個名稱為org.apache.catalina.servlets.DefaultServlet的Servlet,并將這個Servlet設置為了缺省Servlet。
三 Servlet的線程安全問題
當多個客戶端并發訪問同一個Servlet時,web服務器會為每一個客戶端的訪問請求創建一個線程,并在這個線程上調用Servlet的service方法,因此service方法內如果訪問了同一個資源的話,就有可能引發線程安全問題。不存在線程安全問題的代碼:
public class ServletDemo3 extends HttpServlet {
?
? ? ?
? ? ?public void doGet(HttpServletRequest request, HttpServletResponse response)
? ? ? ? ? ? ?throws ServletException, IOException {
? ? ? ? ?
? ? ? ? ?/**
? ? ? ? ? * i變量被多個線程并發訪問,但是沒有線程安全問題,因為i是doGet方法里面的局部變量,
? ? ? ? ? * 當有多個線程并發訪問doGet方法時,每一個線程里面都有自己的i變量,
? ? ? ? ? * 各個線程操作的都是自己的i變量,所以不存在線程安全問題
? ? ? ? ? * 多線程并發訪問某一個方法的時候,如果在方法內部定義了一些資源(變量,集合等)
? ? ? ? ? * 那么每一個線程都有這些東西,所以就不存在線程安全問題了
? ? ? ? ? */
? ? ? ? ?int i=1;
? ? ? ? ?i++;
? ? ? ? ?response.getWriter().write(i);
? ? ?}
?
? ? ?public void doPost(HttpServletRequest request, HttpServletResponse response)
? ? ? ? ? ? ?throws ServletException, IOException {
? ? ? ? ?doGet(request, response);
? ? ?}
?
?}
存在線程安全問題的代碼:
?public class ServletDemo3 extends HttpServlet {
?
? ? ?int i=1;
? ? ?public void doGet(HttpServletRequest request, HttpServletResponse response)
? ? ? ? ? ? ?throws ServletException, IOException {
? ? ? ??
? ? ? ? ?i++;
? ? ? ? ?try {
? ? ? ? ? ? ?Thread.sleep(1000*4);
? ? ? ? ?} catch (InterruptedException e) {
? ? ? ? ? ? ?e.printStackTrace();
? ? ? ? ?}
? ? ? ? ?response.getWriter().write(i+"");
? ? ?}
?
? ? ?public void doPost(HttpServletRequest request, HttpServletResponse response)
? ? ? ? ? ? ?throws ServletException, IOException {
? ? ? ? ?doGet(request, response);
? ? ?}
?
?}
把i定義成全局變量,當多個線程并發訪問變量i時,就會存在線程安全問題了;同時開啟兩個瀏覽器模擬并發訪問同一個Servlet,本來正常來說,第一個瀏覽器應該看到2,而第二個瀏覽器應該看到3的,結果兩個瀏覽器都看到了3。
? ? 如何解決?
public class ServletDemo3 extends HttpServlet {
?
? ? ?int i=1;
? ? ?public void doGet(HttpServletRequest request, HttpServletResponse response)
? ? ? ? ? ? ?throws ServletException, IOException {
? ? ? ? ?/**
? ? ? ? ? * 加了synchronized后,并發訪問i時就不存在線程安全問題了,
? ? ? ? ? * 假如現在有一個線程訪問Servlet對象,那么它就先拿到了Servlet對象的那把鎖
? ? ? ? ? * 等到它執行完之后才會把鎖還給Servlet對象,由于是它先拿到了Servlet對象的那把鎖,
? ? ? ? ? * 所以當有別的線程來訪問這個Servlet對象時,由于鎖已經被之前的線程拿走了,后面的線程只能排隊等候了
? ? ? ? ? *?
? ? ? ? ? */
? ? ? ? ?synchronized (this) {//在java中,每一個對象都有一把鎖,這里的this指的就是Servlet對象
? ? ? ? ? ? ?i++;
? ? ? ? ? ? ?try {
? ? ? ? ? ? ? ? ?Thread.sleep(1000*4);
? ? ? ? ? ? ?} catch (InterruptedException e) {
? ? ? ? ? ? ? ? ?e.printStackTrace();
? ? ? ? ? ? ?}
? ? ? ? ? ? ?response.getWriter().write(i+"");
? ? ? ? ?}
? ? ? ? ?
? ? ?}
?
? ? ?public void doPost(HttpServletRequest request, HttpServletResponse response)
? ? ? ? ? ? ?throws ServletException, IOException {
? ? ? ? ?doGet(request, response);
? ? ?}
?
?}
現在這種做法是給Servlet對象加了一把鎖,保證任何時候都只有一個線程在訪問該Servlet對象里面的資源,這樣就不存在線程安全問題了
? ? 這種做法雖然解決了線程安全問題,但是編寫Servlet卻不能用這種方式處理線程安全問題,假如有9999個人同時訪問這個Servlet,那么這9999個人必須按先后順序排隊輪流訪問。
針對Servlet的線程安全問題,Sun公司提供有解決方案的:讓Servlet去實現一個SingleThreadModel接口,如果某個Servlet實現了SingleThreadModel接口,那么Servlet引擎將以單線程模式來調用其service方法。
查看Sevlet的API可以看到,SingleThreadModel接口中沒有定義任何方法和常量,在Java中,把沒有定義任何方法和常量的接口稱之為標記接口,經常看到的一個最典型的標記接口就是"Serializable",這個接口也是沒有定義任何方法和常量的,標記接口在Java中有什么用呢?主要作用就是給某個對象打上一個標志,告訴JVM,這個對象可以做什么,比如實現了"Serializable"接口的類的對象就可以被序列化,還有一個"Cloneable"接口,這個也是一個標記接口,在默認情況下,Java中的對象是不允許被克隆的,就像現實生活中的人一樣,不允許克隆,但是只要實現了"Cloneable"接口,那么對象就可以被克隆了。
讓Servlet實現了SingleThreadModel接口,只要在Servlet類的定義中增加實現SingleThreadModel接口的聲明即可。 ?
對于實現了SingleThreadModel接口的Servlet,Servlet引擎仍然支持對該Servlet的多線程并發訪問,其采用的方式是產生多個Servlet實例對象,并發的每個線程分別調用一個獨立的Servlet實例對象。
實現SingleThreadModel接口并不能真正解決Servlet的線程安全問題,因為Servlet引擎會創建多個Servlet實例對象,而真正意義上解決多線程安全問題是指一個Servlet實例對象被多個線程同時調用的問題。事實上,在Servlet API 2.4中,已經將SingleThreadModel標記為Deprecated(過時的)。 ?
四 常用功能代碼
1 hello world
? public void init() throws ServletException
? {
? ? ? message = "Hello World";
? }
? public void doGet(HttpServletRequest request,
? ? ? ? ? ? ? ? ? ? HttpServletResponse response)
? ? ? ? ? ? throws ServletException, IOException
? {
? ? ? response.setContentType("text/html");
? ? ? PrintWriter out = response.getWriter();
? ? ? out.println("<h1>" + message + "</h1>");
? }
2 在客戶端輸出一個html文檔
? ? ? ? response.setContentType("text/html");? ? ? ? PrintWriter out = response.getWriter();
? ? ? ? out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
? ? ? ? out.println("<HTML>");
? ? ? ? out.println(" ?<HEAD><TITLE>A Servlet</TITLE></HEAD>");
? ? ? ? out.println(" ?<BODY>");
? ? ? ? out.print(" ? ?This is ");
? ? ? ? out.print(this.getClass());
? ? ? ? out.println(", using the GET method");
? ? ? ? out.println(" ?</BODY>");
? ? ? ? out.println("</HTML>");
? ? ? ? out.flush();
? ? ? ? out.close();
3 處理用戶登陸的servlet實現方法
Login.java
package com.bai;
?
import javax.servlet.http.*;?
import java.io.*;
?
public class Login extends HttpServlet{
? ? ?public void doGet(HttpServletRequest req,HttpServletResponse res){
? ? ? ? ?try{req.setCharacterEncoding("gb2312");
? ? ? ? ?res.setContentType("text/html;charset=gb2312");
? ? ? ? ? ? ?PrintWriter pw=res.getWriter();
? ? ? ? ? ? ?pw.println("<html>");
? ? ? ? ? ? ?pw.println("<body>");
? ? ? ? ? ? ?pw.println("<h1>登陸界面</h1>");
? ? ? ? ? ? ?pw.println("<form action=logincl method=post>");
? ? ? ? ? ? ?pw.println("用戶名:<input type=text name=username><br>");
? ? ? ? ? ? ?pw.println("密碼:<input type=password name=passwd><br>");
? ? ? ? ? ? ?pw.println("<input type=submit value=login><br>");
? ? ? ? ? ? ?pw.println("</form>");
? ? ? ? ? ? ?pw.println("</body>");
? ? ? ? ? ? ?pw.println("</html>");
? ? ? ? ?}
? ? ? ? ?catch(Exception e){
? ? ? ? ? ? ?e.printStackTrace();
? ? ? ? ?}
? ? ?}
? ? ?
? ? public void doPost(HttpServletRequest req,HttpServletResponse res){
? ? ? ? ?this.doGet(req,res);
? ? ?}
?}
?
LoginCl.java
package com.bai;
?
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
?
public class LoginCl extends HttpServlet{
? ? ?public void doGet(HttpServletRequest req,HttpServletResponse res){
? ? ? ? ?
? ? ? ? ?Connection conn=null;
? ? ? ? ?Statement stmt=null;
? ? ? ? ?ResultSet rs=null;
? ? ? ? ?String sql = "select username,passwd from users where username = ? and passwd = ?";
? ? ? ? ?try{//req.setCharacterEncoding("gb2312");
? ? ? ? ? ? ?String user=req.getParameter("username");
? ? ? ? ? ? ?String password=req.getParameter("passwd");
? ? ? ? ? ? ?
? ? ? ? ? ? Class.forName("com.mysql.jdbc.Driver");
? ? ? ? ? ? ?conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/sqdb","root","root");
?// ? ? ? ? ? ?stmt=conn.createStatement();
? ? ? ? ? ? ?PreparedStatement pstmt = conn.prepareStatement(sql);
? ? ? ? ? ? ?pstmt.setString(1, user);
? ? ? ? ? ? ?pstmt.setString(2, password);
? ? ? ? ? ? ?rs = pstmt.executeQuery();
?// ? ? ? ? ? ?rs=stmt.executeQuery("select top 1 * from users where username='"+user
?// ? ? ? ? ? ? ? ?+"' and passwd='"+password+"'");
? ? ? ? ? ? ?if(rs.next())
? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ?HttpSession hs=req.getSession(true);
? ? ? ? ? ? ? ? ?hs.setMaxInactiveInterval(60);
? ? ? ? ? ? ? ? ?hs.setAttribute("name",user);
? ? ? ? ? ? ? ? ?res.sendRedirect("welcome?&uname="+user+"&upass="+password);
? ? ? ? ? ? ?}
? ? ? ? ? ? ?else{
? ? ? ? ? ? ? ? ?res.sendRedirect("login"); //url
? ? ? ? ? ? ?}
? ? ? ? ? ? ?
? ? ? ? }
? ? ? ? ?catch(Exception e){
? ? ? ? ? ? ?e.printStackTrace();
? ? ? ? ?}finally{
? ? ? ? ? ? ?try{
? ? ? ? ? ? ? ? ?if(rs!=null){
? ? ? ? ? ? ? ? ?rs.close();
? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ?if(stmt!=null){
? ? ? ? ? ? ? ? ? ? ?stmt.close();
? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ?if(conn!=null){
? ? ? ? ? ? ? ? ? ? ?conn.close();
? ? ? ? ? ? ? ? ?} ? ?
? ? ? ? ? ? }catch(Exception e){
? ? ? ? ? ? ? ? ?e.printStackTrace();
? ? ? ? ? ? ?} ? ? ? ?
? ? ? ? }
? ? ?}
? ? ?
? ? public void doPost(HttpServletRequest req,HttpServletResponse res){
? ? ? ? ?this.doGet(req,res);
? ? ?}
?}
?
注:
上面這個處理用戶名密碼帶有明顯注入漏洞,可以根據用戶名從數據庫取密碼,用取出的密碼和用戶輸入的密碼比較
sql=select passwd from users where username = ? ?limit 1
if(rs.next())
?{
? ? ?String passwd=rs.getString(1);
? ? ?if(passwd.equals(password))
? ? ? ? ? ? ?//密碼正確
? ? ?else //密碼錯誤
?}
Welcome.java
package com.bai;
?
import javax.servlet.http.*;
import java.io.*;
?
public class Welcome extends HttpServlet{
? ? ?public void doGet(HttpServletRequest req,HttpServletResponse res){
? ? ? ? ?
? ? ? ? HttpSession hs=req.getSession();
? ? ? ? ?String val=(String)hs.getAttribute("pass");
? ? ? ? ?
? ? ? ? if(val==null){
? ? ? ? ? ? ?try{
? ? ? ? ? ? ? ? ?System.out.print(1);
? ? ? ? ? ? ? ? ?res.sendRedirect("login");
? ? ? ? ? ? ?}catch(Exception e){
? ? ? ? ? ? ? ? ?e.printStackTrace();
? ? ? ? ? ? ?}
? ? ? ? ? ? ?
? ? ? ? } ? ? ? ?
? ? ? ? ? ??
? ? ? ? String u=req.getParameter("uname");
? ? ? ? ?String p=req.getParameter("upass");
? ? ? ? ?
? ? ? ? try{//req.setCharacterEncoding("gb2312");
? ? ? ? ? ? ?PrintWriter pw=res.getWriter();
? ? ? ? ? ? ?pw.println("welcome! "+u+"&pass="+p);
? ? ? ? ?}
? ? ? ? ?catch(Exception e){
? ? ? ? ? ? ?e.printStackTrace();
? ? ? ? ?}
? ? ?}
? ? ?
? ? public void doPost(HttpServletRequest req,HttpServletResponse res){
? ? ? ? ?this.doGet(req,res);
? ? ?}
?}
4 servlet中session
在servlet中,session是封裝在javax.servlet.http.HttpSession這個接口中的,這個接口是構建在cookie或者URL重寫的基礎上,要得到一個HttpSession的實例,就可以通過HttpServletRequest的getSession()方法來獲得HttpServletRequest有兩個重載的getSession()方法,一個接受一個boolean的類型的值,另一個不帶任何參數,getSession()方法和getSession(true)方法功能一樣,就是如果對應的客戶端已經產生過一個session,那么就會返回這個舊的session,否則,這個方法將會產生一個session ID并且和對應的客戶端綁定在一起,而如果getSession(false)表示如果對應的客戶端已經有對應的session,那么返回這個舊的session,否則不會產生新的session。可以使用HttpSession對象上的isNow()方法來判定這個session是否為新建的
?
HttpSession常用方法
?
public void setAttribute(String name,Object value)
將value對象以name名稱綁定到會話
public object getAttribute(String name)
取得name的屬性值,如果屬性不存在則返回null
public void removeAttribute(String name)
從會話中刪除name屬性,如果不存在不會執行,也不會拋處錯誤.
public Enumeration getAttributeNames()
返回和會話有關的枚舉值
public void invalidate()
使會話失效,同時刪除屬性對象
public Boolean isNew()
用于檢測當前客戶是否為新的會話
public long getCreationTime()
返回會話創建時間
public long getLastAccessedTime()
返回在會話時間內web容器接收到客戶最后發出的請求的時間
public int getMaxInactiveInterval()
返回在會話期間內客戶請求的最長時間為秒
public void setMaxInactiveInterval(int seconds)
允許客戶客戶請求的最長時間
ServletContext getServletContext()
返回當前會話的上下文環境,ServletContext對象可以使Servlet與web容器進行通信
public String getId()
返回會話期間的識別號
?
一個保存信息到session的例子
?
sessionlogin.html
<meta name="keywords" content="keyword1,keyword2,keyword3" />
<meta name="description" content="this is my page" />
<meta name="content-type" content="text/html; charset=UTF-8" />
?<!-- ? ?<link rel="stylesheet" type="text/css" href="./styles.css">--></pre>
<form action="servlet/saveinfo" method="post">
?用戶名:
?<input type="text" name="username" /> <input type="submit" />
?密碼:
?<input type="password" name="userpasswd" />
?</form>
<pre>
</pre>
</div>
<div>
package xxx;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class saveinfo extends HttpServlet {
?public saveinfo() {
?super();
?}
?public void destroy() {
?super.destroy(); // Just puts "destroy" string in log
?// Put your code here
?}
?public void doGet(HttpServletRequest request, HttpServletResponse response)
?throws ServletException, IOException {
?//如果用戶輸入過了用戶名 則將其放在session中
?if(request.getParameter("username")!=null);
?{
?HttpSession session = request.getSession();
?session.setAttribute("username",request.getParameter("username"));
?}
?response.setContentType("text/html;charset=GBK");
?PrintWriter out = response.getWriter();
?out.println("session已經創建");
?out.println("
");
?out.println("跳轉到其他<a>頁面</a>");
?}
?public void doPost(HttpServletRequest request, HttpServletResponse response)
?throws ServletException, IOException {
?doGet(request,response);
?}
?public void init() throws ServletException {
?// Put your code here
?}
}
package xxx;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class getsession extends HttpServlet {
?public getsession() {
?super();
?}
?public void destroy() {
?super.destroy(); // Just puts "destroy" string in log
?// Put your code here
?}
?public void doGet(HttpServletRequest request, HttpServletResponse response)
?throws ServletException, IOException {
response.setContentType("text/html;charset=GBK");
?PrintWriter out = response.getWriter();
?String username = "";
?//此處不是創建session 而是去取已經創建的session
?HttpSession session = request.getSession();
?//如果已經取到,說明已經登錄
?if(session!=null)
?{
?username = (String)session.getAttribute("username");
?out.println("獲得創建的Session");
?out.println("
");
?out.println("登錄名:"+username);
?}
?else
?{
?response.sendRedirect("../sessionlogin.html");
?}
?}
?public void doPost(HttpServletRequest request, HttpServletResponse response)
?throws ServletException, IOException {
?doGet(request,response);
?}
?public void init() throws ServletException {
?// Put your code here
?}
}
5 獲得客戶端IP和url
可以配合實現IP白名單控制,import javax.servlet.http.HttpServletRequest;
?
public class ClientInfoUtil{
?
/**
* 獲得客戶端的IP地址
* @param request
* @return
*/
static public String getIP(HttpServletRequest request) {
? ? String ip = request.getHeader("x-forwarded-for");
? ? if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
? ? ? ? ip = request.getHeader("Proxy-Client-IP");
? ? }
? ? if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
? ? ? ? ip = request.getHeader("WL-Proxy-Client-IP");
? ? }
? ? if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
? ? ? ? ip = request.getRemoteAddr();
? ? }
? ? return ip;
}
?
/**
* 獲得客戶端訪問服務器的url地址
* @param request
* @return
*/
static public String getURL(HttpServletRequest request) {
? ? String url = request.getScheme()+"://"; ??
? ? url+=request.getHeader("host"); ??
? ? url+=request.getRequestURI(); ??
? ? if(request.getQueryString()!=null) ?{
? ? ? ? url+="?"+request.getQueryString(); ??
? ? }
? ? return url;
}
}
6 JSP+Servlet+JavaBean實現登錄
登錄頁面:login.html登錄成功歡迎頁面:login_success.jsp
登錄失敗頁面:login_failure.jsp
Servlet處理文件:LoginServlet.java
?
登錄頁面:login.html
<!-- 一個簡單的登錄界面 --><!-- 該JSP程序是用來測試與MySQL數據庫的連接, 需要一個數據庫:LearnJSP,和其中一個表:userinfo 表中有兩個字段分別為:UserName varchar (20) not null,UserPwd varchar (20) not null--><html> <head> ?<title>登錄</title> ?<meta http-equiv="content-type" content="text/html; charset=UTF-8"> ?<meta http-equiv="Content-Language" content="ch-cn"> </head> <body> <!-- Form 用來提取用戶填入并提交的信息--> <form method="post" name="frmLogin" action="LoginServlet"> ?<h1 align="center">用戶登錄</h1><br> ?<div align="center">用戶名: ? <input type="text" name="txtUserName" value="Your name" ? ?size="20" maxlength="20" ? ?οnfοcus="if(this.value=='Your name')this.value='';"><br>密碼: ? <input type="password" name="txtPassword" value="Your password" ? ?size="20" maxlength="20" ? ?οnfοcus="if(this.value=='Your password')this.value='';"><br> ? <input type="submit" name="Submit" value="提交" onClick="validateLogin();" > ? ? ? ? ? ? <input type="reset" name="Reset" value="重置"><br> ?</div> </form> <!-- javaScript 函數 validateLogin(),用來驗證用戶名和密碼是否為空 --> ?<script language="javaScript"> ? function validateLogin() ? { ? var sUserName = document.frmLogin.txtUserName.value; ? var sPassword = document.frmLogin.txtPassword.value; ? if( sUserName=="" ) ? { ? ?alert("請輸入用戶名!"); ? ?return false; ? } ? if( sPassword=="" ) ? { ? ?alert("請輸入密碼!"); ? ?return false; ? } ? } ?</script> </body></html>?
登錄成功歡迎頁面:login_success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>My JSP 'login_failure.jsp' starting page</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <% ?String userName = (String)session.getAttribute ( "UserName" ); %> <div align=center> ?<%=userName%> ?歡迎您,登錄成功! </div> </body></html>?
登錄失敗頁面:login_failure.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>My JSP 'login_failure.jsp' starting page</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <% String userName = (String)session.getAttribute ( "UserName" ); %> <div align=center> ?<%=userName%> ?對不起,登錄失敗! </div> </body></html>?
Servlet處理文件:LoginServlet.java
/** * 該JSP程序是用來測試與MySQL數據庫的連接, * 需要一個數據庫:LearnJSP,和其中一個表:userinfo * 表中有兩個字段分別為:UserName varchar (20) not null,UserPwd varchar (20) not null */package zieckey.login.servlet;import java.sql.Statement;import java.io.IOException;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import javax.servlet.Servlet;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class LoginServlet extends HttpServlet implements Servlet{ public LoginServlet () { // TODO Auto-generated constructor stub } /* * (non-Javadoc) * * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override protected void doGet ( HttpServletRequest arg0, HttpServletResponse arg1 ) ?throws ServletException, IOException { } /* * (non-Javadoc) * * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override protected void doPost ( HttpServletRequest request, HttpServletResponse response ) ?throws ServletException, IOException { response.setContentType ( "text/html" ); String result = ""; // 獲取用戶名 String sUserName = request.getParameter ( "txtUserName" ); if ( sUserName == "" || sUserName == null || sUserName.length ( ) > 20 ) { ?try ?{ ?result = "請輸入用戶名(不超過20字符)!"; ?request.setAttribute ( "ErrorUserName", result ); ?response.sendRedirect ( "login.html" ); ?} catch ( Exception e ) ?{ ?} } // 獲取密碼 String sPasswd = request.getParameter ( "txtPassword" ); if ( sPasswd == "" || sPasswd == null || sPasswd.length ( ) > 20 ) { ?try ?{ ?result = "請輸入密碼(不超過20字符)!"; ?request.setAttribute ( "ErrorPassword", result ); ?response.sendRedirect ( "login.html" ); ?} catch ( Exception e ) ?{ ?} } // 登記JDBC驅動程序 try { ?Class.forName ( "org.gjt.mm.mysql.Driver" ).newInstance ( ); } catch ( InstantiationException e ) { ?// TODO Auto-generated catch block ?e.printStackTrace ( ); ?System.out.println ("InstantiationException"); } catch ( IllegalAccessException e ) { ?// TODO Auto-generated catch block ?e.printStackTrace ( ); ?System.out.println ("IllegalAccessException"); } catch ( ClassNotFoundException e ) { ?// TODO Auto-generated catch block ?e.printStackTrace ( ); ?System.out.println ("ClassNotFoundException"); } // 連接參數與Access不同 String url = "jdbc:mysql://localhost/LearnJSP"; // 建立連接 java.sql.Connection connection = null; Statement stmt = null; ResultSet rs = null; try { ?connection = DriverManager.getConnection ( url, "root", "011124" ); ?stmt = connection.createStatement ( ); ?// SQL語句 ?String sql = "select * from userinfo where username='" + sUserName ? + "' and userpwd = '" + sPasswd + "'"; ?rs = stmt.executeQuery ( sql );// 返回查詢結果 } catch ( SQLException e ) { ?// TODO Auto-generated catch block ?e.printStackTrace ( ); } try { ?if ( rs.next ( ) )// 如果記錄集非空,表明有匹配的用戶名和密碼,登陸成功 ?{ ?// 登錄成功后將sUserName設置為session變量的UserName ?// 這樣在后面就可以通過 session.getAttribute("UserName") 來獲取用戶名, ?// 同時這樣還可以作為用戶登錄與否的判斷依據 ?request.getSession ( ).setAttribute ( "UserName", sUserName ); ?response.sendRedirect ( "login_success.jsp" ); ?} else ?{ ?// 否則登錄失敗 ?//response.sendRedirect ( "MyJsp.jsp" ); ?response.sendRedirect ( "login_failure.jsp" ); ?} } catch ( SQLException e ) { ?// TODO Auto-generated catch block ?e.printStackTrace ( ); } try { ?if ( null!=rs ) ?{ ?rs.close ( ); ?} ?if ( null!=stmt ) ?{ ?stmt.close ( ); ?} ?if ( null!=connection ) ?{ ?connection.close ( ); ?} } catch ( SQLException e ) { ?// TODO Auto-generated catch block ?e.printStackTrace ( ); } } /** * */ private static final long serialVersionUID = 1L;}?
7 java servlet頁面跳轉
?response.sendRedirect("/a.jsp");response.sendRedirect("http://www.jb51.net");
RequestDispatcher dispatcher = request.getRequestDispatcher("/a.jsp");
dispatcher .forward(request, response);
response.setHeader("Location","");
8 java中Servlet處理亂碼
1)從頁面獲取數據的servlet出現亂碼,在servlet中已經把request.setCharacterEncoding("GB2312");加入到代碼中去,
JAVA是Unicode編碼,先轉換成ISO8859-1,然后再轉換成GBK或是GB2312.
request.setCharacterEncoding("ISO8859-1"); ? ?
ad=request.getParameter("name"); ? ?
byte[] temp3 = ad.getBytes("GBK"); ? ?
String str = new String(temp3); ??
這樣就是中文啦
2)直接在服務器里設置編碼轉換
在Tomcat的conf目錄里找到SERVER.XML文件,設置如下:?
里面增加一個屬性,URIEncoding="GBK"
3)JSP頁面上是中文,但是看的后是亂碼
解決的辦法就是在JSP頁面的編碼的地方,因為Jsp轉成Java文件時的編碼問題,默認的話有的服務器是ISO-8859-1,如果一個JSP中直接輸入了中文,Jsp把它當作 ISO8859-1來處理是肯定有問題的,這一點,我們可以通過查看Jasper所生成的Java中間文件來確認
?
4)當用Request對象獲取客戶提交的漢字代碼的時候,會出現亂碼
解決的辦法是:要配置一個filter,也就是一個Servelet的過濾器,
代碼如下:
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)throws IOException, ServletException {
request.setCharacterEncoding("GBK");
// 傳遞控制到下一個過濾器
chain.doFilter(request, response);
}
配置web.xml
<filter></filter>
<filter-name></filter-name>Set Character Encoding
<filter-class></filter-class>SetCharacterEncodingFilter
?
<filter-mapping></filter-mapping>
<filter-name></filter-name>Set Character Encoding
<url-pattern></url-pattern>/*
如果還是出現這種情況的話就往下看看是不是出現了第四種情況,Form提交的數據是不是用get提交的,一般來說用post提交的話是沒有問題的,如果是的話,看第四種解決的辦法。
還有就是對含有漢字字符的信息進行處理,處理的代碼是:
public String toUni(String gbStr){
String uniStr = "";
if(gbStr == null){
gbStr = "";
}
try{
byte[] tempByte = gbStr.getBytes("GB2312");
uniStr = new String(tempByte,"ISO8859_1");
}catch(Exception ex){
}
return uniStr;
}
}
也可以在直接的轉換,首先將獲取的字符串用ISO-8859-1進行編碼,然后將這個編碼存放到一個字節數組中,然后將這個數組轉化成字符串對象就可以了,
String str=request.getParameter(“girl”);
Byte B[]=str.getBytes(“ISO-8859-1”);
Str=new String(B);
通過上述轉換的話,提交的任何信息都能正確的顯示。
5)在 Form get請求在服務端用request. getParameter(“name”)時返回的是亂碼
按tomcat的做法設置Filter也沒有用或者用 request.setCharacterEncoding("GBK");也不管用問題是出在處理參數傳遞的方法上:如果在servlet中用 doGet(HttpServletRequest request, HttpServletResponse response)方法進行處理的話前面即使是寫了:
request.setCharacterEncoding("GBK");
response.setContentType("text/html;charset=GBK");
也是不起作用的,返回的中文還是亂碼.
如果把這個函數改成doPost(HttpServletRequest request, HttpServletResponse response)一切就OK了。
同樣,在用兩個JSP頁面處理表單輸入之所以能顯示中文是因為用的是post方法傳遞的,改成get方法依舊不行。
由此可見在servlet中用doGet()方法或是在JSP中用get方法進行處理要注意。這畢竟涉及到要通過瀏覽器傳遞參數信息,很有可能引起常用字符集的沖突或是不匹配。
這個地方理解為request.setCharacterEncoding("GBK");set的是request中的body,而不是header部分,get請求時把參數放在url后邊,不是放在body中,所以這個時候request.setCharacterEncoding("GBK")就沒有起到作用,換到post提交就沒有問題了,
解決的辦法是:
1) 打開tomcat的server.xml文件,找到區塊,加入如下一行:
URIEncoding=”GBK”
完整的應如下:
<connector uriencoding="GBK" maxthreads="150" debug="0" redirectport="8443" port="8080" enablelookups="false" maxsparethreads="75" minsparethreads="25" connectiontimeout="20000" disableuploadtimeout="true" acceptcount="100"></connector>
重啟tomcat,一切OK。
6)JSP頁面上有中文,按鈕上面也有中文,但是通過服務器查看頁面的時候出現亂碼
解決的辦法是:首先在JSP文件中不應該直接包含本地化的消息文本,而是應該通過<bean:message>標簽從Resource Bundle中獲得文本。應該把中文文本放到Application.properties文件中,這個文件放在WEB-INF/classes/* 下,例如頁面里有姓名,年齡兩個label,首先就是要建一個Application.properties,里面的內容應該是name=”姓名” age=”年齡”,然后把這個文件放到WEB-INF/classes/properties/下,接下來根據 Application.properties文件,對他進行編碼轉化,創建一個中文資源文件,假定名字是 Application_cn.properties。在JDK中提供了native2ascii命令,能夠實現字符編碼的轉換。在DOS環境中找到你放置Application.properties的這個文件的目錄,在DOS環境中執行一下命令,將生成按GBK編碼的中文資源文件 Application_cn.properties:native2ascii ?encoding gbk Application.properties Application_cn.properties執行以上命令以后將生成如下內容的Application_cn.properties文件: name=u59d3u540d age=u5e74u9f84,在Struts-config.xml中配置:<message-resources parameter="properties.Application_cn"></message-resources>。到這一步,基本上完成了一大半,接著就要在JSP頁面上寫,到名字的那個label是要寫<bean:message key="”name”">,這樣的化在頁面上出現的時候就會出現中文的姓名,年齡這個也是一樣,按鈕上漢字的處理也是同樣的。
?
7)寫入到數據庫是亂碼
解決的方法:要配置一個filter,也就是一個Servelet的過濾器,代碼如同第二種時候一樣。
如果是通過JDBC直接鏈接數據庫的時候,配置的代碼如下:jdbc:mysql://localhost:3306/workshopdb? useUnicode=true&characterEncoding=GBK,這樣保證到數據庫中的代碼是不是亂碼。
如果是通過數據源鏈接的話不能按照這樣的寫法了,首先就要寫在配置文件中,
<context debug="0" path="/workshop" docbase="workshop"></context>reloadable="true" >
?
<resource name="jdbc/WorkshopDB"></resource>auth="Container"
type="javax.sql.DataSource" />
?
<resourceparams name="jdbc/WorkshopDB"></resourceparams>
<parameter></parameter>?
<name></name>factory
<value></value>org.apache.commons.dbcp.BasicDataSourceFactory
?
<parameter></parameter>?
<name></name>maxActive
<value></value>100
?
<parameter></parameter>?
<name></name>maxIdle
<value></value>30
?
<parameter></parameter>?
<name></name>maxWait
<value></value>10000
?
<parameter></parameter>?
<name></name>username
<value></value>root
?
<parameter></parameter>?
<name></name>password
<value></value>
?
<parameter></parameter>?
<name></name>driverClassName
<value></value>com.mysql.jdbc.Driver
?
<parameter></parameter>?
<name></name>url
<value></value>
8)servlet分頁
Oracle數據庫,獲取SCOTT用戶EMP表中的數據,創建一個對象 UserData,用以保存從數據庫中獲取的數據。
package com.tool;
?
import java.math.BigDecimal;
import java.util.Date;
?
public class UserData {
?
? ? /**
? ? ?* EMP表中的數據屬性
? ? ?*/
? ? private String ename;
? ? private String job;
? ? private BigDecimal empno;
? ? private BigDecimal mgr;
? ? private Date hireDate;
? ? private BigDecimal sal;
? ? private BigDecimal comm;
? ? private BigDecimal deptno;
?
? ? public BigDecimal getEmpno() {
? ? ? ? return empno;
? ? }
?
? ? public void setEmpno(BigDecimal empno) {
? ? ? ? this.empno = empno;
? ? }
?
? ? public BigDecimal getMgr() {
? ? ? ? return mgr;
? ? }
?
? ? public void setMgr(BigDecimal mgr) {
? ? ? ? this.mgr = mgr;
? ? }
?
? ? public Date getHireDate() {
? ? ? ? return hireDate;
? ? }
?
? ? public void setHireDate(Date hireDate) {
? ? ? ? this.hireDate = hireDate;
? ? }
?
? ? public BigDecimal getSal() {
? ? ? ? return sal;
? ? }
?
? ? public void setSal(BigDecimal sal) {
? ? ? ? this.sal = sal;
? ? }
?
? ? public BigDecimal getComm() {
? ? ? ? return comm;
? ? }
?
? ? public void setComm(BigDecimal comm) {
? ? ? ? this.comm = comm;
? ? }
?
? ? public BigDecimal getDeptno() {
? ? ? ? return deptno;
? ? }
?
? ? public void setDeptno(BigDecimal deptno) {
? ? ? ? this.deptno = deptno;
? ? }
?
? ? public String getEname() {
? ? ? ? return ename;
? ? }
?
? ? public void setEname(String ename) {
? ? ? ? this.ename = ename;
? ? }
?
? ? public String getJob() {
? ? ? ? return job;
? ? }
?
? ? public void setJob(String job) {
? ? ? ? this.job = job;
? ? }
}
創建一個 DBHelper 對象用以與數據庫進行交互
package com.dao;
?
import com.tool.UserData;
?
import java.math.BigDecimal;
import java.sql.*;
import java.util.*;
import java.util.Date;
?
public class DBHelper {
?
? ? Connection conn; ?//數據庫連接對象
? ? PreparedStatement pt; ?//SQL語句預處理對象
? ? ResultSet rs; ?//結果集對象
?
? ? public ?DBHelper(){
? ? ? ? try {
? ? ? ? ? ? Class.forName("oracle.jdbc.driver.OracleDriver"); ?//裝載驅動
? ? ? ? } catch (ClassNotFoundException e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? }
?
? ? /**
? ? ?* 獲取當前頁的數據
? ? ?* @param curPage
? ? ?* @param rowsPerPage
? ? ?* @return
? ? ?*/
? ? public List<UserData> getData(int curPage, int rowsPerPage) {
?
? ? ? ? List<UserData> dataList = new ArrayList<>();
? ? ? ? String url = "jdbc:oracle:thin:@localhost:1521:orcl";
? ? ? ? try {
? ? ? ? ? ? conn = DriverManager.getConnection(url,"scott","tiger");
? ? ? ? ? ? String sql = "select * from emp where rownum <= ((? - 1) * "+rowsPerPage+" + "+rowsPerPage+") minus " +
? ? ? ? ? ? ? ? ? ? " select * from emp where rownum <= (? - 1) * "+rowsPerPage+" ";
? ? ? ? ? ? pt = conn.prepareStatement(sql);
? ? ? ? ? ? pt.setInt(1,curPage);
? ? ? ? ? ? pt.setInt(2,curPage);
? ? ? ? ? ? rs = pt.executeQuery();
? ? ? ? ? ? while (rs.next()){
? ? ? ? ? ? ? ? /**
? ? ? ? ? ? ? ? ?* 從結果集中取得數據
? ? ? ? ? ? ? ? ?*/
? ? ? ? ? ? ? ? UserData userData = new UserData();
? ? ? ? ? ? ? ? BigDecimal empno = rs.getBigDecimal("empno");
? ? ? ? ? ? ? ? String ename = rs.getString("ename");
? ? ? ? ? ? ? ? String job = rs.getString("job");
? ? ? ? ? ? ? ? BigDecimal mgr = rs.getBigDecimal("mgr");
? ? ? ? ? ? ? ? Date hireDate = rs.getDate("hiredate");
? ? ? ? ? ? ? ? BigDecimal sal = rs.getBigDecimal("sal");
? ? ? ? ? ? ? ? BigDecimal comm = rs.getBigDecimal("comm");
? ? ? ? ? ? ? ? BigDecimal deptno = rs.getBigDecimal("deptno");
? ? ? ? ? ? ? ? /**
? ? ? ? ? ? ? ? ?* 設置對象屬性
? ? ? ? ? ? ? ? ?*/
? ? ? ? ? ? ? ? userData.setEmpno(empno);
? ? ? ? ? ? ? ? userData.setEname(ename);
? ? ? ? ? ? ? ? userData.setJob(job);
? ? ? ? ? ? ? ? userData.setMgr(mgr);
? ? ? ? ? ? ? ? userData.setHireDate(hireDate);
? ? ? ? ? ? ? ? userData.setSal(sal);
? ? ? ? ? ? ? ? userData.setComm(comm);
? ? ? ? ? ? ? ? userData.setDeptno(deptno);
? ? ? ? ? ? ? ? dataList.add(userData); ?//把對象添加集合中
? ? ? ? ? ? }
? ? ? ? ? ? rs.close();
? ? ? ? ? ? pt.close();
? ? ? ? ? ? conn.close();
? ? ? ? } catch (SQLException e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? ? ? return dataList;
? ? }
?
? ? /**
? ? ?* 返回總頁數
? ? ?* @return
? ? ?*/
? ? public int getMaxPage(int rowsPerPage) {
? ? ? ? int maxPage;
? ? ? ? int maxRowCount = 0;
? ? ? ? String url = "jdbc:oracle:thin:@localhost:1521:orcl";
? ? ? ? try {
? ? ? ? ? ? conn = DriverManager.getConnection(url,"scott","tiger"); ?//創建數據庫連接
? ? ? ? ? ? String sql = "select count(*) from emp";
? ? ? ? ? ? pt = conn.prepareStatement(sql);
? ? ? ? ? ? rs = pt.executeQuery();
? ? ? ? ? ? if (rs.next()){
? ? ? ? ? ? ? ? maxRowCount = rs.getInt(1); ?//總行數
? ? ? ? ? ? }
? ? ? ? } catch (SQLException e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? ? ? maxPage = (maxRowCount + rowsPerPage - 1) / rowsPerPage; ?//總頁數
? ? ? ? return maxPage;
? ? }
}
創建 Servlet 對顯示頁面進行控制
package com.servlet;
?
import com.dao.DBHelper;
import com.tool.UserData;
?
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
?
public class Servlet extends HttpServlet {
?
? ? public int rowsPerPage; ?//每頁顯示的行數
? ? public int curPage; ?//當前頁頁碼
? ? public int maxPage; ?//總共頁數
? ? DBHelper db = new DBHelper();
? ? public Servlet(){
? ? ? ? rowsPerPage = 5;
? ? }
?
? ? protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
? ? ? ? String curPage1 = request.getParameter("page"); ?//獲取當前頁頁碼
? ? ? ? if (curPage1 == null){
? ? ? ? ? ? curPage = 1;
? ? ? ? ? ? request.setAttribute("curPage",curPage); ?//設置curPage對象
? ? ? ? }else {
? ? ? ? ? ? curPage = Integer.parseInt(curPage1);
? ? ? ? ? ? if (curPage < 1){
? ? ? ? ? ? ? ? curPage = 1;
? ? ? ? ? ? }
? ? ? ? ? ? request.setAttribute("curPage",curPage);
? ? ? ? }
?
? ? ? ? List<UserData> dataList;
? ? ? ? dataList = db.getData(curPage,rowsPerPage); ?//獲取當前頁的數據
? ? ? ? maxPage = db.getMaxPage(rowsPerPage); ?//獲取總頁數
? ? ? ? request.setAttribute("dataList",dataList);
? ? ? ? request.setAttribute("maxPage", maxPage);
?
? ? ? ? RequestDispatcher rd = request.getRequestDispatcher("pagemain.jsp"); ?//將請求轉發到pagemain.jsp頁面
? ? ? ? rd.forward(request,response);
? ? }
?
? ? protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
? ? ? ? doPost(request,response);
? ? }
}
創建 JSP 頁面,顯示數據。
<%@ page import="java.util.List" %>
<%@ page import="com.tool.UserData" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
? ? <title>servlet數據分頁</title>
? ? <link rel="stylesheet" type="text/css" href="css.css">
</head>
<body>
<div style="margin-top: 15%; margin-left: 25%">
? ? <table>
? ? ? ? <caption>SCOTT用戶,EMP表中的數據</caption>
? ? ? ? <%! int curPage,maxPage; %>
? ? ? ? <% curPage =Integer.parseInt(request.getAttribute("curPage").toString()); %> <!--取得當前頁-->
? ? ? ? <% maxPage =Integer.parseInt((String)request.getAttribute("maxPage").toString()); %> <!--取得總頁數-->
? ? ? ? <%if (request.getAttribute("dataList") == null){
? ? ? ? %>
? ? ? ? <tr>
? ? ? ? ? ? <td colspan="8">沒有數據</td>
? ? ? ? </tr>
? ? ? ? <%
? ? ? ? }else {
? ? ? ? %>
? ? ? ? <tr>
? ? ? ? ? ? <!--表頭-->
? ? ? ? ? ? <th>EMPNO</th>
? ? ? ? ? ? <th>ENAME</th>
? ? ? ? ? ? <th>JOB</th>
? ? ? ? ? ? <th>MGR</th>
? ? ? ? ? ? <th>HIREDATE</th>
? ? ? ? ? ? <th>SAL</th>
? ? ? ? ? ? <th>COMM</th>
? ? ? ? ? ? <th>DEPTNO</th>
? ? ? ? </tr>
? ? ? ? <%
? ? ? ? ? ? List list = (List) request.getAttribute("dataList");
? ? ? ? ? ? for (Object aList : list) {
? ? ? ? ? ? ? ? UserData userData = (UserData) aList;
? ? ? ? %>
? ? ? ? <tr>
? ? ? ? ? ? <!--取得表中數據-->
? ? ? ? ? ? <td><%= userData.getEmpno() %></td>
? ? ? ? ? ? <td><%= userData.getEname() %></td>
? ? ? ? ? ? <td><%= userData.getJob() %></td>
? ? ? ? ? ? <td><%= userData.getMgr() %></td>
? ? ? ? ? ? <td><%= userData.getHireDate() %></td>
? ? ? ? ? ? <td><%= userData.getSal() %></td>
? ? ? ? ? ? <td><%= userData.getComm() %></td>
? ? ? ? ? ? <td><%= userData.getDeptno() %></td>
? ? ? ? </tr>
? ? ? ? <%
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? %>
? ? </table>
</div>
<div style="margin-top: 8%; margin-left: 29%">
? ? 第<%= curPage %>頁,共<%= maxPage %>頁 ?
? ? <%if (curPage > 1){
? ? %>
? ? <a href="Servlet?page=1">首頁</a>
? ? <a href="Servlet?page=<%=curPage - 1%>">上一頁</a>
? ? <%
? ? }else {
? ? %>
? ? 首頁 上一頁
? ? <%
? ? ? ? }%>
? ? <%if (curPage < maxPage){
? ? %> ?
? ? <a href="Servlet?page=<%=curPage + 1%>">下一頁</a>
? ? <a href="Servlet?page=<%=maxPage %>">尾頁</a>
? ? <%
? ? }else {
? ? %>
? ? 下一頁 尾頁
? ? <%
? ? ? ? }%>
? ? ? 轉至第 <form name="form1" action="Servlet" method="get">
? ? <label>
? ? ? ? <select name="page" οnchange="document.form1.submit()">
? ? ? ? ? ? <%for ( int i = 1; i <= maxPage; i++){
? ? ? ? ? ? ? ? if (i == curPage){
? ? ? ? ? ? %>
? ? ? ? ? ? <!--當前頁頁碼默認選中-->
? ? ? ? ? ? <option selected value="<%= i%>"><%= i %></option>
? ? ? ? ? ? <%
? ? ? ? ? ? }else {
? ? ? ? ? ? %>
? ? ? ? ? ? <option value="<%= i %>"><%= i %></option>
? ? ? ? ? ? <%
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }%>
? ? ? ? </select>
? ? </label>
</form> 頁
</div>
</body>
</html>
?
web.xml
? ? <servlet>
? ? ? ? <servlet-name>Servlet</servlet-name>
? ? ? ? <servlet-class>com.servlet.Servlet</servlet-class>
? ? </servlet>
? ? <servlet-mapping>
? ? ? ? <servlet-name>Servlet</servlet-name>
? ? ? ? <url-pattern>/Servlet</url-pattern>
? ? </servlet-mapping>
總結
以上是生活随笔為你收集整理的Java Servlet 开发常用代码、模板、问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: opencv图像处理总结
- 下一篇: Java开发语句和代码块模板