1 简述什么是重定向。

参考答案

服务器向浏览器发送一个302状态码及一个Location消息头(该消息头的值是一个地址,称之为重定向地址),浏览器收到后会立即向重定向地址发出请求。

2 实现NetCTOSS系统中的帐务帐号的增删改查功能。

参考答案

使用后缀匹配模式,将以do结尾的请求都提交到ActionServlet中,分析do前的操作请求种类,分发到不同的分支执行相应的动作。同时将JDBC以DAO和实体的形式来实现,减少分支内的重复代码。

实现本案例可以按照如下步骤进行。

步骤一:创建web工程

创建名为Servlet_03_exec的web工程,该工程的结构图如下所示:

图-1

步骤二:新建entity.Account类

新建与account表对应的实体类,属性与表字段一一对应,添加get/set方法及构造方法、toString方法。代码如下所示:

package entity;

publicclass Account {
	privateint accountId;
	private String realName;
	private String idcardNo;
	private String loginName;
	private String status;
	private String telephone;

	publicint getAccountId() {
		return accountId;
	}

	publicvoid setAccountId(int accountId) {
		this.accountId = accountId;
	}

	public String getRealName() {
		return realName;
	}

	publicvoid setRealName(String realName) {
		this.realName = realName;
	}

	public String getIdcardNo() {
		return idcardNo;
	}

	publicvoid setIdcardNo(String idcardNo) {
		this.idcardNo = idcardNo;
	}

	public String getLoginName() {
		return loginName;
	}

	publicvoid setLoginName(String loginName) {
		this.loginName = loginName;
	}

	public String getStatus() {
		return status;
	}

	publicvoid setStatus(String status) {
		this.status = status;
	}

	public String getTelephone() {
		return telephone;
	}

	publicvoid setTelephone(String telephone) {
		this.telephone = telephone;
	}

}

步骤三:新建dao.DBUtil公共类

用于实现数据库的连接和关闭的工具类,该类的代码如下所示:

package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * JDBC管理连接的工具类,可以获取连接和关闭连接
 */
public class DBUtil {
	/**
	 * 获取连接对象
	 */
	public static Connection getConnection()throws Exception{
		Connection conn = null;
		try {
			Class.forName("oracle.jdbc.OracleDriver");
			conn = DriverManager.getConnection(
					"jdbc:oracle:thin:@localhost:1521:orcl", "scott", "tiger");
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return conn;
	}
	/**
	 * 关闭连接对象
	 */
	public static void close(Connection conn) throws Exception{
		if(conn!=null){
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw e;
			}
		}
	}
	
	public static void main(String[] args) throws Exception{
		System.out.println(getConnection());
	}
}

步骤四:新建dao.AccountDAO类

建立针对Account实体的数据操作类DAO。该类的代码如下所示:

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import entity.Account;

/**
 * Account的数据操作对象,负责Account的增删改查
 */
public class AccountDAO {
	
	/**
	 * 查询所有帐务帐号信息
	 */
	public List<Account> findAll() throws Exception{
		List<Account> accounts = new ArrayList<Account>();
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try{
			conn = DBUtil.getConnection();
			stmt = conn.prepareStatement("select * from account");
			rs = stmt.executeQuery();
			while(rs.next()){
				Account account = new Account();
				int accountId = rs.getInt("account_id");
				String realName = rs.getString("real_name");
				String idcardNo = rs.getString("idcard_no");
				String loginName = rs.getString("login_name");
				String status=rs.getString("status");
				String telephone = rs.getString("telephone");
				
				account.setAccountId(accountId);
				account.setRealName(realName);
				account.setIdcardNo(idcardNo);
				account.setLoginName(loginName);
				account.setStatus(status);
				account.setTelephone(telephone);
				
				accounts.add(account);
			}
		}catch(Exception e){
			e.printStackTrace();
			throw e;
		}finally{
			DBUtil.close(conn);
		}
		return accounts;
	}
	
