一、前言
二、案例需求
1.編寫login.html登錄頁面,username&password兩個(gè)輸入框
2.使用Druid數(shù)據(jù)庫連接池技術(shù),操作mysql,day14數(shù)據(jù)庫中的user表
3.使用jdbcTemplate技術(shù)封裝JDBC
4.登錄成功跳轉(zhuǎn)到SuccessServlet展示:登錄成功!用戶名,歡迎你
5.登錄失敗跳轉(zhuǎn)到FailServlet展示:登錄失敗密碼錯(cuò)誤
三、開始第一步
首先創(chuàng)建項(xiàng)目,寫html頁面,配置文件,jar包
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/day14/loginServlet" method="post">
用戶名:<input type="text" name="username"> <br>
密碼:<input type="password" name="password"> <br>
<input type="submit" value="登錄">
</form>
</body>
</html>
druid.properties配置文件:
driverClassName=com.mysql.cj.jdbc.Driver url=jdbc:mysql:///day14 username=root password=root #初始化連接數(shù)量 initialSize=5 #最大連接數(shù) maxActive=10 #最大等待時(shí)間 maxWait=3000 filters=stat timeBetweenEvictionRunsMillis=60000 minEvictableIdleTimeMillis=300000 validationQuery=SELECT 1 testWhileIdle=true testOnBorrow=false testOnReturn=false poolPreparedStatements=false maxPoolPreparedStatementPerConnectionSize=200
導(dǎo)入jar包:
四、第二步
創(chuàng)建user類:
package com.wzc.domain;
//用戶的實(shí)體類
public class User {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int 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;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + ''' +
", password='" + password + ''' +
'}';
}
}
五、第三步
創(chuàng)建jdbcUtils工具類
package com.wzc.util;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
//JDBC工具類 使用Druid連接池
public class JDBCUtils {
private static DataSource ds ;
static {
try {
// 加載配置文件
Properties pro = new Properties();
// 使用ClassLoader加載配置文件,獲取字節(jié)輸入流
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
pro.load(is);
// 初始化連接池對象
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
// 初始化連接池
}
/*獲取連接池對象*/
public static DataSource getDataSource(){
return ds;
}
/*獲取連接connection對象*/
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
}
創(chuàng)建UserDao類,提供login方法:
package com.wzc.dao;
import com.wzc.domain.User;
import com.wzc.util.JDBCUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
//操作數(shù)據(jù)庫中user表的類
public class UserDao {
// 聲明JDBCTemplate對象共用
private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
/**
* 登錄方法
* @param loginUser 只有用戶名和密碼
* @return user包含用戶全部數(shù)據(jù),沒有查詢到則返回null
*/
public User login(User loginUser){
try{
// 編寫sql
String sql = "select * from user where username = ? and password = ?";
// 調(diào)用query方法
User user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class),
loginUser.getUsername(), loginUser.getPassword());
return user;
} catch (DataAccessException e){
e.printStackTrace();
// 記錄日志
return null;
}
}
}
編寫loginServlet類:
package com.wzc.web.servlet;
import com.wzc.dao.UserDao;
import com.wzc.domain.User;
import org.apache.commons.beanutils.BeanUtils;
import javax.servlet.ServletContext;
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;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 設(shè)置編碼
req.setCharacterEncoding("utf-8");
/*// 獲取請求參數(shù)
String username = req.getParameter("username");
String password = req.getParameter("password");
// 封裝user對象
User loginUser = new User();
loginUser.setUsername(username);
loginUser.setPassword(password);*/
// 獲取所有請求參數(shù)
Map<String,String[]> map = req.getParameterMap();
// 創(chuàng)建User對象
User loginUser = new User();
// 使用BeanUtils封裝
try {
BeanUtils.populate(loginUser,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
// 調(diào)用UserDao的login方法
UserDao dao = new UserDao();
User user = dao.login(loginUser);
// 判斷user
if (user == null){
// 登錄失敗
req.getRequestDispatcher("/failServlet").forward(req,resp);
}else{
// 登錄成功
// 存儲數(shù)據(jù)
req.setAttribute("user",user);
// 轉(zhuǎn)發(fā)
req.getRequestDispatcher("/successServlet").forward(req,resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
}
六、第四步
編寫SuccessServlet類:
package com.wzc.web.servlet;
import com.wzc.domain.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(name = "/successServlet")
public class SuccessServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 獲取request域中共享的user對象
User user = (User)request.getAttribute("user");
if (user !=null){
//給頁面寫一句話
// 設(shè)置編碼
response.setContentType("text/html;charset=utf-8");
// 輸出
response.getWriter().write("登錄成功!"+user.getUsername()+",歡迎你");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
編寫FailServelt類
package com.wzc.web.servlet;
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("/failServlet")
public class FailServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//給頁面寫一句話
// 設(shè)置編碼
response.setContentType("text/html;charset=utf-8");
// 輸出
response.getWriter().write("登錄失敗,用戶名和密碼錯(cuò)誤");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
輸入錯(cuò)誤的賬號和密碼
登錄失敗提示:
七、總結(jié)
login.html中form表單的action路徑寫法:虛擬路徑+Servlet的資源路徑
**BeanUtils工具類,簡化數(shù)據(jù)封裝:**用于封裝javaBean
javaBean:標(biāo)準(zhǔn)的java類 功能:封裝數(shù)據(jù)
有一下四點(diǎn)要求:
1.類必須被public修飾
2.必須提供空參的構(gòu)造器
3.成員變量必須使用private修飾
4.提供公共setter和getter方法
屬性:setter和getter方法截取后的產(chǎn)物
例如:getUsername()–>Username–>username
可見username就是屬性
方法有三種:
1.setProperty()
2.getProperty()
3.populate(Object obj , Map map):將map集合的鍵值對信息,封裝到對應(yīng)的JavaBean對象中(最常用)
package com.wzc.test;
import com.wzc.domain.User;
import org.apache.commons.beanutils.BeanUtils;
import org.junit.Test;
import java.lang.reflect.InvocationTargetException;
public class BeanUtilsTest {
@Test
public void test(){
User user = new User();
try {
BeanUtils.setProperty(user,"hehe","male");
System.out.println(user);
String gender = BeanUtils.getProperty(user, "hehe");
System.out.println(gender);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
到此這篇關(guān)于Java實(shí)現(xiàn)用戶登錄實(shí)戰(zhàn)練習(xí)的文章就介紹到這了,更多相關(guān)Java實(shí)戰(zhàn)練習(xí)的內(nèi)容,請搜索W3Cschool以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,也希望大家以后多多支持我們!