时间:2023-10-06 18:00:01 | 来源:网站运营
时间:2023-10-06 18:00:01 来源:网站运营
Java Web实验报告:MVC模式及其应用:注:本实验代码要根据实际做适当修改才能运行package demo.JavaBeans;public class User { String username = null; String password = null; 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; }}
第二步:设计DAO对象 (统一放在deom.DAO包下)package demo.DAO;import java.sql.*;import javax.sql.DataSource;import javax.naming.*;public interface DAO { // 查找并返回数据源对象 public static DataSource getDataSource(){ DataSource dataSource = null; try { Context context = new InitialContext(); dataSource = (DataSource)context.lookup("java:comp/env/jdbc/DBLoginDS"); //上面的参数参照context.xml 配置属性 name="jdbc/DBLoginDS" }catch(NamingException ne){ System.out.println("异常:"+ne); } return dataSource; } // 返回连接对象方法 public default Connection getConnection() throws DAOException { DataSource dataSource = getDataSource(); Connection conn = null; try{ conn = dataSource.getConnection(); }catch(SQLException sqle){ System.out.println("异常:"+sqle); } return conn; } }
设计DAOException类是一个异常类,当DAO类中的方法发生运行时异常时抛出异常。package demo.DAO;public class DAOException extends Exception{ private static final long serialVersionUID = 19192L; private String message; public DAOException() {} public DAOException(String message){ this.message = message; } public String getMessage(){ return message; } public void setMessage(String message) { this.message = message; } public String toString(){ return message; }}
UserDAO类实现了DAO接口提供了对User对象的持久化的各种方法package demo.DAO;import demo.JavaBeans.User;import java.util.*;import java.sql.*;import demo.JavaBeans.User;import java.util.logging.Level;import java.util.logging.Logger;public class UserDAO implements DAO { //addUser(User user)添加用户 public boolean addUser(User user) throws DAOException { Connection conn = getConnection(); String sql = "INSERT INTO tb_user(username,password) VALUES(?,?)"; try { PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, user.getUsername()); pstmt.setString(2, user.getPassword()); pstmt.executeUpdate(); } catch (SQLException sqle) { System.out.println(sqle); return false; } try { conn.close(); } catch (SQLException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } return true; } /* find(User user) 在数据库中查询是否存在user的记录, 存在返回true,否则返回false */ public boolean find(User user) throws DAOException { String sql = "SELECT * FROM tb_user WHERE username =? and password=?"; //User user = new User(); try ( Connection conn = getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setString(1, user.getUsername()); pstmt.setString(2, user.getPassword()); try (ResultSet rst = pstmt.executeQuery()) { if (rst.next()) { //user.setUsername(rst.getString("username")); //user.setPassword(rst.getString("password")); conn.close(); return true; } } } catch (SQLException se) { System.out.println(se); return false; } return false; }}
第三步:视图类设计 login.jsp+register.jsp实现登陆和注册界面,并且分别实现了异常处理视图。<%@page contentType="text/html" pageEncoding="UTF-8"%><!DOCTYPE html><html> <head> <title>登录</title> <script> <%-- 这里是JavaScript --%><%-- html加载完毕后,立刻执行--%>window.onload = function () { document.getElementById("img").onclick = function () { <%-- document.getElementById()会通过元素的id来获取整个元素, 也就是说先获取. "img" 元素, 然后.onclick(),点击触发一个事件,这个事件会执行funciton()函数。 目的就是点击id为img的这个页面元素,就会触发funciton函数。--%> this.src = "CheckcodeServlet?time" + new Date().getTime(); <%-- 疑问点 --> <%-- 增加时间戳来更换验证码图片 --%> };}; </script> <script type="text/javascript"> function Check() { for(var i=0;i<document.form1.elements.length-1;i++) { if(document.form1.elements[i].value=="") { alert("不允许空!"); document.form1.elements[i].focus(); return false; } } return true; } </script><style> div{ color: red; }</style> </head> <body> <form action="LoginServlet" method="post" name="form1" onSubmit="return Check()"> <!--疑问点:return--> <table> <tr> <td>用户名</td> <td><input type="text" name="username" size="25"></td> </tr> <tr> <td>密码</td> <td><input type="text" name="password" size="25"></td> </tr> <tr> <td>验证码</td> <td><input type="text" name="checkcode" size="15"> <img id="img" src="CheckcodeServlet" alt="" size="10" align="center"> <!id为img的页面元素,验证码图像; (JavaScript:document.getElementById("img").onclick )> </td> </tr> <tr> <td><input type="submit" value="登录"></td> <td>无账号请<a href="regist.jsp">注册</a></td> <!单击打开注册界面(JavaScript:function reg())> </tr> </table> </form> <%-- 用户名或密码错误 --%> <div>${requestScope.login_error}</div> <%-- 验证码错误 --%> <div>${requestScope.checkcode_error}</div> </body></html>
register.jsp实现注册界面。<%@page contentType="text/html" pageEncoding="UTF-8"%><!DOCTYPE html><script type="text/javascript"> <%--检查是否表单内容均已填写 --%> function Check() { for(var i=0;i<document.form1.elements.length-1;i++) { if(document.form1.elements[i].value=="") { alert("不允许空!"); document.form1.elements[i].focus(); return false; } } return true; } </script><style> div{ color: red; }</style><html><head> <title>注册</title></head><body><form action="RegistServlet" method="post" name="form1" onSubmit="return Check()"> <table> <tr> <td>用户名</td> <td><input type="text" name="username"></td> </tr> <tr> <td>密   码</td> <td><input type="text" name="password"></td> </tr> </table> <p><input type="submit" value="确定注册"> 有账号请直接<a href="login.jsp">登录</a></form><%-- 注册成功 --%><div>${requestScope.regist_success}</div><%-- 用户名被占有,注册失败 --%><div>${requestScope.regist_error}</div></body></html>
success.jsp实现登陆成功界面<%@page contentType="text/html" pageEncoding="UTF-8"%><!DOCTYPE html><html><head> <title>Title</title></head><body><%-- <h1>欢迎您${requestScope.user}</h1> --%> <h1>欢迎您<%=request.getSession().getAttribute("user")%></h1></body></html>
STEP 4:控制器设计package demo.Servlet;import demo.DAO.DAOException;import demo.DAO.UserDAO;import demo.JavaBeans.User;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 javax.servlet.http.HttpSession;import java.io.IOException;import java.util.logging.Level;import java.util.logging.Logger;import javax.servlet.RequestDispatcher;@WebServlet("/LoginServlet")public class LoginServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置字符编码 request.setCharacterEncoding("utf-8"); //读客户端参数 String username = request.getParameter("username");//读用户名 String password = request.getParameter("password");//读口令 String checkcode = request.getParameter("checkcode");//获取生成的验证码 // System.out.println(username+":"+password+":"+checkcode); HttpSession session = request.getSession(); String checkcode_session = (String) session.getAttribute("checkcode_session"); //防止验证码存储 删除Session中存储的验证码 //checkcode-session来自CheckcodeServlet中的会话设置 session.removeAttribute("checkcode_session"); //判断验证码是否正确,equalsIgnoreCase忽略大小写的比较 if (checkcode_session != null && checkcode_session.equalsIgnoreCase(checkcode)) { //验证码正确 User user = new User(); user.setUsername(username); user.setPassword(password); boolean flag = false; UserDAO userdao = new UserDAO(); try { flag = userdao.find(user); } catch (DAOException ex) { System.out.println(ex); } if (flag) { //用户名和口令正确,登录成功 //储用户信息到会话:session session.setAttribute("user", username); //请求转发到success.jsp(不能重定向) RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/success.jsp"); rd.forward(request, response); } else { //用户名或口令错误,登录失败 //提示信息存储到请求对象:request request.setAttribute("login_error", "用户名或口令错误"); //请求转发到登录页面login.jsp request.getRequestDispatcher("/login.jsp").forward(request, response); } } else { //验证码错误,提示信息到存储请求对象:request request.setAttribute("checkcode_error", "验证码错误"); //请求转发到登录页面 request.getRequestDispatcher("/login.jsp").forward(request, response); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // this.doPost(request, response); }}
RegisterServlet使用了DAO对象和持久化对象,实现了注册界面的后台处理功能。package demo.Servlet;import demo.DAO.*;import demo.JavaBeans.User;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 java.io.IOException;@WebServlet("/RegistServlet")public class RegistServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); //读取用户输入的用户名和口令 String username = request.getParameter("username"); String password = request.getParameter("password"); //实例化user对象 User user = new User(); user.setUsername(username); user.setPassword(password); boolean flag=false; try { flag = new UserDAO().addUser(user);//把user写入数据库(usernmae,password) } catch (DAOException ex) { System.out.println(ex); } if(flag) { request.setAttribute("regist_success","注册成功"); //请求转发regist.jsp request.getRequestDispatcher("/regist.jsp").forward(request,response); }else{ request.setAttribute("regist_error","用户名被占用,注册失败"); //请求转发regist.jsp request.getRequestDispatcher("/regist.jsp").forward(request,response); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request,response); }}
运行结果:关键词:模式,实验,报告