	/**
	 * 删除帐务帐号信息
	 */
	public void delete(int accountId) throws Exception{
		Connection conn = null;
		PreparedStatement stmt = null;
		try{
			conn = DBUtil.getConnection();
			stmt = conn.prepareStatement("delete from account where account_id=?");
			stmt.setInt(1, accountId);
			stmt.executeUpdate();
		}catch(Exception e){
			e.printStackTrace();
			throw e;
		}finally{
			DBUtil.close(conn);
		}
	}
	
	/**
	 * 增加帐务帐号信息
	 */
	public void save(Account account) throws Exception{
		Connection conn = null;
		PreparedStatement stmt = null;
		try{
			conn = DBUtil.getConnection();
			stmt = conn.prepareStatement("insert into account" +
					"(account_id,login_name,status,real_name,idcard_no,telephone) " +
					"values(account_id_seq.nextval,?,?,?,?,?)");
			stmt.setString(1, account.getLoginName());
			stmt.setString(2, "0");//添加创建即为开通状态
			stmt.setString(3, account.getRealName());
			stmt.setString(4, account.getIdcardNo());
			stmt.setString(5, account.getTelephone());
			stmt.executeUpdate();
		}catch(Exception e){
			e.printStackTrace();
			throw e;
		}finally{
			DBUtil.close(conn);
		}
	}
	
	/**
	 * 根据id查询员工信息
	 */
	public Account findById(int id) throws Exception{
		Account account = null;
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try{
			conn = DBUtil.getConnection();
			stmt = conn.prepareStatement("select * from account where account_id=?");
			stmt.setInt(1, id);
			rs = stmt.executeQuery();
			if(rs.next()){
				account = new Account();
				int accountId = rs.getInt("account_id");
				String realName = rs.getString("real_name");
				String idcardNo = rs.getString("idcard_no");
				String loginName = rs.getString("login_name");
				String status=rs.getString("status");
				String telephone = rs.getString("telephone");
				
				account.setAccountId(accountId);
				account.setRealName(realName);
				account.setIdcardNo(idcardNo);
				account.setLoginName(loginName);
				account.setStatus(status);
				account.setTelephone(telephone);
			}
		}catch(Exception e){
			e.printStackTrace();
			throw e;
		}finally{
			DBUtil.close(conn);
		}
		return account;
	}

	/**
	 * 保存修改员工信息
	 */
	public void modify(Account account)throws Exception{
		Connection conn = null;
		PreparedStatement stmt = null;
		try{
			conn = DBUtil.getConnection();
			stmt = conn.prepareStatement("update account set login_name=?,real_name=?," +
					"idcard_no=?,telephone=? where account_id=?");
			stmt.setString(1, account.getLoginName());
			stmt.setString(2, account.getRealName());
			stmt.setString(3, account.getIdcardNo());
			stmt.setString(4, account.getTelephone());
			stmt.setInt(5, account.getAccountId());
			stmt.executeUpdate();
		}catch(Exception e){
			e.printStackTrace();
			throw e;
		}finally{
			DBUtil.close(conn);
		}
	}
}

步骤五:新建web.ActionServlet类

创建用于进行动作分发的ActionServlet类,通过getRequestURI获取请求资源路径,分析do前面的动作种类,执行不同的分支。代码如下所示:

package web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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

import dao.AccountDAO;
import entity.Account;

