Servlet+JSP实现人员新增

什么是mvc   

Controller(**Servlet)把数据封装成Model发给View显示

Model (Person)用户输入放到Model中传给Controller

View(jsp)只写for循环、颜色控制显示等,不在jsp中写业务逻辑代码

【知识点】

forward和sendRedirect都会导致浏览器收到一个响应,由于http协议规定一个请求只能对应一个响应,所以在进行forward或sendRedirect操作后,立即return,这样可以避免后面的代码再次生成响应从而导致错误


【注意】

setAttribute的使用周期  

sendRedirect和forward的选择


【PersonServlet.java】

查询和新增功能

package com.rupeng.web2;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

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

public class PersonServlet extends HttpServlet
{
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException
	{
		this.doGet(req, resp);
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException
	{
		String action = req.getParameter("action");
		if (action.equals("list"))
		{
			try
			{
				ResultSet rs = JdbcUtils
						.executeQuery("select * from T_Persons2");
				// req.setAttribute("rs", rs);
				List<Person> list = new LinkedList<Person>();
				while (rs.next())
				{
					int id = rs.getInt("Id");
					String name = rs.getString("Name");
					int age = rs.getInt("Age");

					Person p = new Person();
					p.setId(id);
					p.setName(name);
					p.setAge(age);

					list.add(p);
				}
				JdbcUtils.closeAll(rs);

				// /REsultSet等一般不要传给jsp
				req.setAttribute("persons", list);// request中的数据有效期是“当前请求”
				// jsp中就可以从request总取出"persons"的值
				
				//!!!如果逻辑是服务器处理的,那么"/"一般可以表示“项目的WebRoot根目录”
				//如果逻辑是浏览器端处理的。
				req.getRequestDispatcher("/PersonList2.jsp").forward(req, resp);
				//req.getRequestDispatcher("/PersonList2_2.jsp").forward(req, resp);
				//resp.sendRedirect("/PersonList2.jsp");
				//resp.sendRedirect("PersonList2.jsp");
				//!!!如果写成sendRedirect,那么浏览器是发出两次请求的,两次请求中的request数据不能共享
				
				// 让/PersonList2.jsp进行数据的显示
			} catch (SQLException e)
			{
				resp.getWriter().write("数据库查询错误");
			}
		}
		else if(action.equals("addnew"))
		{
			//MVC中用户不直接和JSP打交道(地址栏中不会出现jsp),JSP只是负责
			//req.getRequestDispatcher("/PersonList2.jsp").forward(req, resp);
			//之后数据的显示。用户永远直接和普通的Servlet打交道
			
			//由/PersonAddNew.jsp帮我处理吧。
			req.getRequestDispatcher("/PersonAddNew.jsp").forward(req, resp);
		}
		else if(action.equals("addnewSubmit"))
		{
			String name= req.getParameter("name");
			int age = Integer.parseInt(req.getParameter("age"));
			
			try
			{
				JdbcUtils.executeUpdate("insert into T_Persons2(Name,Age) values(?,?)", name,age);
				resp.sendRedirect("person?action=list");
			} catch (SQLException e)
			{
				req.setAttribute("msg","插入数据执行失败");//把jsp要用的数据放到reques中
				//让"/MyError.jsp"去显示数据
				req.getRequestDispatcher("/MyError.jsp").forward(req, resp);
				//resp.sendRedirect("MyError.jsp");
			}
		}
		else if(action.equals("edit"))
		{
			int id = Integer.parseInt(req.getParameter("id"));
			try
			{
				ResultSet rs = JdbcUtils.executeQuery("select * from T_Persons2 where Id=?", id);
				if(rs.next())
				{
					Person person = new Person();
					person.setId(id);
					person.setName(rs.getString("Name"));
					person.setAge(rs.getInt("Age"));
					req.setAttribute("person", person);
					req.getRequestDispatcher("/PersonEdit.jsp").forward(req, resp);
				}
				else
				{
					req.setAttribute("msg", "没有找到id="+id+"的人员");
					req.getRequestDispatcher("/MyError.jsp").forward(req, resp);
				}
				JdbcUtils.closeAll(rs);
			} catch (SQLException e)
			{
				req.setAttribute("msg", "数据查询出错");
				req.getRequestDispatcher("/MyError.jsp").forward(req, resp);
			}
		}
		else if(action.equals("editSubmit"))
		{
			int id = Integer.parseInt(req.getParameter("id"));
			String name = req.getParameter("name");
			int age = Integer.parseInt(req.getParameter("age"));
			try
			{
				JdbcUtils.executeUpdate("Update T_Persons2 set Name=?,Age=? where Id=?", 
						name,age,id);
				resp.sendRedirect("person?action=list");
			} catch (SQLException e)
			{
				req.setAttribute("msg", "保存出错");
				req.getRequestDispatcher("/MyError.jsp").forward(req, resp);
			}
		}
		else if (action.equals("delete"))
		{
			int id = Integer.parseInt(req.getParameter("id"));
			try
			{
				JdbcUtils.executeUpdate("delete from  T_Persons2 where Id=?",id);
				resp.sendRedirect("person?action=list");
			} catch (SQLException e)
			{
				req.setAttribute("msg", "删除出错");
				req.getRequestDispatcher("/MyError.jsp").forward(req, resp);
			}
		}
	}
}


【PersonList2.jsp】

显示人员列表

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="java.util.List"%>
<%@page import="com.rupeng.web2.Person"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>人员列表</title>
</head>
<body>
<p>
<a href="person?action=addnew">新增</a>
</p>
<table>
	<thead>
		<tr><td>Id</td><td>姓名</td><td>年龄</td><td>编辑</td><td>删除</td></tr>
	</thead>
	<tbody>
		<%
		List<Person> persons = (List<Person>)request.getAttribute("persons");
		for(Person person : persons)
		{
		%>
		<tr><td><%=person.getId() %></td><td><%=person.getName() %></td><td><%=person.getAge() %></td>
		<td><a href="person?action=edit&id=<%=person.getId() %>">编辑</a></td>
		<td><a href="person?action=delete&id=<%=person.getId() %>">删除</a></td>
		</tr>
		<%} %>
	</tbody>
</table>
</body>
</html>


【PersonAddNew.jsp】

显示新增人员页面


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>新增人员</title>
</head>
<body>
<form action="person" method="post">
	<input type="hidden" name="action" value="addnewSubmit"/>
	姓名:<input type="text" name="name"/>
	年龄:<input type="text" name="age"/>
	<input type="submit" value="保存"/>
</form>
</body>
</html>

【PersonEdit.jsp】


<%@ page language="java" contentType="text/html; charset=UTF-8"<span style="white-space:pre">	</span>
	import="com.rupeng.web2.Person"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>编辑</title>
</head>
<body>
<%
	Person person = (Person)request.getAttribute("person");
%>
<form action="person" method="post">
<input type="hidden" name="action" value="editSubmit"/>
<input type="hidden" name="id" value="<%=person.getId() %>"/>
姓名:<input type="text" name="name" value="<%=person.getName() %>"/>
年龄:<input type="text" name="age" value="<%=person.getAge() %>"/>
<input type="submit" value="保存"/>
</form>
</body>
</html>


【MyError.jsp】

显示错误页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>错误</title>
</head>
<body>
	 <%=request.getAttribute("msg") %>
</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">

	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	
	<error-page>
		<exception-type>java.lang.Throwable</exception-type>
		<location>/Error.jsp</location>
	</error-page>
	<error-page>
		<error-code>404</error-code>
		<location>/muyou.html</location>
	</error-page>
	 
