一.整体架构:

注:取自其他文章,最后的NewFile.html纯用于测试错误,完全不用。

二.具体代码:

1.User.java

package common;

public class User {
private Integer id;
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
} }

2.UserDao.java

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; import common.User;
import helper.DbHelper; public class UserDao {
/**
* 查询所有用户信息
* @return
*/
public List<User> getAllUser(){
List<User> list = new ArrayList<User>();
Connection conn = DbHelper.getConnection();//连接数据库
String sql = "select * from user";
try {
PreparedStatement pst = conn.prepareStatement(sql);
ResultSet rst = pst.executeQuery();
while (rst.next()) {
User user = new User();
user.setId(rst.getInt("id"));
user.setName(rst.getString("name"));
user.setAge(rst.getInt("age"));
list.add(user);
}
rst.close();
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
return list;
} /**
* 添加用户
* @param user
* @return
*/
public boolean addUser(User user){
String sql = "INSERT INTO `user`(`name`,`age`) VALUES (?,?)";
Connection conn = DbHelper.getConnection();
try {
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, user.getName());
pst.setInt(2, user.getAge());
int count = pst.executeUpdate();
pst.close();
return count>0?true:false;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
} /**
* 修改用户信息
* @param user
* @return
*/
public boolean updateUser(User user){
String sql = "UPDATE `user` SET `name`=?,`age`=? WHERE `id` = ?";
Connection conn = DbHelper.getConnection();
try {
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, user.getName());
pst.setInt(2, user.getAge());
pst.setInt(3, user.getId());
int count = pst.executeUpdate();
pst.close();
return count>0?true:false;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
} /**
* 删除用户
* @param id
* @return
*/
public boolean deleteUser(int id){
String sql = "delete from user where id = ?";
Connection conn = DbHelper.getConnection();
try {
PreparedStatement pst = conn.prepareStatement(sql);
pst.setInt(1, id);
int count = pst.executeUpdate();
pst.close();
return count>0?true:false;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
} /**
* 根据ID进行查询用户
* @param id
* @return
*/
public User selectUserById(int id){
Connection conn = DbHelper.getConnection();
String sql = "select * from user where id = "+id;
User user = null;
try {
PreparedStatement pst = conn.prepareStatement(sql);
ResultSet rst = pst.executeQuery();
while (rst.next()) {
user = new User();
user.setId(rst.getInt("id"));
user.setName(rst.getString("name"));
user.setAge(rst.getInt("age"));
}
rst.close();
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
return user;
}
}

3.DbHelper

package helper;

import java.sql.Connection;
import java.sql.DriverManager; public class DbHelper {
private static String url = "jdbc:mysql://localhost:3306/my-db"; //数据库地址
private static String userName = "root"; //数据库用户名
private static String passWord = "Pa33w0rd"; //数据库密码
private static Connection conn = null; private DbHelper(){ } public static Connection getConnection(){
if(null == conn){
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, userName, passWord);
} catch (Exception e) {
e.printStackTrace();
}
}
return conn;
} public static void main(String[] args) { //测试数据库是否连通
System.out.println(getConnection());
}
}

4.Servlet

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 common.User;
import dao.UserDao; public class AddServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException { this.doPost(req, resp); } protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String name = req.getParameter("name");
Integer age = Integer.valueOf(req.getParameter("age"));
User user = new User();//创建user对象
user.setName(name);
user.setAge(age);
UserDao dao = new UserDao();
dao.addUser(user);//添加到数据库中
req.getRequestDispatcher("list").forward(req, resp);
} // @Override
// protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// String name = req.getParameter("name");
// Integer age = Integer.valueOf(req.getParameter("age"));
// System.out.println("name:"+name+" 111111111 age:"+age);
// User user = new User();//创建user对象
// user.setName(name);
// user.setAge(age);
// UserDao dao = new UserDao();
// dao.addUser(user);//添加到数据库中
// req.getRequestDispatcher("list").forward(req, resp);
// }
}
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 dao.UserDao; public class DeleteServlet extends HttpServlet{
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
} protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String idStr = req.getParameter("id"); // 删除数据的ID,根据ID删除
if (idStr != null && !idStr.equals("")) {
int id = Integer.valueOf(idStr);
UserDao dao = new UserDao();
dao.deleteUser(id);
}
req.getRequestDispatcher("list").forward(req, resp);
}
}
package servlet;

