本文主要是介绍mysql+jsp+servlet 增删改查实例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
采用简单的MVC设计模式,M(模型层) -> Address.java 里面包含id,name,street,city,state,zip 等相关属性和set,get方法
V(视图层) -> 主要指jsp页面,包含list.jsp,add.jsp,edit.jsp
C(控制层) -> 这里只用一个servlet实现其增删改查(简单明了,方便理解),并没有用业务层的那套 service+serviceImp
项目目录:
相关的mysql数据库代码:
create database addr;
use addr;
create table address(
id int primary key auto_increment,
name varchar(20),
street varchar(20),
city varchar(20),
state varchar(20),
zip varchar(20)
);
insert into address(name,street,city,state,zip) values ('AAA','永宁街','西安','aa','1101');
insert into address(name,street,city,state,zip) values ('BBB','嘉定街','上海','bb','1102');
insert into address(name,street,city,state,zip) values ('CCC','福寿街','天津','cc','1103');
insert into address(name,street,city,state,zip) values ('DDD','回民街','北京','dd','1104');
insert into address(name,street,city,state,zip) values ('EEE','健康街','武汉','ee','1105');
根据数据库表,我们首先创建一个实体(domain)类:Address.java, 。这里我们就不贴图展示了
然后创建JdbcUtil.java 主要用来连接mysql数据库:
public class JdbcUtil {
static{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException{
String dbUrl="jdbc:mysql://localhost:3306/addr?useUnicode=true&characterEncoding=utf8";
String dbUser="root";
String dbPassword="1101";
return DriverManager.getConnection(dbUrl,dbUser,dbPassword);
}
public static void close(Statement stmt,Connection conn) throws SQLException{
stmt.close();
conn.close();
}
}
当然代码JdbcUtil的代码可进行适当优化
注意:要修改成你们mysql的用户名和密码,
Dao层(数据访问层)代码编写
public class AddressDao {
//增加
public void add(Address address){
try {
Connection conn = JdbcUtil.getConnection();
PreparedStatement pstmt = conn.prepareStatement("insert into address(name,street,city,state,zip) values(?,?,?,?,?)");
pstmt.setString(1,address.getName());
pstmt.setString(2,address.getStreet());
pstmt.setString(3,address.getCity());
pstmt.setString(4,address.getState() );
pstmt.setString(5,address.getZip() );
pstmt.executeUpdate();
JdbcUtil.close(pstmt, conn);
} catch (SQLException e) {
e.printStackTrace();
}
}
//删除
public void delete(int id){
try{
Connection conn = JdbcUtil.getConnection();
PreparedStatement pstmt = conn.prepareStatement("delete from address where id = ?");
pstmt.setInt(1, id);
pstmt.executeUpdate();
JdbcUtil.close(pstmt, conn);
}catch(SQLException e){
e.printStackTrace();
throw new RuntimeException();
}
}
//修改
public void update(Address address){
try {
Connection conn = JdbcUtil.getConnection();
PreparedStatement pstmt = conn.prepareStatement("update address set name = ?,street = ?,city =? ,state =?,zip= ? where id = ?");
pstmt.setInt(6, address.getId());
pstmt.setString(1,address.getName());
pstmt.setString(2,address.getStreet());
pstmt.setString(3,address.getCity());
pstmt.setString(4,address.getState());
pstmt.setString(5,address.getZip());
pstmt.executeUpdate();
JdbcUtil.close(pstmt, conn);
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
//查询
public List<Address> findAll(){
List<Address> list = new ArrayList<Address>();
try{
Connection conn = JdbcUtil.getConnection();
PreparedStatement pstmt = conn.prepareStatement("select * from address");
ResultSet rs = pstmt.executeQuery();
while(rs.next()){
Address address = new Address();
address.setId(rs.getInt(1));
address.setCity(rs.getString(4));
address.setStreet(rs.getString(3));
address.setState(rs.getString(5));
address.setName(rs.getString(2));
address.setZip(rs.getString(6));
list.add(address);
}
JdbcUtil.close(pstmt, conn);
}catch(SQLException e){
e.printStackTrace();
throw new RuntimeException();
}
return list;
}
//根据id查询
public Address findById(int id){
Address address = new Address();
try{
Connection conn = JdbcUtil.getConnection();
PreparedStatement pstmt = conn.prepareStatement("select * from address where id="+id);
ResultSet rs = pstmt.executeQuery();
if(rs.next()){
address.setId(rs.getInt(1));
address.setCity(rs.getString(4));
address.setStreet(rs.getString(3));
address.setState(rs.getString(5));
address.setName(rs.getString(2));
address.setZip(rs.getString(6));
}
JdbcUtil.close(pstmt, conn);
}catch(SQLException e){
e.printStackTrace();
throw new RuntimeException();
}
return address;
}
}
servlet代码编写
public class AddressServlet extends HttpServlet {
// 注入dao
private AddressDao addressDao = new AddressDao();
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置编码,很重要,否则页面提交,中文会出现乱码
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("utf-8");
//设置路径
String path = "list.jsp";
String method = request.getParameter("method");
//若请求的url有list
if (("list").equals(method)) {
List<Address> list = addressDao.findAll();
request.setAttribute("list", list);
}
else if (method.equals("add")) {
//注入Address实体类
Address address = new Address();
//获取参数
String name = request.getParameter("name");
String street = request.getParameter("street");
String city = request.getParameter("city");
String state = request.getParameter("state");
String zip = request.getParameter("zip");
//设置增加的属性
address.setName(name);
address.setStreet(street);
address.setCity(city);
address.setState(state);
address.setZip(zip);
addressDao.add(address);
<!--把新加入的数据重新加载
这点特别重要,否则刷新页面会报空指针异常
-->
path = "AddressServlet?method=list";
}
else if (method.equals("delete")) {
//根据id来删除
int id = Integer.parseInt(request.getParameter("id"));
addressDao.delete(id);
//要重新查询一遍,否则会报空指针
path = "AddressServlet?method=list";
}
//跳转编辑页面url请求如下:
else if (method.equals("toedit")) {
int id = Integer.parseInt(request.getParameter("id"));
Address address = addressDao.findById(id);
path = "edit.jsp";
request.setAttribute("address", address);
}
else if (method.equals("edit")) {
//根据id修改
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
String street = request.getParameter("street");
String city = request.getParameter("city");
String state = request.getParameter("state");
String zip = request.getParameter("zip");
Address address = new Address();
address.setId(id);
address.setName(name);
address.setStreet(street);
address.setCity(city);
address.setState(state);
address.setZip(zip);
addressDao.update(address);
//把新加入的数据重新加载
path = "AddressServlet?method=list";
}
request.getRequestDispatcher(path).forward(request, response);
}
add.jsp页面
<form action="AddressServlet?method=add" method="post">
Name:<input type="text" name="name"/><br>
Street:<input type="text" name="street"/><br>
City:<input type="text" name="city"/><br>
State:<input type="text" name="state"/><br>
Zip:<input type="text" name="zip"/><br>
<input type="submit" name="add"/><br>
</form>
edit.jsp页面
//获取request中的address对象
<% Address address = (Address)request.getAttribute("address"); %>
<form action="AddressServlet?method=edit" method="post">
<input type="hidden" name="id"value="<%=address.getId()%>"><br>
Name:<input type="text" name="name" value="<%=address.getName()%>"><br>
Street:<input type="text" name="street" value="<%=address.getStreet()%>"><br>
City:<input type="text" name="city" value="<%=address.getCity()%>"><br>
State:<input type="text" name="state" value="<%=address.getState()%>"><br>
Zip:<input type="text" name="zip" value="<%=address.getZip()%>"><br>
<input type="submit" name="Edit" value="编辑"/><br>
</form>
list页面
<body><br>
<table border="1">
<tr>
<td>Name</td>
<td>Street</td>
<td>City</td>
<td>State</td>
<td>Zip</td>
<td><center>Options</center></td>
<tr>
<%
List<Address> list = (List<Address>)request.getAttribute("list");
for(Address a :list){
%>
<tr>
<td><%=a.getName()%></td>
<td><%=a.getStreet() %></td>
<td> <%=a.getCity()%></td>
<td><%=a.getState()%></td>
<td><%=a.getZip() %></td>
<td>
<a href="AddressServlet?method=delete&id=<%=a.getId() %>">Delete</a>
<a href="AddressServlet?method=toedit&id=<%=a.getId() %>">Edit</a>
</td>
</tr>
<%}%>
</table>
<a href="add.jsp">Add</a>
最后若觉得请求url名字过长,可在index.jsp页面设置默认跳转<jsp:forward page="AddressServlet?method=list"></jsp:forward>
主要重点在于增删改查的逻辑,方便对这些知识掌握不牢的同学进行理解,当然有兴趣的同学代可以继续优化代码,使之更加符合项目要求的MVC设计思想,增加service以及serviceImp,daoImp等等,以后会出基于ssh三层架构的javaWeb,欢迎批评指正
源代码下载
这篇关于mysql+jsp+servlet 增删改查实例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!