• JAVA Web基础 留言本综合练习


    一.com.hanqi.model包

    留言本类

    package com.hanqi.model;
    import java.util.Date;
    //留言本对象
    public class Message {
    	private Integer id;//留言ID
    	private String content;//留言内容
    	private Date createtime;//留言时间
    	private String username;//留言人用户名
    	public Message(Integer id, String content, Date createtime, String username) {
    		super();
    		this.id = id;
    		this.content = content;
    		this.createtime = createtime;
    		this.username = username;
    	}
    	public Message() {
    		super();
    	}
    	public Integer getId() {
    		return id;
    	}
    	public void setId(Integer id) {
    		this.id = id;
    	}
    	public String getContent() {
    		return content;
    	}
    	public void setContent(String content) {
    		this.content = content;
    	}
    	public Date getCreatetime() {
    		return createtime;
    	}
    	public void setCreatetime(Date createtime) {
    		this.createtime = createtime;
    	}
    	public String getUsername() {
    		return username;
    	}
    	public void setUsername(String username) {
    		this.username = username;
    	}	
    }
    

     用户类

    package com.hanqi.model;
    import java.util.Date;
    //用户对象
    public class Users {
    	private Integer id ;//用户ID
    	private String username;//用户名
    	private String password;//用户密码
    	private String realname;//用户真实姓名
    	private Date createtime;//用户注册时间
    	private Integer mark;//用户有效标记
    	public Users(Integer id, String username, String password, String realname, Date createtime, Integer mark) {
    		super();
    		this.id = id;
    		this.username = username;
    		this.password = password;
    		this.realname = realname;
    		this.createtime = createtime;
    		this.mark = mark;
    	}
    	public Users() {
    		super();
    	}
    	public Integer getId() {
    		return id;
    	}
    	public void setId(Integer 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 getRealname() {
    		return realname;
    	}
    	public void setRealname(String realname) {
    		this.realname = realname;
    	}
    	public Date getCreatetime() {
    		return createtime;
    	}
    	public void setCreatetime(Date createtime) {
    		this.createtime = createtime;
    	}
    	public Integer getMark() {
    		return mark;
    	}
    	public void setMark(Integer mark) {
    		this.mark = mark;
    	}
    	@Override
    	public String toString() {
    		return username;
    	}
    }
    

     二.com.hanqi.util工具包

    package com.hanqi.util;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    //创建数据库连接类
    public class DBHelper {
    	private static final String USERNAME = "Test0315";
    	private static final String PASSWORD = "123456";
    	private static final String URL = "jdbc:oracle:thin:@localhost:1521:xe";
    	private static final String CLASSNAME = "oracle.jdbc.OracleDriver";
    	
    	static {//静态代码块,优先执行且只执行一次
    		try {
    			//加载数据库驱动到驱动管理类,这一步即将数据库厂商提供的ojdbc.jar加载到驱动管理类中
    			Class.forName(CLASSNAME);
    		} catch (ClassNotFoundException e) {
    			e.printStackTrace();
    		}
    	}
    	
    	public static Connection getConnection() {//该方法通过类就可以直接调用,需要设置为静态方法
    		Connection conn = null;
    		try {
    			//使用驱动管理类的方法获取数据库的连接,并返回为数据库连接对象Connection
    			conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}
    		return conn;
    	}
    	//写一个静态方法每次使用完数据处理对象后对其进行销毁,用来释放内存资源;
    	public static void destroy(Connection conn,PreparedStatement ps,ResultSet rs) {
    		if(conn != null) {
    			try {
    				conn.close();
    			} catch (SQLException e) {
    				e.printStackTrace();
    			}
    			conn = null;
    		}
    		if(ps != null) {
    			try {
    				ps.close();
    			} catch (SQLException e) {
    				e.printStackTrace();
    			}
    			ps = null;
    		}
    		if(rs != null) {
    			try {
    				rs.close();
    			} catch (SQLException e) {
    				e.printStackTrace();
    			}
    			rs = null;
    		}
    	}
    	//该方法打印结果为oracle.jdbc.driver.T4CConnection@93a7ca,用来测试是否连接数据库成功;
    	public static void main(String[] args) {
    		System.out.println(getConnection());
    	}
    }
    

     三.数据库访问对象包

    1.先写一个父类对象,存放通用的方法

    package com.hanqi.dao;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    import com.hanqi.util.DBHelper;
    
    public class Basedao {
    	protected PreparedStatement ps;
    	protected Connection conn;
    	protected ResultSet rs;
    	//设置预执行参数,这里将设置参数单独拿出写成方法,需要时直接调用
    	protected void setParam(PreparedStatement ps, Object... objects) throws SQLException {
    		for (int i = 0; i < objects.length; i++) {
    
    			ps.setObject(i + 1, objects[i]);
    		}
    	}
    	//获取数据库连接,创建预执行对象
    	protected void init(String sql) throws SQLException {
    		conn = DBHelper.getConnection();
    		ps = conn.prepareStatement(sql);
    	}
    	//关闭数据库连接
    	protected void close() {
    		DBHelper.destroy(conn, ps, rs);
    	}
    }
    

     2.用户数据库访问对象

    package com.hanqi.dao;
    
    import java.sql.SQLException;
    
    import com.hanqi.model.Users;
    
    public class Usersdao extends Basedao {
    	//用户注册验证,返回值如果为0则可以注册
    	public int selectUsersExists(String username) throws SQLException {
    		String sql ="select count(1) num from users u where u.username = ?";
    		init(sql);
    		setParam(ps, username);
    		rs = ps.executeQuery();
    		int num = -1;
    		if(rs.next()) {
    			num =rs.getInt("num");
    		}
    		close();
    		return num;
    	}
    	//插入用户注册信息,返回值为受影响的行数
    	public int insertUser(Users user) throws SQLException {
    		int r = -1;
    		String sql = "insert into users values(?,?,?,sq_test.nextval,sysdate,1)";
    		init(sql);
    		setParam(ps, user.getUsername(),user.getPassword(),user.getRealname());
    		r = ps.executeUpdate();
    		close();
    		return r;
    	}
    	//用户登录验证,返回值为从数据库中获取的用户对象
    	public Users selectUsers(String username,String password) throws SQLException {
    		Users user = null;
    		String sql = "select u.* from users u where u.username = ? and u.password = ?";
    		init(sql);
    		setParam(ps, username,password);
    		rs = ps.executeQuery();
    		if(rs.next()) {
    			user = new Users();
    			user.setId(rs.getInt("id"));
    			user.setCreatetime(rs.getDate("createtime"));
    			user.setUsername(rs.getString("username"));
    			user.setPassword(rs.getString("password"));
    			user.setRealname(rs.getString("realname"));
    			user.setMark(rs.getInt("mark"));
    		}
    		close();
    		return user;
    	}
    

     3.留言本数据库访问对象

    package com.hanqi.dao;
    
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
    
    import com.hanqi.model.Message;
    
    public class Messagedao extends Basedao {
    	//获取记事本信息
    	public List<Message> SelectMessage() throws SQLException {
    		List<Message> list = new ArrayList<>();//实例化一个集合
    		String sql = "select m.* from message m ";//写sql查询语言
    		init(sql);//将语言传入预执行方法
    		rs = ps.executeQuery();//执行查询语言
    		while(rs.next()) {//如果能查到数据,将数据依次放入留言本对象中,再将对象添加到集合中
    			Message m = new Message();
    			m.setId(rs.getInt("id"));
    			m.setContent(rs.getString("content"));
    			m.setCreatetime(rs.getTimestamp("createtime"));
    			m.setUsername(rs.getString("username"));
    			list.add(m);
    		}
    		close();
    		return list;//返回该集合
    	}
    	//插入记事本信息
    	public int InsertMessage(Message m) throws SQLException {
    		int r = -1;
    		String sql = "insert into message m values(sq_test.nextval,?,sysdate,?)";
    		init(sql);
    		setParam(ps, m.getContent(),m.getUsername());
    		r = ps.executeUpdate();
    		close();
    		return r;
    	}
    }
    

     四.JSP网页

    共3个,首页,登录页,注册页

    <%@ 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 = "LoginRegisterServlet" method = "post" >
    	<input type = "hidden" name = "flag" value = "reg" >
    	用户名:<input type = "text" name = "username" ><br>
    	密码:<input type = "text" name = "password"><br>
    	确认密码:<input type = "text" name = "password2"><br>
    	真实姓名:<input type = "text" name = "realname"><br>
    	<input type = "submit" value = "注册"><br>
    </form>
    <a href="login.jsp">返回登录</a>
    ${requestScope.errmsg}
    </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">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>登录页</title>
    </head>
    <body>
    <form action = "LoginRegisterServlet" method = "post"  >
    	<input type = "hidden" name = "flag" value = "log" > 
    	用户名:<input type = "text" name = "username" ><br>
    	密码:<input type = "text" name = "password"><br>
    	<input type = "submit" value = "登录"><br>
    </form>
    <a href="register.jsp">返回注册</a>
    ${requestScope.errmsg}
    </body>
    </html>
    
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ page import="com.hanqi.model.*"%>
    <%@ page import="java.util.*"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <!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>
    <h1>欢迎${sessionScope.currentUser}</h1>
    <form action="MessageServlet" method="post">
    	<textarea name="msg" style=" 350px; height: 100px; resize: none; font-family: microsoft yahei;"></textarea>
    	<input type="submit" value="保存留言" />
    </form>
    <hr>
    <c:forEach items="${requestScope.msgList }" var="msglist">
    	${msglist.content }<br>
    	${msglist.createtime }<br>
    	${msglist.username }<br>
    	<br>
    </c:forEach> 
    </body>
    </html>
    

     五.servlet包

    1.用户登录注册服务页

    package com.hanqi.servlet;
    
    import java.io.IOException;
    import java.sql.SQLException;
    
    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 com.hanqi.dao.Usersdao;
    import com.hanqi.model.Users;
    
    /**
     * Servlet implementation class loginRegister
     * 该页为用户注册登录服务端,当用户进行注册或登录请求时会在此端进行接收,
     * 该页代码效果为当用户注册时会现将用户名带入到数据库中进行唯一验证,如果查不到并且密码二次确认成功后
     * 会将该用户信息封装为用户对象并保存在数据库中;
     * 
     * 当用户登录时,会将该信息带入数据库进行查询,如果能查到则取出该用户对象,
     * 并保存在会话作用域中重定向到首页服务端。
     */
    @WebServlet("/LoginRegisterServlet")//注解
    public class LoginRegisterServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
        
        public LoginRegisterServlet() {
            super();
        }
    
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		
    		request.setCharacterEncoding("utf-8");//设置编码格式
    		response.setCharacterEncoding("utf-8");
    		response.setContentType("text/html;charset=utf-8");
    		Usersdao ud = new Usersdao();//示例用户数据访问对象
    		String flag = request.getParameter("flag");
    		if(flag == null|| flag.trim().length()<=0) {//判断是否为非法访问
    			response.sendRedirect("register.jsp");
    		}
    		if("reg".equals(flag)) {//用户注册时执行代码
    			String username = request.getParameter("username");
    			String password = request.getParameter("password");
    			String password2 = request.getParameter("password2");
    			String realname = request.getParameter("realname");
    			if(!check(username, password,password2,realname)) {//非空验证
    				request.setAttribute("errmsg", "请正确输入信息!");
    				request.getRequestDispatcher("register.jsp").forward(request, response);
    			}else {
    				int r = -1;
    				try {
    					r = ud.selectUsersExists(username);//验证用户唯一性
    				} catch (SQLException e) {
    					e.printStackTrace();
    				}
    				if(r == 0) {//如果查不到执行代码
    					if(password.equals(password2)) {//密码重复验证
    						Users user = new Users();//实例化用户对象
    						user.setUsername(username);
    						user.setPassword(password);
    						user.setRealname(realname);
    						int updateCount = 0;
    						try {
    							updateCount = ud.insertUser(user);//将用户对象存入数据库
    						} catch (SQLException e) {
    							e.printStackTrace();
    						}
    						if(updateCount > 0) {
    							request.setAttribute("errmsg","注册成功!");
    							request.getRequestDispatcher("register.jsp").forward(request, response);
    						}else {
    							request.setAttribute("errmsg","后台异常!");
    							request.getRequestDispatcher("register.jsp").forward(request, response);
    						}
    					}else {
    						request.setAttribute("errmsg", "两次密码输入不同!");
    						request.getRequestDispatcher("register.jsp").forward(request, response);
    					}
    				}else {
    					request.setAttribute("errmsg", "该用户名已存在!");
    					request.getRequestDispatcher("register.jsp").forward(request, response);
    				}
    			}
    		}
    		
    		if("log".equals(flag)) {//用户登录时执行代码
    			String username = request.getParameter("username");
    			String password = request.getParameter("password");
    			if(!check(username,password)) {//非空验证
    				request.setAttribute("errmsg", "请正确输入信息!");
    				request.getRequestDispatcher("login.jsp").forward(request, response);
    			}else {
    				Users user = null;
    				try {
    					user = ud.selectUsers(username, password);//将用户名和密码带入数据库查询
    				} catch (SQLException e) {
    					e.printStackTrace();
    				}
    				if(user != null) {//如果能查询到保存该对象,重定向到首页服务页
    					request.getSession().setAttribute("currentUser", user);
    					response.sendRedirect("IndexServlet");
    				}else {
    					request.setAttribute("errmsg", "密码错误!");
    					request.getRequestDispatcher("login.jsp").forward(request, response);
    				}
    				
    			}
    		}
    	}
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	
    		doGet(request, response);
    	}
    	private static boolean check(String...strings) {//非空验证方法
    		for (String string : strings) {
    			if (string == null||string.trim().length()<=0) {
    				return false;
    			}
    		}
    		return true;
    	}
    }
    

     2.首页服务页

    package com.hanqi.servlet;
    
    import java.io.IOException;
    import java.sql.SQLException;
    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 com.hanqi.dao.Messagedao;
    import com.hanqi.model.Message;
    import com.hanqi.model.Users;
    
    /**
     * Servlet implementation class IndexServlet
     * 该页为首页服务端,当用户登录成功后会重定向到此页,
     * 该页代码效果为将数据库里的Message对象以集合形式全部取出,
     * 并保存在请求作用域中转发到首页。
     */
    @WebServlet("/IndexServlet")
    public class IndexServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
           
        public IndexServlet() {
            super();
            // TODO Auto-generated constructor stub
        }
       
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		request.setCharacterEncoding("utf-8");//设置编码格式
    		response.setCharacterEncoding("utf-8");
    		response.setContentType("text/html;charset=utf-8");
    		Users user = (Users)request.getSession().getAttribute("currentUser");//获取该用户对象
    		Messagedao md = new Messagedao();//实例留言本数据访问对象
    		if(user == null) {
    			request.setAttribute("errmsg", "用户名已失效!");
    			request.getRequestDispatcher("login.jsp").forward(request, response);
    		}else {
    			List<Message> list = null;
    			try {
    				list = md.SelectMessage();//获取数据库里的所有信息存放在list集合中
    			} catch (SQLException e) {
    				e.printStackTrace();
    			}
    			request.setAttribute("msgList", list);//将list集合保存在请求作用域中并请求转发到首页
    			request.getRequestDispatcher("/WEB-INF/page/Index.jsp").forward(request, response);
    		}
    	}
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// TODO Auto-generated method stub
    		doGet(request, response);
    	}
    }
    

     3.留言本服务页

    package com.hanqi.servlet;
    
    import java.io.IOException;
    import java.sql.SQLException;
    
    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 com.hanqi.dao.Messagedao;
    import com.hanqi.model.Message;
    import com.hanqi.model.Users;
    
    /**
     * Servlet implementation class Message
     * 该页为留言本服务端,当用户在首页提交留言请求后在此端用于接收文本内容,
     * 该页代码效果为将文本内容封装为记事本对象存放到数据库中,
     * 并重定向到首页服务端。
     */
    @WebServlet("/MessageServlet")
    public class MessageServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
           
        /**
         * @see HttpServlet#HttpServlet()
         */
        public MessageServlet() {
            super();
            // TODO Auto-generated constructor stub
        }
    
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		request.setCharacterEncoding("utf-8");
    		response.setCharacterEncoding("utf-8");
    		response.setContentType("text/html; charset=utf-8");
    		Messagedao md = new Messagedao();
    		Users user = (Users)request.getSession().getAttribute("currentUser");
    		if(user == null) {
    			request.setAttribute("errmsg", "用户名已失效!");
    			request.getRequestDispatcher("login.jsp").forward(request, response);
    		}else {
    			String msg = request.getParameter("msg");//获取留言本文本内容
    			if(msg != null&& msg.trim().length()>0) {
    				Message m = new Message();//实例化留言本对象,将用户名和留言内容放入对象中
    				m.setContent(msg);
    				m.setUsername(user.getUsername());
    				int r = -1;
    				try {
    					 r = md.InsertMessage(m);//将留言本对象保存在数据库中
    				} catch (SQLException e) {
    					e.printStackTrace();
    				}
    				if(r > 0) {
    					System.out.println("留言成功!");
    				}else {
    					System.out.println("留言失败!");
    				}
    			}
    			response.sendRedirect("IndexServlet");//重定向到首页服务页
    		}
    	}
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// TODO Auto-generated method stub
    		doGet(request, response);
    	}
    }
    
  • 相关阅读:
    setTimeout,setInterval你不知道的…
    浏览器console的用法
    命题和命题的否定可以同时成立吗?
    Web云笔记--CSS
    dreamweaver代码提示失效
    游戏平台代表--PS4【推荐】
    Mac上好用的视频播放器有哪些?
    新浪博客“网络繁忙请稍后再试”
    人工智能成功识别“色情暴力”信息??…
    JS查错小工具-三生有幸【推荐】
  • 原文地址:https://www.cnblogs.com/wyc1991/p/9131441.html
Copyright © 2020-2023  润新知