how2j.cn

-->
下载区
文件名 文件大小
j2ee.rar 525k

解压rar如果失败,请用5.21版本或者更高版本的winrar

点击下载 winrar5.21
步骤 1 : 先运行,看到效果,再学习   
步骤 2 : 模仿和排错   
步骤 3 : 编写 HeroUpdateServlet   
步骤 4 : 配置web.xml   

步骤 1 :

先运行,看到效果,再学习

edit
老规矩,先下载右上角的可运行项目,配置运行起来,确认可用之后,再学习做了哪些步骤以达到这样的效果。
在确保可运行项目能够正确无误地运行之后,再严格照着教程的步骤,对代码模仿一遍。
模仿过程难免代码有出入,导致无法得到期望的运行结果,此时此刻通过比较正确答案 ( 可运行项目 ) 和自己的代码,来定位问题所在。
采用这种方式,学习有效果,排错有效率,可以较为明显地提升学习速度,跨过学习路上的各个槛。

推荐使用diffmerge软件,进行文件夹比较。把你自己做的项目文件夹,和我的可运行项目文件夹进行比较。
这个软件很牛逼的,可以知道文件夹里哪两个文件不对,并且很明显地标记出来
这里提供了绿色安装和使用教程:diffmerge 下载和使用教程
步骤 3 :

编写 HeroUpdateServlet

edit
HeroUpdateServlet
根据浏览器提交的id name hp damage创建一个Hero对象
然后调用HeroDAO的update,进行更新

更新结束后,客户端跳转到 /listHero
package servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import bean.Hero; import dao.HeroDAO; public class HeroUpdateServlet extends HttpServlet { protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); Hero hero = new Hero(); hero.setId(Integer.parseInt(request.getParameter("id"))); hero.setName(request.getParameter("name")); hero.setHp(Float.parseFloat(request.getParameter("hp"))); hero.setDamage(Integer.parseInt(request.getParameter("damage"))); new HeroDAO().update(hero); response.sendRedirect("/listHero"); } }
新增对路径 /updateHero的映射
<?xml version="1.0" encoding="UTF-8"?> <web-app> <servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>HelloServlet</servlet-class> <load-on-startup>10</load-on-startup> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping> <servlet> <servlet-name>RegisterServlet</servlet-name> <servlet-class>RegisterServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>RegisterServlet</servlet-name> <url-pattern>/register</url-pattern> </servlet-mapping> <servlet> <servlet-name>HeroListServlet</servlet-name> <servlet-class>servlet.HeroListServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HeroListServlet</servlet-name> <url-pattern>/listHero</url-pattern> </servlet-mapping> <servlet> <servlet-name>HeroAddServlet</servlet-name> <servlet-class>servlet.HeroAddServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HeroAddServlet</servlet-name> <url-pattern>/addHero</url-pattern> </servlet-mapping> <servlet> <servlet-name>HeroDeleteServlet</servlet-name> <servlet-class>servlet.HeroDeleteServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HeroDeleteServlet</servlet-name> <url-pattern>/deleteHero</url-pattern> </servlet-mapping> <servlet> <servlet-name>HeroEditServlet</servlet-name> <servlet-class>servlet.HeroEditServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HeroEditServlet</servlet-name> <url-pattern>/editHero</url-pattern> </servlet-mapping> <servlet> <servlet-name>HeroUpdateServlet</servlet-name> <servlet-class>servlet.HeroUpdateServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HeroUpdateServlet</servlet-name> <url-pattern>/updateHero</url-pattern> </servlet-mapping> </web-app>


HOW2J公众号,关注后实时获知最新的教程和优惠活动,谢谢。


问答区域    
2024-08-03 借助 DAO 的思想,利用 Tomcat 和 Servlet 实现 Mysql 的 CRUD 操作+前端 Html
虚心求学

关于 J2EE-Servlet-更新 的提问