public class ActionServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();

		// 获取请求资源路径
		String uri = request.getRequestURI();
		// 获取请求资源路径中除应用名以外的部分
		String action = uri.substring(uri.lastIndexOf("/") + 1, uri
				.lastIndexOf("."));
		AccountDAO dao = new AccountDAO();
		if (action.equals("list")) {
			try {
				List<Account> accounts = dao.findAll();
				out
						.println("<table table border='1' cellpadding='0' cellspacing='0' width='60%'>");
				out.println("<caption>帐务帐号信息列表</caption>");
				out
						.println("<tr><td>ID</td><td>姓名</td><td>身份证号</td><td>登录名</td>"
								+ "<td>状态</td><td>手机号</td><td>操作</td></tr>");
				for (Account account : accounts) {
					out.println("<tr>");
					String strStatus = "";
					if ("1".equals(account.getStatus())) {
						strStatus = "暂停";
					} else if ("2".equals(account.getStatus())) {
						strStatus = "删除";
					} else {
						strStatus = "开通";
					}
					out.println("<tr><td>" + account.getAccountId()
							+ "</td><td>" + account.getRealName() + "</td><td>"
							+ account.getIdcardNo() + "</td><td>"
							+ account.getLoginName() + "</td><td>" + strStatus
							+ "</td><td>" + account.getTelephone() + "</td>");

					out.println("<td><a href='delete.do?accountId="
							+ account.getAccountId() + "' "
							+ "onclick=\"return confirm('是否确定删除"
							+ account.getRealName() + "');\">删除</a>");
					out.println("<a href='load.do?accountId=" + account.getAccountId()
							+ "'>修改</a></td>");

					out.println("</tr>");
				}
				out.println("</table>");
				out.println("<a href='addAccount.html'>增加帐务帐号</a>");
			} catch (Exception e) {
				e.printStackTrace();
				out.print("系统繁忙");
			}
		} else if (action.equals("add")) {
			String realName = request.getParameter("realName");
			String idcardNo = request.getParameter("idcardNo");
			String loginName = request.getParameter("loginName");
			String telephone = request.getParameter("telephone");
			try {
				Account account = new Account();
				account.setRealName(realName);
				account.setIdcardNo(idcardNo);
				account.setLoginName(loginName);
				account.setStatus("0");
				account.setTelephone(telephone);
				dao.save(account);
				response.sendRedirect("list.do");
			} catch (Exception e) {
				e.printStackTrace();
				out.print("系统繁忙");
			}
		} else if (action.equals("delete")) {
			String accountId = request.getParameter("accountId");
			try {
				dao.delete(Integer.parseInt(accountId));
				response.sendRedirect("list.do");
			} catch (Exception e) {
				e.printStackTrace();
				out.print("系统繁忙");
			}
		} else if (action.equals("load")) {
			String accountId = request.getParameter("accountId");
			try {
				Account acc = dao.findById((Integer.parseInt(accountId)));
				out.println("<html><head></head><body style='font-size:30px'>");
				if (acc != null) {
					out.println("<form action='modify.do' method='post'>");
					out.println("编号:" + acc.getAccountId() + "<br>");
					out.println("<input type='hidden' name='accountId' value='"
							+ acc.getAccountId() + "'/><br>");
					out.println("姓名:<input name='realName' value='"
							+ acc.getRealName() + "'/><br>");
					out.println("身份证:<input name='idcardNo' value='"
							+ acc.getIdcardNo() + "'/><br>");
					out.println("登录名:<input name='loginName' value='"
							+ acc.getLoginName() + "'/><br>");
					out.println("手机号:<input name='telephone' value='"
							+ acc.getTelephone() + "'/><br>");
					out.println("<input type='submit' value='修改'/>");
					out.println("</form>");
				}
				out.println("</body></html>");
			} catch (Exception e) {
				e.printStackTrace();
				out.print("系统繁忙");
			}
		} else if (action.equals("modify")) {
			String accountId = request.getParameter("accountId");
			String realName = request.getParameter("realName");
			String idcardNo = request.getParameter("idcardNo");
			String loginName = request.getParameter("loginName");
			String telephone = request.getParameter("telephone");
			try {
				Account account = new Account();
				account.setAccountId(Integer.parseInt(accountId));
				account.setRealName(realName);
				account.setIdcardNo(idcardNo);
				account.setLoginName(loginName);
				account.setTelephone(telephone);
				dao.modify(account);
				response.sendRedirect("list.do");
			} catch (Exception e) {
				e.printStackTrace();
				out.print("系统繁忙");
			}
		}
     out.close();
	}

}