import java.io.IOException;
import java.util.List; import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import common.User;
import dao.UserDao; @WebServlet("/list")
public class ListServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
UserDao dao = new UserDao();
List<User> list = dao.getAllUser();
System.out.println("dao:"+dao+" 111111111 list:"+list);
req.setAttribute("userInfoList", list);
req.getRequestDispatcher("list.jsp").forward(req, resp); } protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
} }
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 common.User;
import dao.UserDao; public class UpdateServlet extends HttpServlet {
/**
* 查询到选中ID的值所对应的数据
*/
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String idStr = req.getParameter("id");
if (idStr != null && !idStr.equals("")) {
int id = Integer.valueOf(idStr);
UserDao dao = new UserDao();
User user = dao.selectUserById(id);
req.setAttribute("user", user);
}
req.getRequestDispatcher("update.jsp").forward(req, resp);
} /**
* 根据此ID对数据的值进行修改
*/
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String idStr = req.getParameter("id");
if (idStr != null && !idStr.equals("")) {
int id = Integer.valueOf(idStr);
String name = req.getParameter("name");
Integer age = Integer.valueOf(req.getParameter("age"));
User user = new User();
user.setId(id);
user.setName(name);
user.setAge(age);
UserDao dao = new UserDao();
dao.updateUser(user);
}
req.getRequestDispatcher("list").forward(req, resp);
}
}

5.web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>MyServlet</display-name>
<!-- <servlet>
servlet的注册名称,自定义。每个servlet的name不一样
<servlet-name>listServ</servlet-name>
servlet的完整类名: 包名+类名;如果ctrl+鼠标左击能 点开,说明成功
<servlet-class>servlet.ListServlet</servlet-class>
</servlet> -->
<!-- servlet的映射配置 -->
<!-- <servlet-mapping>
servlet的注册名称,一定要和上面的内部名称保持一致!!
<servlet-name>listServ</servlet-name>
servlet的对外访问路径(访问servlet的名称)
<url-pattern>/list</url-pattern>
</servlet-mapping>
ps:同一个servlet可以配置多个servlet-mapping,举个栗子
<servlet-mapping>
还是上面的那个servlet
<servlet-name>listServ</servlet-name>
除了/ListServlet,又配置了一个list2,通过这两个路径都可访问listServ这个servlet
<url-pattern>/list2</url-pattern>
</servlet-mapping> --> <servlet>
<servlet-name>addServ</servlet-name>
<servlet-class>servlet.AddServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>addServ</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping> <servlet>
<servlet-name>updateServ</servlet-name>
<servlet-class>servlet.UpdateServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>updateServ</servlet-name>
<url-pattern>/update</url-pattern>
</servlet-mapping> <servlet>
<servlet-name>delServ</servlet-name>
<servlet-class>servlet.DeleteServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>delServ</servlet-name>
<url-pattern>/delete</url-pattern>
</servlet-mapping>
</web-app>