前端:addHero.html、editHero.html 后端:HeroSevlet(查询主表)、AddHeroServlet、DeleteHeroServlet、EditHeroServlet、UpdateServlet、HeroDAO 简化代码,避免频繁请求连接 connection,避免冗长的 声明 PreparedStatement 以及冗长的设置参数的代码。 使用一个 query 方法 封装所有的 CRUD 操作,以提高代码复用率。 由于 反射机制 学的不是很深入,就采用了较为简单的判断方法来设置参数。 具体如下: 使用懒汉单例模式构建 HeroDAO 类,因为我觉得不应该提供多个 Connection , 毕竟暂时还未考虑多线程和并发,既避免 多个 Connection 容易形成的错误, 又减轻了访问数据库的压力和资源占用,还可以复用同一个 Connection。 query 方法 用于访问数据库,需要提供字符串参数 sql 语句,可选择的 Object 参数。 采用 PreparedStatement ,并结合 try-with-resource 的方法,调用完就关闭资源。 但是,Connection 不能使用 try-with-catch ,因为后续 DAO 都复用这个唯一连接。 所有的 PreparedStatement 的参数设置都封装在一个方法内, 通过 query ( String sql,Object...params ) 来通用所有的参数类型, 根据 sql语句与指定的参数,访问数据库并执行增删改查操作。 * @param sql 为数据操作所执行的 sql 语句 * @param objs 参数,如果为 Hero 对象,则默认设置 Hero 除 id 以外的所有属性, * 可以另外提供 hero.id 参数作为输入, * 如果为基本数据则设置相应的参数,类型:Integer、Float,其他皆按照 Double设置 * 如果为String对象,则设置字符串参数。 * 不提供参数,则不进行设置,直接执行 sql 语句。 * @return 如果为查询操作,则以 LinkList 形式返回查询结果,否则返回 null
加载中
个人认为,核心是 HeroDAO。
nodejs下载:npm install gxdao

前端:

--------------------------- addHero.html  ------------------------------------

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

		<style>
		input{
			width:100px;
			margin:5px;
		}
		div{
			float:left;
			width:80px;
			text-align:right;

		}
		form{
			border:1px solid lightSkyBlue;
			margin:50px;
			width:190px;
			padding:5px;
			float:left;
		}
		input.fright{
			float:right;
			margin-top:10px;
		}
		</style>

		<script>
		function checkEmpty(){
			let is = document.getElementsByTagName('input');
			for(const i of is){
				let value = i.value;
				if(!value||value.trim()==""){
					let name = i.previousElementSibling.innerText;
					showMsg(name+"\r\n不允许为空",'red');
					return false;
				}
			}
			return true;
		}
		function check(sender,e){
			if(e!=null&&e.key=='Backspace')return true;
			let value = sender.value.trim();
			if(Number.isNaN((Number)(value))){
				let name = sender.previousElementSibling.innerText;
				showMsg(name+"\r\n请输入整数",'red');
				let num = parseFloat(value);
				sender.value =  Number.isNaN(num)?"":num;
				return false;
			}
			return true;
		}
		function showMsg(text,color){
			let msg = document.getElementById('msg');
			msg.style.display="inline";
			msg.style.color=color;
			msg.innerText = text;
		}
		function hideMsg(){
			let msg = document.getElementById('msg');
			msg.style.display="none";
		}
		function clearWhen(sender){
			let value = sender.value.trim();
			if(Number.isNaN((Number)(value))){
				let name = sender.previousElementSibling.innerText;
				showMsg(name+"\r\n请输入整数",'red');
				let num = parseFloat(value);
				sender.value =  Number.isNaN(num)?"":num;
				return false;
			}
			return true;
		}
		function jumpTo(){
			window.location.href="/j2ee/hero"
		}
		</script>
	</head>
	<body>
		<form action="addHero" method="post">
			<div>name:</div><input name="name"  placeholder="输入英雄名称" type="text"><br/>
			<div>hp:</div><input onblur="clearWhen(this)" onkeydown="return check(this,event)" name="hp" placeholder="输入 HP " type="text"><br/>
			<div>damage:</div><input onblur="clearWhen(this)" onkeydown="return check(this,event)" name = "damage" placeholder="输入伤害值" type="text">
			<div style="display:none;text-align:center" id="msg"></div>
			<input type="submit" onclick="return checkEmpty()" value="添加" class="fright">
			<input type='button' onclick='jumpTo()'  value='取消'  class='fright'>
		</form>
		
	</body>