步骤六:新建addAccount.html文件

新建用于完成增加员工的表单页面。表单的action地址为ActionServlet对应的add.do,method方式为post,代码如下所示:

<html>
	<head>
		<meta http-equiv="content-type" content="text/html;charset=utf-8">
	</head>
	<body style="font-size:24px">
		<form action="add.do" method="post">
			<fieldset>
				<legend>添加帐务帐号</legend>
				姓名:<input name="realName"/><br>
				身份证:<input name="idcardNo"/><br>
				登录名:<input name="loginName"/><br>
				手机号:<input name="telephone"/><br>
				<input type="submit" value="添加"/>
			</fieldset>
		</form>
	</body>
</html>

步骤七:修改web.xml文件

使用后缀匹配模式配置ActionServlet的映射原则。代码如下所示:

<?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>actionServlet</servlet-name>
		<servlet-class>web.ActionServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>actionServlet</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
</web-app>

步骤八:部署应用,访问

部署并访问工程,访问地址为“http://localhost:8080/应用名/list.do”。

本案例的完整代码如下。

Account类的完整代码如下所示:

package entity;

publicclass Account {
	privateint accountId;
	private String realName;
	private String idcardNo;
	private String loginName;
	private String status;
	private String telephone;

	publicint getAccountId() {
		return accountId;
	}

	publicvoid setAccountId(int accountId) {
		this.accountId = accountId;
	}

	public String getRealName() {
		return realName;
	}

	publicvoid setRealName(String realName) {
		this.realName = realName;
	}

	public String getIdcardNo() {
		return idcardNo;
	}

	publicvoid setIdcardNo(String idcardNo) {
		this.idcardNo = idcardNo;
	}

	public String getLoginName() {
		return loginName;
	}

	publicvoid setLoginName(String loginName) {
		this.loginName = loginName;
	}

	public String getStatus() {
		return status;
	}

	publicvoid setStatus(String status) {
		this.status = status;
	}

	public String getTelephone() {
		return telephone;
	}

	publicvoid setTelephone(String telephone) {
		this.telephone = telephone;
	}

}

DBUtil类的完整代码如下所示::

package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * JDBC管理连接的工具类,可以获取连接和关闭连接
 */
public class DBUtil {
	/**
	 * 获取连接对象
	 */
	public static Connection getConnection()throws Exception{
		Connection conn = null;
		try {
			Class.forName("oracle.jdbc.OracleDriver");
			conn = DriverManager.getConnection(
					"jdbc:oracle:thin:@localhost:1521:orcl", "scott", "tiger");
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return conn;
	}
	/**
	 * 关闭连接对象
	 */
	public static void close(Connection conn) throws Exception{
		if(conn!=null){
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw e;
			}
		}
	}
	
	public static void main(String[] args) throws Exception{
		System.out.println(getConnection());
	}
}

AccountDAO类的完整代码如下所示:

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import entity.Account;

/**
 * Account的数据操作对象,负责Account的增删改查
 */
public class AccountDAO {
	
	/**
	 * 查询所有帐务帐号信息
	 */
	public List<Account> findAll() throws Exception{
		List<Account> accounts = new ArrayList<Account>();
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try{
			conn = DBUtil.getConnection();
			stmt = conn.prepareStatement("select * from account");
			rs = stmt.executeQuery();
			while(rs.next()){
				Account account = new Account();
				int accountId = rs.getInt("account_id");
				String realName = rs.getString("real_name");
				String idcardNo = rs.getString("idcard_no");
				String loginName = rs.getString("login_name");
				String status=rs.getString("status");
				String telephone = rs.getString("telephone");
				
				account.setAccountId(accountId);
				account.setRealName(realName);
				account.setIdcardNo(idcardNo);
				account.setLoginName(loginName);
				account.setStatus(status);
				account.setTelephone(telephone);
				
				accounts.add(account);
			}
		}catch(Exception e){
			e.printStackTrace();
			throw e;
		}finally{
			DBUtil.close(conn);
		}
		return accounts;
	}
	
