案例--编写一个Servlet,显示已有用户信息,可添加/修改、删除帐务帐号信息,并重新显示新页面

要求如下:

 帐务帐号信息表(ACCOUNT)


操作界面如下:


添加员工界面:


修改员工界面:


代码如下:

Servlet:

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.DeleteAccountDao;
import dao.FindAccountDao;
import dao.ModifyAccountDao;
import dao.addAccountDao;
import dao.findDao;
import entity.Account;

public class AccountServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse res) 
			throws ServletException, IOException {
		String path = req.getServletPath();
		if("/findAccount.acc".equals(path)){
			findAccount(req,res);
		}else if("/addAccount.acc".equals(path)){
			addAccount(req,res);
		}else if("/deleteAccount.acc".equals(path)){
			deleteAccount(req,res);
		}else if("/modifyAccount.acc".equals(path)){
			modifyAccount(req,res);
		}else{
			throw new RuntimeException("找不到此路径");
		}
	}
	//查询  /findAccount.acc
	protected void findAccount(HttpServletRequest req, HttpServletResponse res) 
			throws ServletException, IOException {
		//处理业务
		findDao dao = new FindAccountDao();
		List<Account> list = dao.findAccount();
		res.setContentType("text/html;charset=utf-8");
		PrintWriter out = res.getWriter();
		//拼写动态网页
		out.println("<table border='1' cellspacing='0' width='60%'>");
		out.println("  <caption>员工信息列表</caption>");
		out.println("  <tr>");
		out.println("<td>ID</td><td>姓名</td><td>身份证号</td><td>登录名</td><td>状态</td><td>手机号码</td><td>操作</td>");
		out.println("  </tr>");
		for(Account acc : list){
			//对状态进行判断
			String status = acc.getStatus();
			//删除时传入该account_id
			int account_id = acc.getAccount_id(); 
			if("0".equals(status)){		 //0  开通
				status = "开通";
			}else if("1".equals(status)){//1 暂停
				status = "暂停";
			}else{					     //2 删除
				status = "删除";
			}
			out.println("<tr>");
			out.println("<td>"+account_id+"</td>");
			out.println("<td>"+acc.getReal_name()+"</td>");
			out.println("<td>"+acc.getIdcard_no()+"</td>");
			out.println("<td>"+acc.getLogin_name()+"</td>");
			out.println("<td>"+status+"</td>");
			out.println("<td>"+acc.getTelephone()+"</td>");
			out.println("<td>");
			out.println("<a href='deleteAccount.acc?account_id="+account_id+"'"+
						" οnclick=\"return confirm('是否删除?');\">删除</a>  ");
			out.println("<a href='modify_account.html?account_id="+account_id+"'"+">修改</a>");
			out.println("</td>");
			out.println("</tr>");
		}
		out.println("</table>");
		out.println("<a href='add_account.html'>添加员工信息</a>");
		out.close();
	}
	
	//增加  /addAccount.acc
	protected void addAccount(HttpServletRequest req, HttpServletResponse res) 
		throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		res.setContentType("text/html;charset=utf-8");
		String real_name = req.getParameter("real_name");
		String idcard_no = req.getParameter("idcard_no");
		String login_name = req.getParameter("login_name");
		String telephone = req.getParameter("telephone");
		Account acc = new Account();
		acc.setReal_name(real_name);
		acc.setIdcard_no(idcard_no);
		acc.setLogin_name(login_name);
		acc.setTelephone(telephone);
		acc.setStatus("0");
		//新添加用户状态status为0,表示开通,ID采用序列,此时Account实例中account_id=null,在访问数据库是使用序列替换掉
		
		//处理业务,将新添加的用户加入到数据库oracle--account表中
		new addAccountDao().addAccount(acc);
		
		//重定向
		res.sendRedirect("findAccount.acc");
	}
	
	//删除  /deleteAccount.acc
	protected void deleteAccount(HttpServletRequest req, HttpServletResponse res) 
			throws ServletException, IOException {
		//接收请求参数 点击超链接为get请求
		int account_id = Integer.parseInt(req.getParameter("account_id"));
		//处理业务
		new DeleteAccountDao().deleteAccount(account_id);
		//重定向到查询页面
		res.setContentType("text/html;charset=utf-8");
		res.sendRedirect("findAccount.acc");
	}
	
	//修改  /modifyAccount.acc
	protected void modifyAccount(HttpServletRequest req, HttpServletResponse res) 
			throws ServletException, IOException {
		//接收参数,实例化为Account实例
		req.setCharacterEncoding("utf-8");
		int account_id = Integer.parseInt(req.getParameter("account_id"));
		String real_name = req.getParameter("real_name");
		String idcard_no = req.getParameter("idcard_no");
		String login_name = req.getParameter("login_name");
		String status = req.getParameter("status");
		String telephone = req.getParameter("telephone");
		Account acc = new Account();
		acc.setAccount_id(account_id);
		acc.setIdcard_no(idcard_no);
		acc.setLogin_name(login_name);
		acc.setReal_name(real_name);
		acc.setStatus(status);
		acc.setTelephone(telephone);
		//处理业务
		new ModifyAccountDao().modifyAccount(acc);
		//重定向到查询页面
		res.setContentType("text/html;charset=utf-8");
		res.sendRedirect("findAccount.acc");
	}
}

