手把手搭建一个完整的javaweb项目(适合新手)
本篇文章仅供参考。如果您遇到了问题,建议自己使用英文进行google搜索。而不是当一个不经过自己努力和思考的伸手党
本文章以前在CSDN发布:点此查看
2021/02/24更新:仅做参考,建议学习SpringBoot。
说明1:只是实现了简单的操作,但是逻辑并不严谨(比如并没有进行密码的加密,也没有进行对不规范字符串的判断),仅适合新手,望注意。
说明2:这个项目是在我的macbookpro上运行的。windows用户的环境配置可能不一样。望注意
前提:正确建立了一个javaweb项目(web项目建立教程)
开发环境与工具
- IntelliJ IDEA 2018.3.3(Ultimate Edition)(Mac版本)
- Mysql Workbench8.0
- jdk11
- Tomcat for mac ( 安装教程 )
工具包
添加下包三个jar包,放到lib文件夹中。 jar包链接
密码:rglh
功能说明
- 用户登录
- 新用户注册
- 用户列表展示
- 用户信息删除
- 用户信息更新
操作步骤
- 在mysql建立一个新表Student,里面有name,password,id(为了简化操作,所以只有三列并且都是String类型)
create table if not exists Student (name varchar(10) primary key,
password varchar(10) not null,
id varchar(10) not null);
- 插入数据
insert into Student(name,password,id) values("005",123,5);
insert into Student(name,password,id) values("004",123,4);
insert into Student(name,password,id) values("003",123,3);
insert into Student(name,password,id) values("002",123,2);
insert into Student(name,password,id) values("001",123,1);
- 打开intellij新建一个javaweb项目,具体操作参考我的博客
- 导入连接数据库的jar包,具体操作参考我的博客 intellij导数据库jar包
- 建立对应的包结构
filter //过滤器,解决中文字符集乱码
util //数据库连接工具类
entity //实体类
dao //数据操作类
servlet //servlet类
- 在filter下新建一个EncodingFilter用来解决中文字符集乱码,它需要实现Filter接口,并重写doFilter函数
package filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
//在filter下新建一个EncodingFilter用来解决中文字符集乱码,它需要实现Filter接口,并重写doFilter函数
public class EncodingFilter implements Filter {
public EncodingFilter() {
System.out.println("过滤器构造");
}
public void destroy() {
System.out.println("过滤器销毁");
}
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);
}
public void init(FilterConfig arg0) throws ServletException {
System.out.println("过滤器初始化");
}
}
- web.xml的全部配置信息
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<display-name></display-name>
<filter><!-- 过滤器配置-->
<filter-name>EncodingFilter</filter-name>
<filter-class>filter.EncodingFilter</filter-class><!--全路径 从根包开始一直到类名-->
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern> <!--*即为过滤所有-->
</filter-mapping>
<servlet><!--servlet类路径配置-->
<servlet-name>loginServlet</servlet-name>
<servlet-class>servlet.loginServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>registerServlet</servlet-name>
<servlet-class>com.servlet.registerServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>showAllServlet</servlet-name>
<servlet-class>servlet.showAllServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>deleteServlet</servlet-name>
<servlet-class>com.servlet.deleteServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>updateServlet</servlet-name>
<servlet-class>servlet.updateServlet</servlet-class>
</servlet>
<servlet-mapping><!--servlet类映射配置-->
<servlet-name>loginServlet</servlet-name>
<url-pattern>/loginServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>registerServlet</servlet-name>
<url-pattern>/registerServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>showAllServlet</servlet-name>
<url-pattern>/showAllServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>deleteServlet</servlet-name>
<url-pattern>/deleteServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>updateServlet</servlet-name>
<url-pattern>/updateServlet</url-pattern>
</servlet-mapping>
<welcome-file-list><!--默认首页地址-->
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
</web-app>
- 在util下新建一个DBconnect类用来处理对数据库的连接操作(用户名或密码按照自己的数据库更改)
package com.util;
import java.sql.*;
public class DBconnect
{
static String url="jdbc:mysql://localhost:3306/DataTest?useSSL=false";
static String user="root";
static String pw = "12345678";
static Connection conn=null;
static PreparedStatement ps=null;
static ResultSet rs=null;
static Statement st=null;
public static void init() throws SQLException, ClassNotFoundException {//SQl程序初始化
try{
Class.forName("com.mysql.jdbc.Driver");//注册驱动
conn= DriverManager.getConnection(url, user, pw); //建立连接
}catch (Exception e){
System.out.println("SQL程序初始化失败");
e.printStackTrace();
}
}
public static int addUpdateDelete(String sql){
int i=0;
try{
ps=conn.prepareStatement(sql);
boolean flag= ps.execute();
if(flag==false){//如果第一个结果是结果集对象,则返回true;如果第一个结果是更新计数或者没有结果,则返回false
i++;
}
}catch(Exception e){
System.out.println("数据库增删改异常 ");
e.printStackTrace();
}
return i;
}
public static ResultSet selectSql(String sql){
try{
ps=conn.prepareStatement(sql);
rs=ps.executeQuery();
}catch(Exception e){
System.out.println("数据库查询异常");
e.printStackTrace();
}
return rs;
}
public static void closeConn(){
try{
conn.close();
}catch(Exception e){
System.out.println("数据库关闭异常");
e.printStackTrace();
}
}
}
- 在entity下新建一个MyUser实体类(实体即抽象出来的用户对象,对应数据库中的Student表,表中每个字段在实体中为一个属性,也可以理解为一个User对象对应数据库中的Student表一条记录)
package entity;
public class MyUser {
private String name;
private String password;
private String id;
public MyUser(){}
public MyUser(String name,String password,String id){
this.name=name;
this.password=password;
this.id=id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public MyUser(String name, String password) {
this.name = name;
this.password = password;
}
public String getName() {
return name;
}
public void setName(String username) {
this.name = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
- 在dao下新建一个UserDao接口 以及对应的方法实现类(使用接口类是为了规范开发)
UserDao类
package dao;
import java.util.List;
import entity.MyUser;
public interface UserDao {
public boolean login(String name,String password);
public boolean register(MyUser user);
public List<MyUser> getUserAll();//返回用户信息集合
public boolean delete(String id);//根据id删除
public boolean update(String name, String id);
}
UserDaoImplement类
package dao;
import entity.MyUser;
import util.DBconnect;
import java.lang.invoke.MutableCallSite;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class UserDaoImplement implements UserDao {
public boolean login(String name, String password) {
boolean flag = false;
try {
try{
DBconnect.init();
}catch (Exception e){
e.printStackTrace();
}
//注意查询语句中的单引号双引号
ResultSet rs = DBconnect.selectSql("select * from student where name=\'" + name + " \'and password=\'" + password + "\';");
while (rs.next()) {
if (rs.getString("name").equals(name) && rs.getString("password").equals(password)) {
flag = true;
}
}
DBconnect.closeConn();
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
public boolean register(MyUser user) {
boolean flag = false;
try{
DBconnect.init();
}catch (Exception e){
e.printStackTrace();
}
int i = DBconnect.addUpdateDelete("insert into student(name,password,id) " +
"values(\'" + user.getName() + "\',\'" + user.getPassword() + "\',\'"+user.getId()+" \' )");
if (i > 0) {
flag = true;
}
DBconnect.closeConn();
return flag;
}
public List<MyUser> getUserAll() {//返回用户信息集合
List<MyUser> list = new ArrayList<>();
try {
try{
DBconnect.init();
}catch (Exception e){
e.printStackTrace();
}
ResultSet rs = DBconnect.selectSql("select * from student");
while (rs.next()) {
String nameone=rs.getString("name");
String passwordone=rs.getString("password");
String idone=rs.getString("id");
MyUser user=new MyUser(nameone,passwordone,idone);
list.add(user);
}
DBconnect.closeConn();
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
public boolean delete(String id) {//根据id删除{
boolean flag = false;
try{
DBconnect.init();
}catch (Exception e){
e.printStackTrace();
}
String sql = "delete from student where id=\'" + id+"\'";
int i = DBconnect.addUpdateDelete(sql);//i的意义:
if (i > 0) {
flag = true;
}
DBconnect.closeConn();
return flag;
}
public boolean update(String name, String id) {
boolean flag = false;
try{
DBconnect.init();
}catch (Exception e){
e.printStackTrace();
}
String sql = "update student set name =\'" + name
+"\'"+"where id = \'" + id+"\'";
int i = DBconnect.addUpdateDelete(sql);
System.out.println("1"+" "+i);
if (i > 0) {
flag = true;
}
DBconnect.closeConn();
return flag;
}
}
- 在servlet下创建loginServlet用来实现对用户登录的操作
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.UserDao;
import dao.UserDaoImplement;
public class loginServlet extends HttpServlet { //需要继承HttpServlet 并重写doGet doPost方法
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"); //得到jsp页面传过来的参数
String password = request.getParameter("password");
UserDao ud = new UserDaoImplement();
if (ud.login(name, password)) {
//request.setAttribute("hello", "欢迎用户" + name); //向request域中放置信息
request.getRequestDispatcher("/success.jsp").forward(request, response);//转发到成功页面
} else {
response.sendRedirect("login.jsp"); //重定向到首页
}
}
}
- 在servlet下创建一个registerServlet用来实现用户注册的操作
package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.text.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.UserDao;
import dao.UserDaoImplement;
import entity.MyUser;
public class registerServlet 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"); //获取jsp页面传过来的参数
String pwd = request.getParameter("password");
String id = request.getParameter("id");
MyUser user = new MyUser(); //实例化一个对象,组装属性
user.setName(name);
user.setPassword(pwd);
user.setId(id);
UserDao ud = new UserDaoImplement();
if(ud.register(user)){
request.setAttribute("name", name); //向request域中放置参数
request.getRequestDispatcher("/login.jsp").forward(request, response); //转发到登录页面
}else{
response.sendRedirect("register.jsp");//注册失败则返回注册页面,但是缺少提示"注册失败"
}
}
}
- 在servlet下创建shouAllServlet用来返回数据库中所有用户信息
package servlet;
import java.io.IOException;
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.UserDao;
import dao.UserDaoImplement;
import entity.MyUser;
public class showAllServlet 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 {
response.setContentType("text/html;charset=utf-8");
UserDao ud = new UserDaoImplement();
List<MyUser> userAll = ud.getUserAll();
request.setAttribute("all", userAll);
request.getRequestDispatcher("showAll.jsp").forward(request, response);
}
}
- 在servlet下创建updateServlet用来更新用户信息(在此仅仅根据id来更新用户姓名,逻辑性很弱
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.ParseException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.UserDao;
import dao.UserDaoImplement;
import entity.MyUser;
public class updateServlet 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");
String name = request.getParameter("name"); //获取jsp页面传过来的参数
UserDao ud = new UserDaoImplement();
if(ud.update(name, id)){
request.getRequestDispatcher("/addUpdateDeleteSuccess.jsp").forward(request, response);
}else{
response.sendRedirect("addUpdateDeleteFail.jsp");
}
}
}
补充:在servlet下创建deleteServlet用来删除用户信息
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;
import dao.UserDaoImplement;
public class deleteServlet 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");
UserDao ud = new UserDaoImplement();
if (ud.delete(id)) {
request.getRequestDispatcher("addUpdateDeleteSuccess.jsp").forward(request, response);
} else {
response.sendRedirect("addUpdateDeleteFail.jsp");
}
}
}
- 新建各种jsp页面
login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
<head>
<title>登录注册页面</title>
</head>
<body >
<form action="loginServlet" method="post" style="padding-top:-700px;">
用户名:<input type="text" name="name"value=""><br><br>
密码: <input type="password" name="password"value=""><br><br>
<input type="submit"value="登录"name="login"><input type="reset"value="重置"><br>
</form>
<form action="register.jsp">
<input type="submit"value="新用户注册">
</form>
</body>
</html>
success.jsp
<%@ page language="java" import="java.util.*" 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">
<html>
<head>
<title>My JSP \'success.jsp\' starting page</title>
</head>
<body>
<br>
<a href="showAllServlet">查看所有用户</a>
</body>
</html>
register.jsp
<%@ page language="java" import="java.util.*" 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">
<html>
<head>
<title>My JSP starting page</title>
</head>
<body >
<form action="registerServlet"method="post" style="padding-top:-700px;">
输入姓名:<input name="name" type="text"><br><br>
输入密码:<input name="password" type="password"><br><br>
输入id:<input name="id" type="text" ><br><br>
<input type="reset"value="重置"><input type="submit"value="注册">
</form>
</body>
</html>
showAll.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="com.entity.MyUser" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="com.dao.UserDao" %>
<%@ page import="com.dao.UserDaoImplement" %>
<%@ page import="java.lang.ref.ReferenceQueue" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>所有用户页面</title>
</head>
<body>
<!--以下两段代码放在body中不要放在<html>之外-->
<%
String path=request.getContextPath();
String basepath=request.getScheme()+"://"+ request.getServerName()+":"+request.getServerPort()+"/";
%>
<!-- 使用from提交数据,不能在不刷新页面的情况下直接在当前页面显示处理过的后台数据-->
<c:forEach var="U" items="${requestScope.all}" >
<form action="updateServlet" method="post">
<tr>
<td><input type="text" value="${U.name}" name="name" ></td>
<td><input type="text" value="${U.password}" name="password"></td>
<td><input type="text" value="${U.id}" name="id"></td>
<td><a href="deleteServlet?id=${U.id}">删除</a> <input type="submit" value="更新"/></td>
</tr>
</form>
</c:forEach>
</body>
</html>
addUpdateDeleteFail.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>addUpdatedDeleteFail</title>
</head>
<body>
<p>addUpdateDeleteFail</p>
</body>
</html>
addUpdateDeleteSuccess.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>addUpdateDeleteSuccess</title>
</head>
<body>
<a href="showAllServlet">查看所有用户</a>
</body>
</html>
操作截图
-
开启Tomcat,运行login.jsp,展示首页
-
输入名字001与密码123,登录成功进入loginServlet,点击查看所有用户,显示用户信息
-
点击删除,若是删除成功则返回所有用户列表,否则返回addUpdateDelete.jsp(这里不展示删除具体的例子)
-
在首页点击注册,进入注册页面,注册007,注册完成会返回登录页面
遇到的问题以及解决方式
问题1
在showAll.jsp页面中显示了所有数据库的数据,但是删除或者更改其中的一个数据,再想返回修改数据之后的当前页面,就会出现错误。
问题症结所在:jsp页面回显数据
分析:前端提交数据,主要有两种方式。from表单与ajax异步提交。两种方式都可以提交数据到后台。但是想让后台数据返回当前页面显示的话,在不刷新整个页面的前提下,就需要使用ajax,因为ajax可以实现异步刷新
解决方式:在此转换了一个思路。删除或者更新之后,先跳转到addUpdateDeleteSuccess.jsp,这个jsp界面有个按钮链接可以跳转到showAll.jsp界面,然后再显示所有用户的信息(其实使用ajax解决也是ok的)
问题2:端口1099被占用
解决方式:
1) 在mac终端输入lsof -i tcp:1099,查看是哪个进程占用1099
2) 知道是进程80049占用
输入sudo kill -9 80049,即可解决问题
问题3:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
解决:
将数据库连接的jar文件导入到工程的web/WEB-INF/lib中(查询连接https://blog.csdn.net/mayuko2012/article/details/72971997)
问题4:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column…
分析:出现这个异常的很大可能性是 数据库是没有问题的!关键原因是:你从传过来的参数是String类型的,我们在操作数据库时String类型的参数必须要用\’ \’把参数引起来才能传递并接收! 例如rs=stmt.executeQuery(“select * from userinfo where userid = \'”+ID+”\'”);ID是String类型,在进行数据库操作时,千万不要漏了两边的单引号,切记 !!!常错点!!!
问题5:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException异常,
解决:一般都是自己的sql语句写错了(仔细查找错误)。
问题6:org.apache.jasper.JasperException: javax.el.ELException: Failed to parse the expression [${}]
分析:没有jstl标签库
操作:在lib文件夹添加相关的jar。文章开头已给出。
感想
- 报错的信息,可以直接粘贴,google一下,很多问题都可以找得到答案。
- google问题时候,比较考验自己的筛选能力。很多博文写的真的是只有自己能看懂,所以我在找错的时候花了很多的时间
- 有条件一定要FQgoogle,百度真的是会浪费你的时间。买个一年的服务器也就是百来十块钱,但是自己的时间一定是可以节省很多的。
- 多上github,StackOverflow,多用google。
- 有一个bug我改了三天,都变佛系了。改了一天没结果,我就第三天再继续刚。
- 有个27寸的显示器真的能让你多坐在座位上打码
- 初级选手的话,数据库的表尽量设计得简单,不然很麻烦
- 打码更多需要的是耐心与坚持