总图
图片.png
百度网盘:
链接:https://pan.baidu.com/s/13yIlRuOmRd-_OSnKMnfl5A
提取码:7nr3
1、补充web.xml
<servlet>
<servlet-name>UserLoginServlet</servlet-name>
<servlet-class>com.llhc.servlet.UserLoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserLoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
2、用户model
package com.llhc.model;
public class User {
private int id;
private String name;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
3、dao层
package com.llhc.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.llhc.model.User;
public class UserDao {
public User getUser(String name,String password){
//产品查询
User user = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/db_web_cart?characterEncoding=UTF-8","root","root");
String sql = "select * from user where name = ? and password = ?";
PreparedStatement p=conn.prepareStatement(sql);
p.setString(1, name);
p.setString(2, password);
ResultSet rs=p.executeQuery();
while(rs.next()){
user=new User();
user.setId(rs.getInt("id"));
user.setPassword(password);
user.setName(name);
}
} catch (Exception e) {
// TODO: handle exception
}
return user;
}
}
4、Servlet层
package com.llhc.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 com.llhc.dao.UserDao;
import com.llhc.model.User;
public class UserLoginServlet extends HttpServlet{
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(req,resp);
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
String name = req.getParameter("name");
String password = req.getParameter("password");
UserDao p = new UserDao();
User u=p.getUser(name, password);
if(null != u){
req.getSession().setAttribute("user", u);
resp.sendRedirect("listProduct");
}else{
resp.sendRedirect("login.jsp");
}
}
}
5、前端页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<form action="login" method="post">
账号: <input type="text" name="name"> <br>
密码: <input type="password" name="password"> <br>
<input type="submit" value="登录">
</form>
6、访问:http://localhost/Cart/login.jsp
网友评论