使用接口,可扩展性更好:

查询业务接口

package dao;

import java.util.List;

import entity.Account;

public interface findDao {
	List<Account> findAccount();
}
增加业务接口:

package dao;

import entity.Account;

public interface addDao {
	void addAccount(Account acc);
}

删除业务接口:

package dao;

public interface deleteDao {
	void deleteAccount(int account_id);
}

修改业务接口:

package dao;

import entity.Account;

public interface modifyDao {
	void modifyAccount(Account acc);
}

接口的实现类:

package dao;

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

import entity.Account;
import tool.DBUtil2;

public class FindAccountDao implements findDao {

	public List<Account> findAccount() {
		List<Account> list = new ArrayList<Account>();
		try{
			Connection conn = DBUtil2.getConnection();
			Statement state = conn.createStatement();
			String sql = "SELECT * FROM account ORDER BY account_id";
			ResultSet rs = state.executeQuery(sql);
			while(rs.next()){
				Account acc = new Account();
				acc.setAccount_id(rs.getInt("account_id"));
				acc.setIdcard_no(rs.getString("idcard_no"));
				acc.setLogin_name(rs.getString("login_name"));
				acc.setReal_name(rs.getString("real_name"));
				acc.setStatus(rs.getString("status"));
				acc.setTelephone(rs.getString("telephone"));
				list.add(acc);
			}
			return list;
		}catch(Exception e){
			e.printStackTrace();
			throw new RuntimeException("操作数据库失败!");
		}finally{
			DBUtil2.closeConnection();
		}
	}
	/*测试代码
	public static void main(String[] args) {
		List<Account> list = new FindAccountDao().findAccount();
		for(Account acc : list){
			System.out.println(acc.getReal_name());
		}
	}
	*/
}

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;

import entity.Account;
import tool.DBUtil2;

public class addAccountDao implements addDao {
	public void addAccount(Account acc) {
		try{
			Connection conn = DBUtil2.getConnection();
			String sql = "INSERT INTO account "
					+ "(account_id,login_name,status,real_name,idcard_no,telephone) "
					+ "VALUES "
					+ "(account_seq.nextval,?,?,?,?,?)";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, acc.getLogin_name());
			ps.setString(2, acc.getStatus());
			ps.setString(3, acc.getReal_name());
			ps.setString(4, acc.getIdcard_no());
			ps.setString(5, acc.getTelephone());
			ps.executeUpdate();
		}catch(Exception e){
			e.printStackTrace();
			throw new RuntimeException("访问数据库失败!");
		}finally{
			DBUtil2.closeConnection();
		}
	}
}
package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import tool.DBUtil2;

public class DeleteAccountDao implements deleteDao {
	public void deleteAccount(int account_id) {
		try {
			Connection conn = DBUtil2.getConnection();
			String sql = "DELETE FROM account WHERE account_id=?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setInt(1, account_id);
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("访问数据库失败!");
		} finally {
			DBUtil2.closeConnection();
		}
	}
}
package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import entity.Account;
import tool.DBUtil2;

public class ModifyAccountDao implements modifyDao {

	public void modifyAccount(Account acc) {
		try {
			Connection conn = DBUtil2.getConnection();
			String sql = "UPDATE account SET "
					+ "real_name=?,idcard_no=?,login_name=?,status=?,telephone=? "
					+ "WHERE account_id=?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, acc.getReal_name());
			ps.setString(2, acc.getIdcard_no());
			ps.setString(3, acc.getLogin_name());
			ps.setString(4, acc.getStatus());
			ps.setString(5, acc.getTelephone());
			ps.setInt(6, acc.getAccount_id());
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("访问数据库失败!");
		} finally{
			DBUtil2.closeConnection();
		}
	}

}

表单静态页面:

添加信息:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>增加员工</title>
</head>
<body>
  <form action="addAccount.acc" method="post">
    <fieldset>
      <legend>添加账务账号</legend>
      <p>姓   名:<input type="text" name="real_name"/></p>
      <p>身份证:<input type="text" name="idcard_no"/></p>             
      <p>登录名:<input type="text" name="login_name"/></p>             
      <p>手机号:<input type="text" name="telephone"/></p>             
      <p><input type="submit" value="添加"/></p> 
    </fieldset>
  </form>
  <p><b>注意:</b>status为状态,当添加进入列表后就为开通状态status=0,ID使用序列的方式插入,一共六个字段,次数自需要获取其余4个字段即可</p>