	/**
	 * 删除帐务帐号信息
	 */
	public void delete(int accountId) throws Exception{
		Connection conn = null;
		PreparedStatement stmt = null;
		try{
			conn = DBUtil.getConnection();
			stmt = conn.prepareStatement("delete from account where account_id=?");
			stmt.setInt(1, accountId);
			stmt.executeUpdate();
		}catch(Exception e){
			e.printStackTrace();
			throw e;
		}finally{
			DBUtil.close(conn);
		}
	}
	
	/**
	 * 增加帐务帐号信息
	 */
	public void save(Account account) throws Exception{
		Connection conn = null;
		PreparedStatement stmt = null;
		try{
			conn = DBUtil.getConnection();
			stmt = conn.prepareStatement("insert into account" +
					"(account_id,login_name,status,real_name,idcard_no,telephone) " +
					"values(account_id_seq.nextval,?,?,?,?,?)");
			stmt.setString(1, account.getLoginName());
			stmt.setString(2, "0");//添加创建即为开通状态
			stmt.setString(3, account.getRealName());
			stmt.setString(4, account.getIdcardNo());
			stmt.setString(5, account.getTelephone());
			stmt.executeUpdate();
		}catch(Exception e){
			e.printStackTrace();
			throw e;
		}finally{
			DBUtil.close(conn);
		}
	}
	
	/**
	 * 根据id查询员工信息
	 */
	public Account findById(int id) throws Exception{
		Account account = null;
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try{
			conn = DBUtil.getConnection();
			stmt = conn.prepareStatement("select * from account where account_id=?");
			stmt.setInt(1, id);
			rs = stmt.executeQuery();
			if(rs.next()){
				account = new Account();
				int accountId = rs.getInt("account_id");
				String realName = rs.getString("real_name");
				String idcardNo = rs.getString("idcard_no");
				String loginName = rs.getString("login_name");
				String status=rs.getString("status");
				String telephone = rs.getString("telephone");
				
				account.setAccountId(accountId);
				account.setRealName(realName);
				account.setIdcardNo(idcardNo);
				account.setLoginName(loginName);
				account.setStatus(status);
				account.setTelephone(telephone);
			}
		}catch(Exception e){
			e.printStackTrace();
			throw e;
		}finally{
			DBUtil.close(conn);
		}
		return account;
	}

	/**
	 * 保存修改员工信息
	 */
	public void modify(Account account)throws Exception{
		Connection conn = null;
		PreparedStatement stmt = null;
		try{
			conn = DBUtil.getConnection();
			stmt = conn.prepareStatement("update account set login_name=?,real_name=?," +
					"idcard_no=?,telephone=? where account_id=?");
			stmt.setString(1, account.getLoginName());
			stmt.setString(2, account.getRealName());
			stmt.setString(3, account.getIdcardNo());
			stmt.setString(4, account.getTelephone());
			stmt.setInt(5, account.getAccountId());
			stmt.executeUpdate();
		}catch(Exception e){
			e.printStackTrace();
			throw e;
		}finally{
			DBUtil.close(conn);
		}
	}
}

ActionServlet类的完整代码如下所示:

package web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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

import dao.AccountDAO;
import entity.Account;

