1 首先导入jar包(看个人情况导入)
这里需要注意的是平时我们导入jar包是导入在自己的工程或者moudle下面的,在这里我们必须把jar包导入在WEB-INF中(详情可看图),从图中可看出,一个工程在编译过后,只有src下的数据会编译到WEB-INF下的classes目录中,所以需要将静态资源,jar包等资源放到web或者WEB-INF中。
应用与项目的关系
2 连接数据库,我们可以先导入配置文件utils(自己写的druid连接池)
public class DruidUtils {
private static DataSource ds;
static {
Properties pro = new Properties();
try {//1.加载配置文件
pro.load(DruidUtils.class.getResourceAsStream("jdbc.properties"));
//.2.获取DataSource
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (Exception e) {
throw new RuntimeException(e);
}
}//获取连接
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
//获取连接池方法
public static DataSource getDataSource(){
return ds;
}
//释放资源
public static void close(Connection conn, PreparedStatement stmt, ResultSet rs){
try {
if (rs == null) rs.close();
if (stmt == null) rs.close();
if (conn == null) rs.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
编写配置文件(仅供参考,要注意的是末尾的.properties后缀名不能写错)
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql:///wyb?serverTimezone=GMT
username=root
password=gg791480
3.编写登录代码:
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
JdbcTemplate template = new JdbcTemplate(DruidUtils.getDataSource());
String sql = "select * from user where name=? and poaaword=?";
try {
User user = template.queryForObject(sql,new BeanPropertyRowMapper<>(User.class),username,password);
response.sendRedirect(request.getContextPath()+"index.jsp");
}catch (Exception e){
response.sendRedirect(request.getContextPath()+"/html/loser.html");
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
4.接下来我们用Java的三层架构规范来实现功能
4.1 首先用三成架构的方式分析登录功能,如果所示,我们在web包下实现获取参数,发送请求,service包下处理数据,dao包下连接数据库
4.2如图,我们在src下创建一个包,然后再包下再创建如下包
web层下代码:
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private UserSerivce userSerivce =new UserSerivceImpl();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
try {
User loginUser = userSerivce.login(username, password);
request.getSession().setAttribute("user",loginUser);
response.sendRedirect(request.getContextPath()+"/index.jsp");
}catch (Exception e){
request.setAttribute("error",e.getMessage());
request.getRequestDispatcher("/login.jsp").forward(request,response);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
test层(测试代码用)
utils层(编写配置文件,与上述一致)
service层代码(一般会先写一个接口,然后再实现其接口
public interface UserSerivce {
User login(String username, String password) throws Exception;
}
)
public class UserSerivceImpl implements UserSerivce {
private UserDao userDao = new UserDaoImpl();
@Override
public User login(String username,String password) throws Exception {
User user = userDao.findByUsernameAndPassword(username, password);
if (user == null) {
throw new Exception("登录或密码错误");
}
return user;
}
}
domain成代码(通过是写实体类)
public class User {
private Integer id;
private String name;
private Integer password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getPassword() {
return password;
}
public void setPassword(Integer password) {
this.password = password;
}
}
dao层(连接数据库代码)
public interface UserDao {
User findByUsernameAndPassword(String username, String password);
}
public class UserDaoImpl implements UserDao {
private JdbcTemplate template = new JdbcTemplate(DruidUtils.getDataSource());
@Override
public User findByUsernameAndPassword(String username,String password){
String sql = "select * from user where name=? and possword=?";
List<User> list = template.query(sql, new BeanPropertyRowMapper<>(User.class), username, password);
return list.size() == 0 ? null : list.get(0);
}
}
4.3 登录页面(login.jsp,参考)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/login" method="post">
用户名<input type="text" name="username"><br>
密码<input type="password" name="password"><br>
<sp>${error}</sp>
<input type="submit" value="登录">
</form>
</body>
</html>