6.前端代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>新增用户</title>
<script type="text/javascript">
function check(form) {
with (form) {
if (name.value == "") {
alert("用户名不能为空");
return false;
}
}
}
</script>
</head>
<body>
<form action="add" method="post" onsubmit="check(this)">
<table align="center" width="450">
<tr>
<td align="center" colspan="2">
<h2>添加用户信息</h2>
<hr>
</td>
</tr>
<tr>
<td align="right">用户名:</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td align="right">年龄:</td>
<td><input type="text" name="age"></td>
</tr>
<tr>
<td align="center" colspan="2">
<input type="submit" value="添 加">
</td>
</tr>
</table>
</form>
</body>
</html>
<%@ 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">
<%@page import="java.util.List"%>
<%@page import="common.User"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>所有用户</title>
<style type="text/css">
td {
font-size: 12px;
}
h2 {
margin: 0px
}
</style>
<script type="text/javascript"> </script>
</head>
<body>
<h2 align="center">
<a href="add.jsp">添加新用户</a>
</h2>
<br>
<table align="center" width="450" border="1" height="180"
bordercolor="white" bgcolor="black" cellpadding="1" cellspacing="1">
<tr bgcolor="white">
<td align="center" colspan="7">
<h2>所有用户信息</h2>
</td>
</tr>
<tr align="center" bgcolor="#e1ffc1">
<td><b>ID</b></td>
<td><b>姓名</b></td>
<td><b>年龄</b></td>
<td colspan="2"><b>操作</b></td>
</tr>
<%
// 获取用户信息集合
List<User> list = (List<User>)(request.getAttribute("userInfoList"));
// 判断是否有数据
if (list == null || list.size() < 1) {
%>
<tr bgcolor="white"><td colspan="5" ><h4 align="center">没有数据</h4></td></tr>
<%
} else {
// 遍历用户集合中的数据
for (User user : list) {
%>
<tr align="center" bgcolor="white">
<td><%=user.getId()%></td>
<td><%=user.getName()%></td>
<td><%=user.getAge()%></td>
<td >
<a href="update?id=<%=user.getId()%>">修改</a> </td>
<td>
<a href="delete?id=<%=user.getId()%>">删除</a>
</td>
</tr>
<%
}
}
%>
</table>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@page import="common.User"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>修改用户信息页面</title>
</head>
<body>
<div>
<table>
<thead><tr><td><h1>修改用户信息</h1></td></tr></thead>
<tbody>
<form action="update" method="post">
<tr>
<td>ID:</td>
<td><input type="text" name="id" value="${user.id}"
readonly="readonly" /></td>
</tr>
<tr>
<td>name:</td>
<td><input type="text" name="name" value="${user.name}" /></td>
</tr>
<tr>
<td>age:</td>
<td><input type="text" name="age" value="${user.age}" /></td>
</tr>
<tr>
<td><input class="btn" type="submit" value="提交" /> <input
class="btn" type="reset" value="重置" /></td>
</tr>
</tbody>
</form>
</table>
</div>
</body>
</html>

三.jar包:mysql-connector-java-5.1.43-bin.jar(用于数据库连接)

 