</body>
</html>

修改信息:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>增加员工</title>
<script type="text/javascript" src="js/jquery-1.11.1.js"></script>
<script type="text/javascript">
  $(function(){
	//获取当前浏览器的路径
	var path = window.location.search;
	console.log(path);
	console.log(typeof(path));
	//获取参数
	path = path.split("=")[1];
	$("input:eq(0)").val(path); 
  });
</script>
</head>
<body>
  <form action="modifyAccount.acc" method="post">
    <fieldset>
      <legend>修改账务账号</legend>
      <p>I      D:<input type="text" name="account_id" value="" readonly/></p>
      <p>姓   名:<input type="text" name="real_name"/></p>
      <p>身份证:<input type="text" name="idcard_no"/></p>             
      <p>登录名:<input type="text" name="login_name"/></p>             
      <p>状   态:<input type="text" name="status"/></p>             
      <p>手机号:<input type="text" name="telephone"/></p>             
      <p><input type="submit" value="提交"/></p> 
    </fieldset>
  </form>
  <p><b>注意:</b>account_id为点击时自动获取的,不可更改,一共六个字段,只需要获取其余5个字段即可</p>
</body>
</html>

web.xml配置文件:

<servlet>
    <servlet-name>account</servlet-name>
    <servlet-class>web.AccountServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>account</servlet-name>
    <url-pattern>*.acc</url-pattern>
  </servlet-mapping>
总结:在jQuery中通过window.location.search可以获取到浏览器中的请求路径




  • 1
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
首先,需要确保你已经安装了Eclipse和Java EE插件。接下来,按照以下步骤进行操作: 1. 创建一个动态Web项目。选择File > New > Dynamic Web Project,输入项目名称,选择Target runtime,点击Next。 2. 添加JDBC驱动程序。将JDBC驱动程序添加到Web项目中的lib目录中。 3. 创建一个JSP页面。选择File > New > JSP File,输入文件名称,选择创建位置,点击Finish。 4. 在JSP页面中添加HTML表单元素,包括商品名称、价格、描述等。 5. 创建一个Java Servlet类。选择File > New > Servlet,输入Servlet名称和URL映射,点击Next。 6. 在Servlet类中编写代码,将表单数据插入数据库中,并将新添加的商品信息显示在JSP页面上。 7. 在web.xml文件中配置Servlet类的映射。 8. 运行Web应用程序。 以下是一个简单的示例代码,用于添加商品到数据库并显示添加的商品信息: JSP页面(addProduct.jsp): ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Add Product</title> </head> <body> <h1>Add Product</h1> <form action="AddProductServlet" method="post"> <label for="name">Product Name:</label> <input type="text" id="name" name="name"><br><br> <label for="price">Price:</label> <input type="text" id="price" name="price"><br><br> <label for="description">Description:</label> <textarea id="description" name="description"></textarea><br><br> <input type="submit" value="Add Product"> </form> </body> </html> ``` Servlet类(AddProductServlet.java): ```java import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/AddProductServlet") public class AddProductServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); String price = request.getParameter("price"); String description = request.getParameter("description"); Connection conn = null; PreparedStatement stmt = null; try { // 连接数据库 Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "password"); // 插入商品信息到数据库 String sql = "INSERT INTO products (name, price, description) VALUES (?, ?, ?)"; stmt = conn.prepareStatement(sql); stmt.setString(1, name); stmt.setString(2, price); stmt.setString(3, description); stmt.executeUpdate(); // 查询新添加的商品信息 sql = "SELECT * FROM products WHERE name=?"; stmt = conn.prepareStatement(sql); stmt.setString(1, name); ResultSet rs = stmt.executeQuery(); rs.next(); // 将商品信息传递到JSP页面并显示 request.setAttribute("product", rs); request.getRequestDispatcher("product.jsp").forward(request, response); } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); } finally { try { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } ``` JSP页面(product.jsp): ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Product</title> </head> <body> <h1>Product Information</h1> <table> <tr> <td>Name:</td> <td><%= request.getAttribute("product").getString("name") %></td> </tr> <tr> <td>Price:</td> <td><%= request.getAttribute("product").getString("price") %></td> </tr> <tr> <td>Description:</td> <td><%= request.getAttribute("product").getString("description") %></td> </tr> </table> </body> </html> ``` 注意:上述示例代码仅供参考,实际应用中需要根据具体情况进行修改和调整。同时,需要确保数据库连接信息正确,并且在Web项目的lib目录中导入正确的JDBC驱动程序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

荒--

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值