这里写目录标题
- 一、数据库准备和创建安全jsp与servlet完成用户登录
- 二、数据库表的创建
- 三、核心代码如下
-
-
- ①dao层相关代码
- ②entity层相关代码
- ③filter层相关代码
- ④servlet层相关代码
- ⑤WEB-INF下面的jsp目录文件
- ⑥WEB-INF下面的lib目录文件
- ⑦web.xml
-
- 四、系统测试结果展示如下:
一、数据库准备和创建安全jsp与servlet完成用户登录 ??1.数据库准备步骤地址
??2.安全jsp与servlet创建过程
二、数据库表的创建
文章图片
文章图片
文章图片
三、核心代码如下
文章图片
①dao层相关代码
1.UserDao
package com.allen.dao;
import com.allen.entity.User;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.*;
public class UserDao {
public User login(String loginName,String loginPassword) throws ClassNotFoundException, SQLException, NoSuchAlgorithmException {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql:///picture?useSSL=false", "root", "123456");
PreparedStatement statement = connection.prepareStatement("select * from user where login_name=? and login_password=?");
statement.setObject(1,loginName);
statement.setObject(2,loginPassword);
ResultSet resultSet = statement.executeQuery();
User user=null;
if (resultSet.next()) {
user = new User();
user.setId(resultSet.getInt("id"));
user.setTrueName(resultSet.getString("true_name"));
user.setEmail(resultSet.getString("email"));
user.setLoginName(resultSet.getString("login_name"));
user.setLoginPassword(resultSet.getString("login_password"));
user.setTelephone(resultSet.getString("telephone"));
}
resultSet.close();
statement.close();
connection.close();
return user;
}
//MD5加密方法
private String md5(String loginPassword) throws NoSuchAlgorithmException {
StringBuffer stringBuffer = new StringBuffer(32);
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] bytes = md5.digest(loginPassword.getBytes());
for (int i = 0;
i < bytes.length;
i++) {
stringBuffer.append(Integer.toHexString((bytes[i]&0xFF)|0x100).toUpperCase(),1,3);
}
return stringBuffer.toString();
}
}
2.ImageDao
package com.allen.dao;
import com.allen.entity.Image;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class ImageDao {
public boolean add(Image image) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql:///picture?useSSL=false", "root", "123456");
PreparedStatement statement = connection.prepareStatement("insert into image (original_file_name,relative_paths,create_time,user_id) values (?,?,now(),?)");
statement.setObject(1,image.getOriginalFileName());
statement.setObject(2,image.getRelativePaths());
statement.setObject(3,image.getUserId());
int i = statement.executeUpdate();
statement.close();
connection.close();
return i!=0;
}public List list() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql:///picture?useSSL=false", "root", "123456");
PreparedStatement statement = connection.prepareStatement("select * from image");
ResultSet resultSet = statement.executeQuery();
List list=new ArrayList<>();
while (resultSet.next()) {
Image image = new Image();
image.setUserId(resultSet.getInt("user_id"));
image.setRelativePaths(resultSet.getString("relative_paths"));
image.setOriginalFileName(resultSet.getString("original_file_name"));
image.setId(resultSet.getInt("id"));
image.setCreateTime(resultSet.getTime("create_time"));
list.add(image);
}
resultSet.close();
statement.close();
connection.close();
return list;
}
}
②entity层相关代码
1.Image
package com.allen.entity;
import java.util.Date;
public class Image {private Integer id;
private String originalFileName;
private String relativePaths;
private Date createTime;
private Integer userId;
public Integer getId() {
return id;
}public void setId(Integer id) {
this.id = id;
}public String getOriginalFileName() {
return originalFileName;
}public void setOriginalFileName(String originalFileName) {
this.originalFileName = originalFileName;
}public String getRelativePaths() {
return relativePaths;
}public void setRelativePaths(String relativePaths) {
this.relativePaths = relativePaths;
}public Date getCreateTime() {
return createTime;
}public void setCreateTime(Date createTime) {
this.createTime = createTime;
}public Integer getUserId() {
return userId;
}public void setUserId(Integer userId) {
this.userId = userId;
}
}
2.User
package com.allen.entity;
public class User {
private Integer id;
private String trueName;
private String loginName;
private String loginPassword;
private String telephone;
private String email;
public Integer getId() {
return id;
}public void setId(Integer id) {
this.id = id;
}public String getTrueName() {
return trueName;
}public void setTrueName(String trueName) {
this.trueName = trueName;
}public String getLoginName() {
return loginName;
}public void setLoginName(String loginName) {
this.loginName = loginName;
}public String getLoginPassword() {
return loginPassword;
}public void setLoginPassword(String loginPassword) {
this.loginPassword = loginPassword;
}public String getTelephone() {
return telephone;
}public void setTelephone(String telephone) {
this.telephone = telephone;
}public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
③filter层相关代码
1.LoginFilter
package com.allen.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter("/*")
public class LoginFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {}@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request= (HttpServletRequest) servletRequest;
HttpServletResponse response= (HttpServletResponse) servletResponse;
if (request.getRequestURI().endsWith("login")) {
filterChain.doFilter(request,response);
return;
}if (request.getSession().getAttribute("UserInfo")!=null) {
filterChain.doFilter(request,response);
return;
}
response.sendRedirect(request.getContextPath()+"/login");
}
@Override
public void destroy() {}
}
④servlet层相关代码
1.IndexServlet
package com.allen.servlet;
import com.allen.dao.ImageDao;
import com.allen.entity.Image;
import com.allen.entity.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;
@WebServlet("/index")
@MultipartConfig
public class IndexServlet extends HttpServlet {
ImageDao imageDao = new ImageDao();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
List list = imageDao.list();
request.setAttribute("imageLsit",list);
request.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(request,response);
}catch (Exception e){
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
Part file = request.getPart("file");
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
String fileName = file.getSubmittedFileName();
String type = fileName.substring(fileName.lastIndexOf("."));
file.write("H:\\demotest\\picture-system\\images\\"+uuid+type);
Image image = new Image();
image.setOriginalFileName(fileName);
image.setRelativePaths("/images/"+uuid+type);
User userInfo = (User) request.getSession().getAttribute("UserInfo");
image.setUserId(userInfo.getId());
try {
imageDao.add(image);
response.sendRedirect(request.getContextPath()+"/index");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
2.LoginServlet
package com.allen.servlet;
import com.allen.dao.UserDao;
import com.allen.entity.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("/login")
public class LoginServlet extends HttpServlet {
UserDao userDao = new UserDao();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
}@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
try {
User user = userDao.login(username, password);
if (user!=null) {
request.getSession().setAttribute("UserInfo",user);
response.sendRedirect(request.getContextPath()+"/index");
return;
}
request.setAttribute("username",username);
request.setAttribute("password",password);
request.setAttribute("msg","账号或密码错误!!!请重新输入");
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
}catch(Exception e){
e.printStackTrace();
}
}
}
3.LogoutServlet
package com.allen.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("/logout")
public class LogoutServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getSession().invalidate();
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
}
}
⑤WEB-INF下面的jsp目录文件
1.login.jsp
登录 - 锐客网
>
h4{
text-align: center;
}
2.index.jsp
首页 - 锐客网
="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js">
>
$(document).ready(function () {
//首先将#back-to-top隐藏
$("#back-to-top").hide();
//当滚动条的位置处于距顶部600像素以下时,跳转链接出现,否则消失
$(function () {
$(window).scroll(function () {
if ($(window).scrollTop() > 300) {
$("#back-to-top").fadeIn(500);
} else {
$("#back-to-top").fadeOut(500);
}
});
//当点击跳转链接后,回到页面顶部位置
$("#back-to-top").click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
});
});
>
p#back-to-top {
position: fixed;
bottom: 30px;
right: 12px;
}p#back-to-top a {
text-align: center;
text-decoration: none;
color: #000;
display: block;
width: 60px;
/*使用CSS3中的transition属性给跳转链接中的文字添加渐变效果*/
-moz-transition: color1s;
-webkit-transition: color1s;
-o-transition: color1s;
}p#back-to-top a:hover {
color: #000011;
}p#back-to-top a span {
background-color: #d4bbbb;
z-index: -100;
border: 1px solid #cccccc;
border-radius: 6px;
display: block;
height: 30px;
width: 30px;
margin-bottom: 5px;
/*使用CSS3中的transition属性给标签背景颜色添加渐变效果*/
-moz-transition: background1s;
-webkit-transition: background1s;
-o-transition: background1s;
}#back-to-top a:hover span {
background-color: #f0f0f0;
}
文章图片
${z.originalFileName}${z.createTime}
class="fa fa-chevron-up" aria-hidden="true" style="width: 80px;
height: 30px;
">返回顶部
⑥WEB-INF下面的lib目录文件
jstl-1.2.jar
mysql-connector-java-5.1.48.jar
⑦web.xml
login
四、系统测试结果展示如下: 测试视频
简单的上传图片系统
【Jsp与Servlet|使用安全 jsp 与 servlet 完成用户登录(登录错误时账号密码回填)。登录成功后才能上传图片的图片管理系统。】视频地址:
推荐阅读
- #|华为机试第五题(HJ5 进制转换)
- Software|简单的增删改查及数据分页
- 编程语言|一年暴增1600万程序员!GitHub 2021年度报告发布(中国755万开发者排全球第二)
- Appium 服务器初始化参数
- Java|Redisson里的“看门狗”居然有这两个“bug”()
- Java|从架构视角去理解Spring,避免重复造轮子
- Java|你有没有发现,Spring Bean的生命周期就像人的一生()
- 经过一个多月的等待我有幸成为Spring相关项目的Contributor
- java-ee|Java中线程的状态和线程安全问题