</html>

--------------------------- editHero.html  ------------------------------------

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

		<style>
		input{
			width:100px;
			margin:5px;
		}
		div{
			float:left;
			width:80px;
			text-align:right;

		}
		form{
			border:1px solid lightSkyBlue;
			margin:50px;
			width:190px;
			padding:5px;
			float:left;
		}
		input.fright{
			float:right;
			margin-top:10px;
		}
		</style>

		<script>
		function checkEmpty(){
			let is = document.getElementsByTagName('input');
			for(const i of is){
				let value = i.value;
				if(!value||value.trim()==''){
					let name = i.previousElementSibling.innerText;
					showMsg(name+'\r\n不允许为空','red');
					return false;
				}
			}
			return true;
		}
		function check(sender,e){
			if(e!=null&&e.key=='Backspace')return true;
			let value = sender.value.trim();
			if(Number.isNaN((Number)(value))){
				let name = sender.previousElementSibling.innerText;
				showMsg(name+'\r\n请输入整数','red');
				let num = parseFloat(value);
				sender.value =  Number.isNaN(num)?'':num;
				return false;
			}
			return true;
		}
		function showMsg(text,color){
			let msg = document.getElementById('msg');
			msg.style.display='inline';
			msg.style.color=color;
			msg.innerText = text;
		}
		function hideMsg(){
			let msg = document.getElementById('msg');
			msg.style.display='none';
		}
		function clearWhen(sender){
			let value = sender.value.trim();
			if(Number.isNaN((Number)(value))){
				let name = sender.previousElementSibling.innerText;
				showMsg(name+'\r\n请输入整数','red');
				let num = parseFloat(value);
				sender.value =  Number.isNaN(num)?'':num;
				return false;
			}
			return true;
		}
		function jumpTo(){
			window.location.href="/j2ee/hero"
		}
		</script>
	</head>
	<body>
		<form action='updateHero' method='post'>
			<input value="%d" name='id' type="hidden">
			<div>name:</div><input value="%s" name='name'  placeholder='输入英雄名称' type='text'><br/>
			<div>hp:</div><input value="%f" onblur='clearWhen(this)' onkeydown='return check(this,event)' name='hp' placeholder='输入 HP ' type='text'><br/>
			<div>damage:</div><input value="%d" onblur='clearWhen(this)' onkeydown='return check(this,event)' name = 'damage' placeholder='输入伤害值' type='text'>
			<div style='display:none;text-align:center' id='msg'></div>
			<input type='submit' onclick='return checkEmpty()' value='更新' class='fright'>
			<input type='button' onclick='jumpTo()' value='取消' class='fright'>
		</form>
		
	</body>
	<script></script>
</html>

后端:
servlet:

--------------------------- AddHeroServlet.java  ------------------------------------

import java.io.IOException;

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