public class ActionServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();

		// 获取请求资源路径
		String uri = request.getRequestURI();
		// 获取请求资源路径中除应用名以外的部分
		String action = uri.substring(uri.lastIndexOf("/") + 1, uri
				.lastIndexOf("."));
		AccountDAO dao = new AccountDAO();
		if (action.equals("list")) {
			try {
				List<Account> accounts = dao.findAll();
				out
						.println("<table table border='1' cellpadding='0' cellspacing='0' width='60%'>");
				out.println("<caption>帐务帐号信息列表</caption>");
				out
						.println("<tr><td>ID</td><td>姓名</td><td>身份证号</td><td>登录名</td>"
								+ "<td>状态</td><td>手机号</td><td>操作</td></tr>");
				for (Account account : accounts) {
					out.println("<tr>");
					String strStatus = "";
					if ("1".equals(account.getStatus())) {
						strStatus = "暂停";
					} else if ("2".equals(account.getStatus())) {
						strStatus = "删除";
					} else {
						strStatus = "开通";
					}
					out.println("<tr><td>" + account.getAccountId()
							+ "</td><td>" + account.getRealName() + "</td><td>"
							+ account.getIdcardNo() + "</td><td>"
							+ account.getLoginName() + "</td><td>" + strStatus
							+ "</td><td>" + account.getTelephone() + "</td>");

					out.println("<td><a href='delete.do?accountId="
							+ account.getAccountId() + "' "
							+ "onclick=\"return confirm('是否确定删除"
							+ account.getRealName() + "');\">删除</a>");
					out.println("<a href='load.do?accountId=" + account.getAccountId()
							+ "'>修改</a></td>");

					out.println("</tr>");
				}
				out.println("</table>");
				out.println("<a href='addAccount.html'>增加帐务帐号</a>");
			} catch (Exception e) {
				e.printStackTrace();
				out.print("系统繁忙");
			}
		} else if (action.equals("add")) {
			String realName = request.getParameter("realName");
			String idcardNo = request.getParameter("idcardNo");
			String loginName = request.getParameter("loginName");
			String telephone = request.getParameter("telephone");
			try {
				Account account = new Account();
				account.setRealName(realName);
				account.setIdcardNo(idcardNo);
				account.setLoginName(loginName);
				account.setStatus("0");
				account.setTelephone(telephone);
				dao.save(account);
				response.sendRedirect("list.do");
			} catch (Exception e) {
				e.printStackTrace();
				out.print("系统繁忙");
			}
		} else if (action.equals("delete")) {
			String accountId = request.getParameter("accountId");
			try {
				dao.delete(Integer.parseInt(accountId));
				response.sendRedirect("list.do");
			} catch (Exception e) {
				e.printStackTrace();
				out.print("系统繁忙");
			}
		} else if (action.equals("load")) {
			String accountId = request.getParameter("accountId");
			try {
				Account acc = dao.findById((Integer.parseInt(accountId)));
				out.println("<html><head></head><body style='font-size:30px'>");
				if (acc != null) {
					out.println("<form action='modify.do' method='post'>");
					out.println("编号:" + acc.getAccountId() + "<br>");
					out.println("<input type='hidden' name='accountId' value='"
							+ acc.getAccountId() + "'/><br>");
					out.println("姓  名:<input name='realName' value='"
							+ acc.getRealName() + "'/><br>");
					out.println("身份证:<input name='idcardNo' value='"
							+ acc.getIdcardNo() + "'/><br>");
					out.println("登录名:<input name='loginName' value='"
							+ acc.getLoginName() + "'/><br>");
					out.println("手机号:<input name='telephone' value='"
							+ acc.getTelephone() + "'/><br>");
					out.println("<input type='submit' value='修改'/>");
					out.println("</form>");
				}
				out.println("</body></html>");
			} catch (Exception e) {
				e.printStackTrace();
				out.print("系统繁忙");
			}
		} else if (action.equals("modify")) {
			String accountId = request.getParameter("accountId");
			String realName = request.getParameter("realName");
			String idcardNo = request.getParameter("idcardNo");
			String loginName = request.getParameter("loginName");
			String telephone = request.getParameter("telephone");
			try {
				Account account = new Account();
				account.setAccountId(Integer.parseInt(accountId));
				account.setRealName(realName);
				account.setIdcardNo(idcardNo);
				account.setLoginName(loginName);
				account.setTelephone(telephone);
				dao.modify(account);
				response.sendRedirect("list.do");
			} catch (Exception e) {
				e.printStackTrace();
				out.print("系统繁忙");
			}
		}