(一)MVC项目的更多相关文章

  1. 采用MiniProfiler监控EF与.NET MVC项目(Entity Framework 延伸系列1)

    前言 Entity Framework 延伸系列目录 今天来说说EF与MVC项目的性能检测和监控 首先,先介绍一下今天我们使用的工具吧. MiniProfiler~ 这个东西的介绍如下: MVC Mi ...

  2. MVC项目中ExecutionTimeout不生效的解决方案

    我们做web服务器端开发时,经常会遇到一个需求场景,因为某些耗时处理造成页面的响应处理时间超长,技术角度就想能否给页面处理程序一个指定的超时时间,服务端处理程序执行时间超过这个指定的超时时间则中断处理 ...

  3. ASP.NET MVC项目实践技巧

    原创文章转载请注明出处:@协思, http://zeeman.cnblogs.com 在.NET开发初期,微软提供的WEB开发模型是WebForm,试图消除Web和桌面的隔阂,建立一致的开发体验.但是 ...

  4. AngularJS2 + ASP.NET MVC项目

    环境:VS2015, NodeJS:v 6.5, npm: v3.10, AngularJs 2 通过将ASP.NET MVC项目与Angualr 2官网上的quick start整合的过程中遇到些问 ...

  5. IntelliJ IDEA上创建maven Spring MVC项目

    IntelliJ IDEA上创建Maven Spring MVC项目 各软件版本 利用maven骨架建立一个webapp 建立相应的目录 配置Maven和SpringMVC 配置Maven的pom.x ...

  6. 远程调试 ASP.NET MVC 项目

    Visual Studio 支持从一台计算机到另一台设备的远程调试.进行远程调试时,主机可以是任何支持 Visual Studio 的平台.远程设备可以是 x86.x64 或 ARM 平台. 本文将指 ...

  7. Visual Studio 2015 新建MVC项目 Package Manager Console不能使用 (HRESULT: 0x80131500)

    Visual studio 2015 突然新建不了MVC项目,报出错误: HRESULT: 0x80131500 在折腾了很长时间,最后在Github上看到这样一个贴 地址:https://githu ...

  8. mvc项目controller重命名了,用原网页url访问不了了,怎么办?

    如题.MVC项目,手机网站. 公司的官方微信上,用户关注之后,点击相应菜单就可以使用相关的功能. 最近项目重构,有些不规范的命名方式给予了重构.上线后,微信上发现一些网页访问不了了. 联系微信的维护人 ...

  9. 本地MVC项目发布到IIS服务器

    0瞎扯 朋友们有时候我们写个一个web程序只能使用卡西尼服务器调试,下面我教大家发布到IIS服务器上(包括本地ISS7.5和远程服务器 IIS) 1.VS发布 a.点击web项目->发布

  10. 基于MVC4+EasyUI的Web开发框架经验总结(15)--在MVC项目中使用RDLC报表

    RDLC是一个不错的报表,有着比较不错的设计模式和展现效果,在我的Winform开发里面,使用RDLC也是一个比较方便操作,如可以参考文章<DevExpress的XtraReport和微软RDL ...

随机推荐

  1. iptables 相关命令

    1. 清除已有iptables规则 iptables -F iptables -X iptables -Z 2. 开放指定的端口(添加规则) iptables -A INPUT -s 127.0.0. ...

  2. 为什么深度(Ubuntu)Linux挂载NTFS分区只读不可写?

      如前所述,经扩展,Dell Vostro 1520笔记本电脑拥有了两块硬盘. 本着旧物利用的心思,在其中一块256GiB固态盘上安装了深度linux,同时挂载另一块2TiB机械盘作为存储盘. 这块 ...

  3. [Luogu] 树链剖分

    模板题,对于对为某个点为根的子树进行处理时,只需每个节点记录两个值 分别为搜索以该节点为根的子树时的最初搜索序和最末搜索序,将这两 个数作为线段树区间操作的端点进行操作 #include <bi ...

  4. Centos 7.x 设置Lvs+ Keepalived

    [实验环境] Centos 7.2 Nginx  以下为本次试验所使用的地址: VIP:192.168.136.100 LVS-1:192.168.136.170 LVS-2:192.168.136. ...

  5. 遇到bug如何处理

    issue中查询是否有相似bug assert / try-except / IDE单步调式 框架可以查询源码或者查询官方文档

  6. vue 传参props里面为什么要带type,还有default?

    这个是子组件啦 ,写type的意思是swiperDate传过来的数据类型是数组,default就是表示不传默认返回的[ ],空数组. 这种就是表示传的数据类型是number,不传默认是0.

  7. 在OpenFOAM中做用户自定义库——编译library【转载】

    转载自:http://openfoam.blog.sohu.com/22041538.html OpenFOAM自己提供的标准类都是以库的形式提供的,并且利用头文件给出了库的应用接口.这样一来,用户的 ...

  8. OpenResty之replace-filter-nginx-module

    原文: openresty/replace-filter-nginx-module 1. 概要 location /t { default_type text/html; echo abc; repl ...

  9. 报错:使用java api连接redis集群时报错 READONLY You can't write against a read only slave.

    报错: READONLY You can’t write against a read only slave. 报错原因: 因为连接的是从节点,从节点只有读的权限,没有写的权限 解决方案: 进入red ...

  10. What is the use of c# “Yield” keyword ?

    What is the use of c# “Yield” keyword ? “Yield keyword helps us to do custom stateful iteration over ...