第一个 javaweb 项目(适合新手)

用户名片信息管理

  • 目标

     通过jsp页面的点击与后台的交互实现用户名片信息的管理.
    
  • 知识点

     Servlet、基本页面标签、mysql、JSTL等等.
    
  • 工具

     Eclipse、Navicat Premium.
    
  • 实现过程
    1、数据库的创建
    具体如下:在这里插入图片描述
    2.创建javaweb项目
    项目目录如下:
    在这里插入图片描述
    字符编码的设置:

public class EncodingFilter implements Filter{

	public EncodingFilter() {
		System.out.println("过滤器构造");
	}
	@Override
	public void destroy() {
		System.out.println("过滤器销毁");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		request.setCharacterEncoding("utf-8");//设置字符集为utf-8
		response.setContentType("text/html;charset=utf-8");
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		System.out.println("过滤器初始化");
		
	}
	
}

实体Bean的编写:

package bean;

public class User {
	private int id;
	private String username;
	private String password;
	private String sex;
	private String home;
	private String info;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getHome() {
		return home;
	}
	public void setHome(String home) {
		this.home = home;
	}
	public String getInfo() {
		return info;
	}
	public void setInfo(String info) {
		this.info = info;
	}
	public User(int id, String username, String password, String sex, String home, String info) {
		super();
		this.id = id;
		this.username = username;
		this.password = password;
		this.sex = sex;
		this.home = home;
		this.info = info;
	}
	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password=" + password + ", sex=" + sex + ", home="
				+ home + ", info=" + info + "]";
	}
	
	
}

数据库工具类的编写(用户名和密码作相应的修改)用来获取Connection 简化代码:

package util;

import java.sql.Connection;
import java.sql.DriverManager;



/**
 * 实现数据库的连接操作和基本功能
 * @author sjl
 *
 */
public class DBUtil {
	public static Connection getConnection() throws Exception{
		String url="jdbc:mysql://localhost/user?useunicuee=true& characterEncoding=utf8";
		String username="root";
		String password="123456";
		
		Connection connection = null;
		Class.forName("com.mysql.jdbc.Driver");//抛出异常
		connection = DriverManager.getConnection(url,username,password);
		return connection;
	}
}

数据操纵代码编写(实现增加删除更新等功能):

package Dao;

import java.util.List;

import bean.User;

public interface Dao {
	public boolean register(User user);
	public boolean login(String name,String password);
	public List<User> getAllusers();
	public boolean updateUser(int id,String name, String pwd,String sex, String home,String info);
	public boolean deleteUser(int id);
}

package Dao;

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


import bean.User;
import util.DBUtil;