out.close();
	}

}

addAccount.html文件的代码如下所示:

<html>
	<head>
		<meta http-equiv="content-type" content="text/html;charset=utf-8">
	</head>
	<body style="font-size:24px">
		<form action="add.do" method="post">
			<fieldset>
				<legend>添加帐务帐号</legend>
				姓   名:<input name="realName"/><br>
				身份证:<input name="idcardNo"/><br>
				登录名:<input name="loginName"/><br>
				手机号:<input name="telephone"/><br>
				<input type="submit" value="添加"/>
			</fieldset>
		</form>
	</body>
</html>

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>actionServlet</servlet-name>
		<servlet-class>web.ActionServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>actionServlet</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
</web-app>

3 简述URI和URL 的区别, 如何获取 ?

参考答案

URI,是uniform resource identifier,统一资源标识符,用来唯一的标识一个资源。而URL是uniform resource locator,统一资源定位器,它是一种具体的URI,即URL可以用来标识一个资源,而且还指明了如何定位这个资源。

在Java的URI中,一个URI实例可以代表绝对的,也可以是相对的,只要它符合URI的语法规则。而URL类则不仅符合语义,还包含了定位该资源的信息,因此它不能是相对的。从HttpServletRequest的javadoc中可以看出,getRequestURI方法返回一个String,比如请求为“POST /some/path.html?a=b HTTP/1.1”,则该方法返回的值为”/some/path.html”。而getRequestURL返回一个StringBuffer,是完整的请求资源路径,不包括querystring。

4 Servlet生命周期分哪几个阶段?什么时候执行?

参考答案

Servlet生命周期分为四个阶段,依次是实例化、初始化、就绪以及销毁。

容器调用Servlet的构造器,创建一个Servlet对象。容器创建Servlet对象的时机有以下两种情形:

情形1,开始容器里面没有Servlet对象,只有收到请求后才会创建Servlet对象。

情形2,容器启动之后就立即创建相应的实例。

容器在创建好Servlet对象之后,会立即调用该对象的init方法。该方法只会执行一次。一般情况下,我们不用写init方法,因为GenericServlet已经提供了init方法的实现(将容器传递过来的ServletConfig对象保存下来,并且,提供了getServletConfig方法来获得ServletConfig对象)。

容器收到请求之后调用Servlet对象的service方法来处理请求。

容器依据自身的算法删除Servlet对象,删除前会调用destroy方法。该方法只会执行一次。可以重写destroy方法来实现自己的处理逻辑。

5 如何配置Servlet的初始参数,以及如何获取该初始参数?

参考答案

在web.xml文件中配置初始化参数,代码如下:

<init-param>
     <param-name>company</param-name>
     <param-value>北京达内</param-value>
</init-param>

可以通过ServletConfig的getInitParameter方法获取初始化参数的值:

String company=config.getInitParameter("company");

上述代码中,config是ServletConfig的引用。上述代码可以获取初始化参数company的值。

6 简述什么是Servlet上下文。

参考答案

容器启动之后,会为每一个Web应用创建唯一的一个符合ServletContext接口要求的对象,该对象就是servlet上下文。

7 Servlet是否是线程安全的,如何解决?

参考答案

Servlet存在线程安全问题。容器搜到请求之后,会启动一个线程来进行相应的处理。

默认情况下,容器只会为某个Servlet创建一个实例,如果同时有多个请求同时访问某个Servlet则肯定会有多个线程访问同一个Servlet实例。如果这些线程要修改Servlet实例的某个属性,就有可能发生线程安全问题。

可以使用synchronized对代码加锁来解决Servlet的安全问题。