标签:java web
接上节:http://4440271.blog.51cto.com/4430271/1661880
修改校验逻辑,从数据库中获取用户信息进行校验:
结合jsp, jdbc, servlet;
首先,修改UserDao接口
添加方法声明,用来根据用户名和密码获取用户信息。
代码:
package com.jike.dao; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import com.jike.entity.User; //定义实现类的行为 public interface UserDao { //定义对数据库的操作 public void save(Connection conn, User user) throws SQLException; public void update(Connection conn, Long id, User user) throws SQLException; public void delete(Connection conn, User user) throws SQLException; // 登陆页面 public ResultSet get(Connection conn, User user) throws SQLException; }
添加具体实现,添加方法:
代码:
package com.jike.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import com.jike.dao.UserDao; import com.jike.entity.User; public class UserDaoImpl implements UserDao { /* * 保存用户信息 */ @Override public void save(Connection conn, User user) throws SQLException { // TODO Auto-generated method stub //PreparedStatement是jdbc用于执行sql查询语句的api之一,用来执行参数化的查询 //?是占位符 PreparedStatement ps = conn.prepareStatement ("insert into tbl_user(name, password, email) values (?,?,?)"); //参数设置 ps.setString(1, user.getName());//索引从1开始 ps.setString(2, user.getPassword()); ps.setString(3, user.getEmail()); ps.execute(); //将参数传入的user对象中的相关信息保存到数据库表中 } /* * 根据用户id更新用户信息 */ @Override public void update(Connection conn, Long id, User user) throws SQLException { // TODO Auto-generated method stub String updateSql = "update tbl_user set name=?, password=?, email=? where id=?"; PreparedStatement ps = conn.prepareStatement(updateSql); ps.setString(1, user.getName()); ps.setString(2, user.getPassword()); ps.setString(3, user.getEmail()); ps.setLong(4, id); ps.execute(); } /* * 删除指定的用户信息 */ @Override public void delete(Connection conn, User user) throws SQLException { // TODO Auto-generated method stub PreparedStatement ps = conn.prepareStatement("delete from tbl_user where id=?"); ps.setLong(1, user.getId()); ps.execute(); } @Override public ResultSet get(Connection conn, User user) throws SQLException { // TODO Auto-generated method stub PreparedStatement ps = conn.prepareStatement ("select * from tbl_user where name = ? and password = ?"); ps.setString(1, user.getName()); ps.setString(2, user.getPassword()); return ps.executeQuery(); } }
创建service类, 在service类中执行登陆校验的逻辑。它调用Dao层的数据库访问逻辑判断数据是否获取成功,如果成功获取,则返回布尔值true,否则返回false。
package com.jike.service; import java.sql.Connection; import com.jike.dao.UserDao; import com.jike.dao.impl.UserDaoImpl; import com.jike.entity.User; import com.jike.jdbc.util.ConnectionFactory; import com.mysql.jdbc.ResultSet; //校验用户信息 public class CheckUserService { private UserDao userDao = new UserDaoImpl(); public boolean check(User user){//执行登陆校验逻辑 Connection conn = null; try { conn = ConnectionFactory.getInstance().makeConnection(); conn.setAutoCommit(false); ResultSet resultSet = (ResultSet)userDao.get(conn, user);//执行查询 while(resultSet.next()){//如果查询到,返回true return true; } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); try { conn.rollback(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } }finally{ try { conn.close(); } catch (Exception e3) { // TODO: handle exception e3.printStackTrace(); } } return false; } }
控制层:
新建Servlet:
package com.jike.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.jike.entity.User; import com.jike.service.CheckUserService; //CheckServlet作为控制器,根据CheckUserServlet的校验结果,将用户导航到不同的页面 public class CheckServlet extends HttpServlet { /** * */ private static final long serialVersionUID = -2941368629779903572L; private CheckUserService cku = new CheckUserService(); public CheckServlet() { super(); } public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取用户提交的信息 String uname = request.getParameter("uname"); String passwd = request.getParameter("upwd"); RequestDispatcher rd = null; String forward = null; // 非空判断 if(uname == null || passwd == null){ request.setAttribute("msg", "用户名或密码为空"); rd = request.getRequestDispatcher("/09/error.jsp"); rd.forward(request, response); }else{ //若合法,则登陆校验 User user = new User(); user.setName(uname); user.setPassword(passwd); //进行校验 boolean bool = cku.check(user); //根据校验结果进入不同页面 if(bool){ forward = "/09/success.jsp"; }else{ request.setAttribute("msg", "用户名或密码错误,请重新输入!"); forward = "/09/error.jsp"; } rd = request.getRequestDispatcher(forward); rd.forward(request, response); } } public void init() throws ServletException { // Put your code here } }
在web.xml中添加配置信息
<servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>CheckServlet</servlet-name> <servlet-class>com.jike.servlet.CheckServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CheckServlet</servlet-name> <url-pattern>/CheckServlet</url-pattern> </servlet-mapping>
表示层登陆页面设置:
在WebRoot下创建09文件夹,创建login.jsp
<%@ 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"> <!-- 使用css美化当前页面 --> <style type="text/css"> body{ color: #000; font-size: 14px; margin: 20px auto; } </style> <script type="text/javascript"> function check(form){ if(document.forms.loginForm.uname.value==""){ alert("请输入用户名"); document.forms.loginForm.uname.focus(); return false; } if(document.forms.loginForm.upwd.value==""){ alert("请输入密码"); document.forms.loginForm.upwd.focus(); return false; } } </script> <title>Insert title here</title> </head> <body> <form action="<%= request.getContextPath() %>/CheckServlet" name="loginForm"> <table border="1" cellspacing="0" cellpadding="5" bordercolor="silver" align="center"> <tr> <!-- 提示信息 --> <td colspan="2" align="center" bgcolor="#E8E8E8">用户登陆</td> </tr> <tr> <td>用户名:</td> <td><input type="text" name="uname" /></td> </tr> <tr> <td>密码:</td> <td><input type="password" name="upwd" /></td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" name="submit" onclick="return check(this);"/> <input type="reset" name="reset"/> </td> </tr> </table> </form> </body> </html>
添加success.jsp
<%@ 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"> <style type="text/css"> body{ color: #000; font-size: 14px; margin: 20px auto; } #message{ text-align: center; } </style> <title>Insert title here</title> </head> <body> <div id="massage"> 登陆成功<br/> 用户名: <%= request.getParameter("uname") %><br/> 密码:<%= request.getParameter("upwd") %><br/> <a href="<%=request.getContextPath()%>/09/login.jsp">返回登陆页面</a> </div> </body> </html>
添加error.jsp
<%@ 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"> <style type="text/css"> body{ color: #000; font-size: 14px; margin: 20px auto; } #message{ text-align: center; } </style> <title>Insert title here</title> </head> <body> <div id="massage"> 登陆失败<br/> 错误提示 <% Object obj = request.getAttribute("msg"); if(obj !=null){ out.println(obj.toString()); }else{ out.println("无"); } %> <br/> 用户名: <%= request.getParameter("uname") %><br/> 密码:<%= request.getParameter("upwd") %><br/> <a href="<%=request.getContextPath() %>/09/login.jsp">返回登陆页面</a> </div> </body> </html>
测试程序:
标签:java web
原文地址:http://4440271.blog.51cto.com/4430271/1662035