public class DBDao implements Dao{
	Connection conn;
	PreparedStatement pstmt;
	ResultSet rs;
	@Override
	public boolean register(User user) {
		try {
			conn = DBUtil.getConnection();
			String sql = "insert into user(name,pwd,sex,home,info) values('"+user.getUsername()+"','"+user.getPassword()+"',"
					+ "'"+user.getSex()+"','"+user.getHome()+"','"+user.getInfo()+"')";
			pstmt = conn.prepareStatement(sql);
			boolean a =pstmt.execute();
			if(!a){
				System.out.println("插入成功");
				return true;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println("插入失败");
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean login(String name,String password) {
	
		try {
			conn = DBUtil.getConnection();
			String sql = "select * from user where name=? and pwd=?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, name);
			pstmt.setString(2, password);

			boolean b =pstmt.execute();
			System.out.println(b);
			if(b){
				System.out.println("登陆成功");
				return true;
				
			}else{
				System.out.println("请输入正确的账号和密码");
				return false;
				
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;

	}

	@Override
	public List<User> getAllusers() {
		List<User> list = new ArrayList<User>();
		
		try {
			conn = DBUtil.getConnection();
			String sql = "select * from user";
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while(rs.next()){
				User user = new User();
				user.setId(rs.getInt("id"));
				user.setUsername(rs.getString("name"));
				user.setPassword(rs.getString("pwd"));
				user.setSex(rs.getString("sex"));
				user.setHome(rs.getString("home"));
				user.setInfo(rs.getString("info"));
				list.add(user);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return list;
	}

	@Override
	public boolean updateUser(int id,String name, String pwd,String sex, String home,String info) {
		try {
			conn = DBUtil.getConnection();
			String sql = "update user set name ='"+name
					+"' , pwd ='"+pwd
					+"' , sex ='"+sex
					+"' , home ='"+home
					+"' , info ='"+info+"' where id = "+id;
			pstmt = conn.prepareStatement(sql);
			boolean c = pstmt.execute();//!!!!!!!!!执行成功后返回为false!!!!!!!!

			System.out.println(c);
			if(!c){
				return true;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return false;
	}

	@Override
	public boolean deleteUser(int id) {
		try {
			conn = DBUtil.getConnection();
			String sql = "delete from user where id=?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, id);

			boolean d = pstmt.execute();//!!!!!!!!!执行成功后返回为false!!!!!!!!
			if(!d){
				return true;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

}

更新一个知识点:execute的返回值什么时候是true,什么时候是false?
execute 返回值—如果第一个结果为 ResultSet 对象,则返回 true;如果其为更新计数或者不存在任何结果,则返回 false
相应的控制类代码:
登录:

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.DBDao;
import Dao.Dao;

public class LServlet extends HttpServlet{
	public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
		doPost(request, response);  //将信息使用doPost方法执行   对应jsp页面中的form表单中的method
	}
	public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
		String name = request.getParameter("name");
		String pwd = request.getParameter("pwd");
		
		Dao userDao  = new DBDao();
		
		if(userDao.login(name, pwd)){
			request.setAttribute("xiaoxi", "欢迎" + name + "登录");
			request.getRequestDispatcher("/success.jsp").forward(request, response);
		}else{
			response.sendRedirect("index.jsp");
		}
	}
}

注册:

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.DBDao;
import Dao.Dao;
import bean.User;

public class RServlet extends HttpServlet{
	public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
		doPost(request, response);
	}
	public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
		String name=request.getParameter("name");
		String password = request.getParameter("pwd");
		String sex = request.getParameter("sex");
		String home = request.getParameter("home");
		String info = request.getParameter("info");
		
		User user = new User();
		
		user.setUsername(name);
		user.setPassword(password);
		user.setSex(sex);
		user.setHome(home);
		user.setInfo(info);
		
		Dao userDao  = new DBDao();
		
		if(userDao.register(user)){
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		}else{
			response.sendRedirect("index.jsp");
		}	
	}
}

更新:

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.DBDao;
import Dao.Dao;

public class UServlet extends HttpServlet{
	public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
		doPost(request, response);
	}
	public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
		String id=request.getParameter("id");
		int userId = Integer.parseInt(id);
		String name = request.getParameter("name");
		String pwd = request.getParameter("pwd");
		String sex = request.getParameter("sex");
		String home = request.getParameter("home");
		String info = request.getParameter("info");
		
		Dao userDao = new DBDao();
		
		
		if(userDao.updateUser(userId, name, pwd, sex, home, info)){
			request.getRequestDispatcher("/Searchall").forward(request, response);
		}
		else{
			response.sendRedirect("index.jsp");
		}
	}
}

删除:

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.DBDao;
import Dao.Dao;

public class DServlet extends HttpServlet{
	public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
		doPost(request, response);
	}
	public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
		String id = request.getParameter("id");
		int userId = Integer.parseInt(id);
		
		Dao userDao = new DBDao();
		
		if(userDao.deleteUser(userId)){
			request.getRequestDispatcher("/Searchall").forward(request, response);
		}	else{
				response.sendRedirect("index.jsp");
			}
		}
	}


查询所有用户信息:

package servlet;

import java.io.IOException;
import java.util.ArrayList;
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.DBDao;
import Dao.Dao;
import bean.User;

public class SServlet extends HttpServlet{
	public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
		doPost(request, response);
	}
	public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
		Dao userDao = new DBDao();
		List<User> userList = new ArrayList<User>();
		userList = userDao.getAllusers();
		request.setAttribute("userList", userList);
		request.getRequestDispatcher("/Showall.jsp").forward(request, response);
	}

}

编写完相应的控制类代码后,谨记配置web.xml文件
web.xml位于WebContent目录下的web-inf下(可以手动创建也可自动生成)
自动生成如下(勾选红圈 圈住的地方):
在这里插入图片描述
在这里插入图片描述
接下来编写相应视图页面的编写:
登录页面:

<%@ 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>Insert title here</title>
</head>
<body>
<form action="DengluServlet" method="post">
	账号:<input type="text" name="name"><br>
	密码:<input type="text" name="pwd"><br>
	<input type="submit" value="提交"> 
	
</form>
<form action="register.jsp">
	<input type="submit" value="新用户注册"/>
</form>
</body>
</html>

在这里插入图片描述
注册页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
                <%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>"> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="ZhuceServlet" method="post">
		名字:<input type="text" name="name"/><br>
		密码:<input type="text" name="pwd"/><br>
		性别:<input type="text" name="sex"/><br>
		家庭住址:<select name="home">
			<option>山西</option>
			<option>北京</option>
			<option>上海</option>
		</select><br>
		个人说明:<textarea rows="5" cols="30" name="info"></textarea><br>
		<input type="submit" value="提交"/>
	</form>
</body>
</html>

在这里插入图片描述
查询全部用户:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 
        <%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>"> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<table width="600" border="1" cellpadding="0" >

	<tr>
		<td>id</td>
		<td>name</td>
		<td>password</td>
		<td>sex</td>
		<td>home</td>
		<td>info</td>
		<td>doing</td>
	</tr>
	<c:forEach var="U" items="${userList }">
	<form action="UpdateServlet" method="post">
	<tr>
		<td><input type="text" value="${U.id }" name="id"></td>
		<td><input type="text" value="${U.username }" name="name"></td>
		<td><input type="text" value="${U.password }" name="pwd"></td>
		<td><input type="text" value="${U.sex }" name="sex"></td>
		<td><input type="text" value="${U.home }" name="home"></td>
		<td><input type="text" value="${U.info }" name="info"></td>
		<td><a href="DeleteServlet?id=${U.id }">删除</a><input type="submit" value="更新"></td>
	</tr>
</form>
</c:forEach>



</table>

</body>
</html>

在这里插入图片描述
相应操作实现后的成功界面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
        <%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

<head>
<base href="<%=basePath%>"> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
				${xiaoxi} <br>  
			<a href="Searchall">查看所有用户</a>
</body>
</html>

在这里插入图片描述
错误界面:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
    <%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

<head>
<base href="<%=basePath%>"> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
	<h1>操作发生错误,请重新操作</h1>
</body>
</html>

总之,最后通过自己的不断努力实现了相应的功能,俗话说得好,眼过千遍不如手过一遍,还不赶快自己敲起来!!!!!
参考自:https://blog.csdn.net/qq_23994787/article/details/73612870
自己也做了相应的修改!!!有啥问题可以交流哦!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值