	<servlet>
		<servlet-name>personServlet</servlet-name>
		<servlet-class>com.rupeng.web2.PersonServlet</servlet-class>
	</servlet>	
	<servlet-mapping>
		<servlet-name>personServlet</servlet-name>
		<url-pattern>/person</url-pattern>
	</servlet-mapping>
</web-app>


【Person.java】


package com.rupeng.web2;

public class Person
{
	private int id;
	private String name;
	private int age;

	public int getId()
	{
		return id;
	}

	public void setId(int id)
	{
		this.id = id;
	}

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	public int getAge()
	{
		return age;
	}

	public void setAge(int age)
	{
		this.age = age;
	}
}



其余引用【JdbcUtils.java】


  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JSP(JavaServer Pages)、Servlet和MySQL结合起来可以构建一个完整的购物商城源码。首先,JSP可以用于展示网页的静态内容和动态信息,比如商品列表、购物车等。Servlet可以处理用户请求并与后台的数据库进行交互,比如用户注册、登录和管理购物车等功能。而MySQL作为后台数据库,可以存储商品信息、用户信息和订单信息等数据。 在购物商城源码中,可以利用JSP来设计商城的界面,比如商品展示页面、购物车页面、用户登录页面等。而Servlet则负责处理用户的请求,比如处理用户登录、添加商品到购物车、生成订单等功能。同时,Servlet还负责与MySQL数据库进行交互,比如查询商品信息、更新用户信息、存储订单信息等。 在MySQL数据库中,可以设计多张表来存储不同的数据,比如商品表、用户表、订单表等。通过使用SQL语句,可以实现数据的增删改查操作。比如新增商品信息、查询用户信息、更新订单状态等操作。 综合以上三者,可以实现一个完整的购物商城源码,用户可以浏览商品、添加商品到购物车、进行结算下单等操作。同时,还可以实现用户管理功能,比如用户注册、登录、查看订单记录等。整个购物商城源码需要充分利用JSPServlet和MySQL的特点来实现用户友好的界面和高效的数据交互。通过这样的方式,可以构建一个完整的购物商城系统,满足用户的购物需求。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值