import bean.Hero;
import dao.HeroDAO;

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

	public void doPost(HttpServletRequest request,HttpServletResponse response){
		try {
			request.setCharacterEncoding("UTF-8");
			String name = request.getParameter("name");
			float hp = Float.parseFloat(request.getParameter("hp"));
			int damage = Integer.parseInt(request.getParameter("damage"));
			Hero hero = new Hero(name,hp,damage);
			HeroDAO dao = HeroDAO.getInstance();
			dao.insert(hero);
			response.sendRedirect("/j2ee/hero");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}


--------------------------- DeleteHeroServlet.java  ------------------------------------

import java.io.IOException;

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

import dao.HeroDAO;

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

	public void doGet(HttpServletRequest request,HttpServletResponse response){
		int id = Integer.parseInt(request.getParameter("id"));
		HeroDAO dao = HeroDAO.getInstance();
		dao.delete(id);
		try {
			response.sendRedirect("/j2ee/hero");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

--------------------------- EditHeroServlet.java  ------------------------------------

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

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

import bean.Hero;
import dao.HeroDAO;

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

	public void doGet(HttpServletRequest request,HttpServletResponse response){
		int id = Integer.parseInt(request.getParameter("id"));
		HeroDAO dao = HeroDAO.getInstance();
		Hero h = dao.select(id);		
		String path = request.getServletContext().getRealPath("editHero.html");
		String html = readHTML(path);
		html = String.format(html,h.id, h.name,h.hp,h.damage);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		try {
			response.getWriter().write(html);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	private String readHTML(String path){
		File f = new File(path);
		StringBuffer sb = new StringBuffer();
		try(FileInputStream fis = new FileInputStream(f);
				InputStreamReader in = new InputStreamReader(fis,StandardCharsets.UTF_8);
				BufferedReader reader = new BufferedReader(in)
				){
			String line = "";
			while((line=reader.readLine())!=null){
				sb.append(line+"\r\n");
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
	
}


--------------------------- HeroServlet.java ------------------------------------

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

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

import bean.Hero;
import dao.HeroDAO;


public class HeroServlet extends HttpServlet{
	//默认值
	private static final long serialVersionUID = 1L;
	
	public void doGet(HttpServletRequest request,HttpServletResponse response){
		//获取 HeroDAO 实例,以访问数据库执行增删改查操作
		HeroDAO dao = HeroDAO.getInstance();
		//testCRUD(dao);
		List<Hero>heros = dao.selectAll();
		//写入表格元素
		String table = "<style>td{padding:5px;}a{text-decoration:none}</style><a href='/j2ee/addHero.html'>添加</a><table border='1' style='text-align:center;border-collapse:collapse'>%s</table>";
		StringBuffer trs = new StringBuffer();
		String title = "<tr style='font-weight:bold'><td>id</td><td>name</td><td>hp</td><td>damage</td><td>edit</td><td>delete</td></tr>\r\n";
		String row = "<tr><td>%d</td><td>%s</td><td>%.2f</td><td>%d</td><td><a href='/j2ee/editHero?id=%d'>edit</a></td><td><a href='/j2ee/deleteHero?id=%d'>delete</a></td></tr>%n";
		trs.append(title);
		for (Hero hero : heros) {
			String tr = String.format(row, hero.id,hero.name,hero.hp,hero.damage,hero.id,hero.id);
			trs.append(tr);
		}
		String html = String.format(table, trs);
		try {
			//此处不指定 html 格式,写到浏览器的就是纯文本的内容
			response.setContentType("text/html");
			response.setCharacterEncoding("UTF-8");
			response.getWriter().write(html);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@SuppressWarnings("unused")
	private void testCRUD(HeroDAO dao){
		Hero h = new Hero("DAO 添加的hero",123,123);
		dao.insert(h);
		h.name+="(被更新)";
		h.id = 106;
		dao.update(h);
		dao.delete(100);
		System.out.println(dao.select(105));
		System.out.println(dao.list(100,105));
	}
}


--------------------- UpdateHeroServlet.java  -------------------------

import java.io.IOException;

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

import bean.Hero;
import dao.HeroDAO;

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

	public void doPost(HttpServletRequest request,HttpServletResponse response){
		try {
			request.setCharacterEncoding("UTF-8");
			String name = request.getParameter("name");
			int id = Integer.parseInt(request.getParameter("id"));
			float hp = Float.parseFloat(request.getParameter("hp"));
			int damage = Integer.parseInt(request.getParameter("damage"));
			Hero hero = new Hero(id,name,hp,damage);
			HeroDAO dao = HeroDAO.getInstance();
			dao.update(hero);
			response.sendRedirect("/j2ee/hero");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

DAO:

--------------------------- HeroDAO.java  ------------------------------------



package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import bean.Hero;

/**
 * 基于单例模式,服务于  Hero 对象 的 DAO (Database Access Object,DAO) 类,
 * 方便 hero 对象与数据库间的 增删改查 操作。
 * @author W G X
 *
 */
public class HeroDAO {
	private Connection connection;
	private String db = "how2java";
	private String username = "root";
	private String password = "admin";
	private int port = 3306;
	private static  HeroDAO instance = null;
	//懒汉单例模式,仅提供一个唯一的 Connection 
	public static HeroDAO getInstance(){
		if(instance == null){
			instance = new HeroDAO();
		}
		return instance;
	}
	private HeroDAO(){
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		String url = String.format("jdbc:mysql://127.0.0.1:%d/%s?characterEncoding=UTF-8", port,db);
		try {
			this.connection = DriverManager.getConnection(url,username,password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	public void insert(Hero h){
		String sql = "insert into hero values(null,?,?,?)";
		query(sql,h);
	}
	public void delete(int id){
		String sql = "delete from Hero where id = ?";
		query(sql,id);
	}
	public void update(Hero h){
		String sql = "update hero set name = ?,hp = ?,damage = ? where id = ?";
		query(sql,h,h.id);
	}
	public Hero select(int id){
		String sql = "select * from hero where id = ?";
		LinkedList<Hero> list = query(sql,id);
		if(!list.isEmpty()){
			return list.peek();
		}
		return null;
	}
	public List<Hero> selectAll(){
		String sql = "select * from hero orderBy order by id desc";
		List<Hero>list = query(sql);
		return list;
	}
	public List<Hero> list(){
		return list(0,Short.MAX_VALUE);
	}
	public List<Hero> list(int begin,int end){
		String sql = "select * from hero order by id desc limit ?,?";
		return query(sql,begin,end);
	}
	public int count(){
		return selectAll().size();
	}
	//完全清空 hero 表格,并置零 generate key;
	public void clear(){
		String sql = "TRUNCATE TABLE hero";
		query(sql);
	}
	/**
	 * 核心方法:
	 * 根据 sql语句与指定的参数,访问数据库并执行增删改查操作。
	 * @param sql 为数据操作所执行的 sql 语句
	 * @param objs 参数,如果为 Hero 对象,则默认设置 Hero 除 id 以外的所有属性,
	 * 可以另外提供 hero.id 参数作为输入,
	 * 如果为基本数据则设置相应的参数,类型:Integer、Float,其他皆按照 Double设置
	 * 如果为String对象,则设置字符串参数。
	 * 不提供参数,则不进行设置,直接执行 sql 语句。
	 * @return 如果为查询操作,则以 LinkList 形式返回查询结果,否则返回 null
	 */
	public LinkedList<Hero> query(String sql,Object...parms){
		try(PreparedStatement ps = this.connection.prepareStatement(sql)){
			//设置参数
			int paramKey = 1;
			for (Object obj : parms) {
				if(obj == null)continue;
				if(obj instanceof Hero){
					Hero hero = (Hero)obj;
					ps.setString(paramKey++, hero.name);
					ps.setFloat(paramKey++, hero.hp);
					ps.setInt(paramKey++, hero.damage);
				}else if(obj instanceof Integer){
					ps.setInt(paramKey++,(int)obj);
					continue;
				}
				else if(obj instanceof Float){
					ps.setFloat(paramKey++, ((Number)obj).floatValue());
					continue;
				}else if(obj instanceof Number){
					ps.setDouble(paramKey++, ((Number)obj).doubleValue());
					continue;
				}
				else if(obj instanceof String){
					ps.setString(paramKey++, (String)obj);
				}
			}
			//执行SQl
			boolean HasResult = ps.execute();
			//如果为查询操作,获得返回值
			if(HasResult){
				ResultSet set = ps.getResultSet();
				LinkedList<Hero>heros = new LinkedList<Hero>();
				while(set.next()){
					int id = set.getInt("id");
					String name = set.getString("name");
					float hp = set.getFloat("hp");
					int damage = set.getInt("damage");
					Hero hero = new Hero(id,name,hp,damage);
					heros.add(hero);
				}
				return heros;
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
}

bean:
--------------------------- Hero.java  ------------------------------------

package bean;

public class Hero {
	public int id;
	public String name;
	public float hp;
	public int damage;
	public Hero(String name,float hp,int damage){
		this.name = name;
		this.hp = hp;
		this.damage = damage;
	}
	public Hero(int id,String name,float hp,int damage){
		this(name,hp,damage);
		this.id = id;
	}
	public Hero(){
		
	}
	public int getId(){
		return this.id;
	}
	public void setId(int id){
		this.id = id;
	}
	public String getName(){
		return this.name;
	}
	public void setName(String name){
		this.name = name;
	}
	public float getHp(){
		return this.hp;
	}
	public void setHp(float hp){
		this.hp = hp;
	}
	public int getDamage(){
		return this.damage;
	}
	public void setDamage(int damage){
		this.damage = damage;
	}
	@Override
	public String toString(){
		return String.format("%d\t%s\t%.2f\t%d",id,name,hp,damage);
	}
}

xml:
--------------------------- web.xml  ------------------------------------

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
	
	<servlet>
		<servlet-name>HelloServlet</servlet-name>
		<servlet-class>HelloServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>HelloServlet</servlet-name>
		
		<url-pattern>/hello</url-pattern>
	</servlet-mapping>
	
	<servlet>
		<servlet-name>HeroServlet</servlet-name>
		<servlet-class>HeroServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>HeroServlet</servlet-name>
		
		<url-pattern>/hero</url-pattern>
	</servlet-mapping>
	
	<servlet>
		<servlet-name>AddHeroServlet</servlet-name>
		<servlet-class>AddHeroServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>AddHeroServlet</servlet-name>
		
		<url-pattern>/addHero</url-pattern>
	</servlet-mapping>
	
	<servlet>
		<servlet-name>DeleteHeroServlet</servlet-name>
		<servlet-class>DeleteHeroServlet</servlet-class>
	</servlet>
	<servlet-mapping>
	<servlet-name>DeleteHeroServlet</servlet-name>
		<url-pattern>/deleteHero</url-pattern>
	</servlet-mapping>
	
	<servlet>
		<servlet-name>EditHeroServlet</servlet-name>
		<servlet-class>EditHeroServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>EditHeroServlet</servlet-name>
		
		<url-pattern>/editHero</url-pattern>
	</servlet-mapping>
	
	<servlet>
		<servlet-name>UpdateHeroServlet</servlet-name>
		<servlet-class>UpdateHeroServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>UpdateHeroServlet</servlet-name>
		
		<url-pattern>/updateHero</url-pattern>
	</servlet-mapping>
</web-app>

							





回答已经提交成功,正在审核。 请于 我的回答 处查看回答记录,谢谢
答案 或者 代码至少填写一项, 如果是自己有问题,请重新提问,否则站长有可能看不到





2019-05-28 关于HeroAddServlet和HeroUpdateServlet这两个类都有重定向时的问题
genglong

关于 J2EE-Servlet-更新 的提问
这两个类都有重定向,那为什么更新按钮按下后,会去执行HeroUpdateServlet? 是因为web文件夹下面有addHero.html所以HeroAddServlet只和addHero.html的增加按钮联系吗?




1 个答案

取个名字真难
答案时间:2019-09-10
因为在上一讲的表单中action=updateHero,而updateHero在 web.xml中对应的是HeroUpdateServlet
format.append("<form action='updateHero' method='post'>");



回答已经提交成功,正在审核。 请于 我的回答 处查看回答记录,谢谢
答案 或者 代码至少填写一项, 如果是自己有问题,请重新提问,否则站长有可能看不到




2019-03-12 一个小坑
2019-02-21 如果在其他人的电脑上,怎么通过浏览器访问这些网页啊
2018-08-31 点了提交后数据没变 然后我就把站长的代码全部复制上去了 还是不行 后来我发现我就是个傻子


提问太多,页面渲染太慢,为了加快渲染速度,本页最多只显示几条提问。还有 4 条以前的提问,请 点击查看

提问之前请登陆
提问已经提交成功,正在审核。 请于 我的提问 处查看提问记录,谢谢
关于 J2EE-Servlet-更新 的提问

尽量提供截图代码异常信息,有助于分析和解决问题。 也可进本站QQ群交流: 578362961
提问尽量提供完整的代码,环境描述,越是有利于问题的重现,您的问题越能更快得到解答。
对教程中代码有疑问,请提供是哪个步骤,哪一行有疑问,这样便于快速定位问题,提高问题得到解答的速度
在已经存在的几千个提问里,有相当大的比例,是因为使用了和站长不同版本的开发环境导致的,比如 jdk, eclpise, idea, mysql,tomcat 等等软件的版本不一致。
请使用和站长一样的版本,可以节约自己大量的学习时间。 站长把教学中用的软件版本整理了,都统一放在了这里, 方便大家下载: https://how2j.cn/k/helloworld/helloworld-version/1718.html

上传截图