黑马程序员技术交流社区
标题: servlet登录案例分析【石家庄校区】 [打印本页]
作者: Jack.李 时间: 2017-9-29 16:02
标题: servlet登录案例分析【石家庄校区】
1.登录案例的servlet层代码package cn.itcast.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 cn.itcast.dao.UserDao;
import cn.itcast.dao.impl.UserDaoImpl;
import cn.itcast.domain.User;
public class LoginServlet extends HttpServlet {
private UserService userService = new UserServicempl();
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//解决Post参数乱码
request.setCharacterEncoding("UTF-8");
//1.获得参数(用户名,密码)
String name =request.getParameter("name");
String password =request.getParameter("password");
//非空校验
//2.根据用户名查询数据库,获得User对象
User u = userService .getByName(name);
if(u==null){
// 查询不到=>用户名不存在=>转发到登录页面提示用户名不存在
request.setAttribute("error", "用户名不存在!");
request.getRequestDispatcher("/login.jsp").forward(request, response);
return;
}
//查询到了=>继续执行
//3.比对用户填写的密码与数据库中正确的密码
if(!u.getPassword().equals(password)){
// //比对不一致=>密码错误=>转发到登录页面提示密码错误
request.setAttribute("error", "密码错误!");
request.getRequestDispatcher("/login.jsp").forward(request, response);
return;
}
//比对一致=>继续执行
//直接跳转到首页页面
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
2.登录案例的service层代码package cn.itcast.service;
import cn.itcast.dao.UserDao;
import cn.itcast.dao.impl.UserDaoImpl3;
import cn.itcast.domain.User;
public class UserService {
UserDao userDao = new UserDaoImpl();
public User getByName(String name){
return userDao.getByName(name);
}
}
3.登录案例的dao层代码package cn.itcast.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import cn.itcast.dao.UserDao;
import cn.itcast.domain.User;
import cn.itcast.utils.DBUtils;
public class UserDaoImpl implements UserDao {
public User getByName(String name) {
User u = null;
//1 获得连接
Connection conn = JDBCUtils .getConnection();
//2 准备sql
String sql ="select * from t_user where name = ?";
//3 创建PreparedStatement对象
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(sql);
//4 设置参数
ps.setString(1, name);
//5 执行sql
rs = ps.executeQuery();
//6 封装并返回结果
if(rs.next()){
u = new User();
u.setId(rs.getInt("id"));
u.setName(rs.getString("name"));
u.setPassword(rs.getString("password"));
u.setEmail(rs.getString("email"));
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("根据名称获得用户,执行sql异常");
}finally{
//关闭资源
DBUtils.close(rs, ps, conn);
}
return u;
}
}
4.连接数据库的工具类package cn.itcast.utils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class JDBCUtils {
private static final ComboPooledDataSource DATA_SOURCE =new ComboPooledDataSource();
/**
* 获得连接的方法
*/
public static Connection getConnection(){
Connection conn = null;
try {
conn = DATA_SOURCE.getConnection();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public static DataSource getDataSource(){
return DATA_SOURCE;
}
}
5.连接数据库的配置文件内容<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///day09</property>
<property name="user">root</property>
<property name="password">123</property>
<property name="initialPoolSize">5</property>
<property name="maxPoolSize">20</property>
</default-config>
</c3p0-config>
注意:此文件名称必须是c3p0-config.xml因为当我new ComboPooledDataSource();此类会默认从项目的src下去查找名称是c3p0-config.xml文件,当然也可以不是这个名称,但是此时new ComboPooledDataSource();new对象的时候就要在构造方法里面去填写你指定的文件名称以及路径。
6.登录案例的页面代码<%@ 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>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<h1>用户登录</h1>
<form action="${pageContext.request.contextPath}/LoginServlet" method="post" >
<table border="1" >
<tr>
<td>用户名:</td>
<td><input type="text" name="name" value="${param.name}" /><font color="red" >${errorMap.name}</font></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password" value="" /><font color="red" >${errorMap.password}</font></td>
</tr>
<tr>
<td colspan="2" align="center" ><input type="submit" name="" value="登录" /></td>
</tr>
</table>
<font color="red" >${error}</font>
</form>
</body>
</html>
注意:页面的input框(除提交按钮的input框不需要写name)中必须填有name属性和值,因为表单提交提交的内容是name属性值,此时后台通过request.getParameter("name");就可以直接得到用户输入的值
7.登录案例的web.xml配置代码<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
<display-name></display-name>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>cn.itcast.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |