gpt4 book ai didi

java - 关于使用 jsp 创建管理页面的建议

转载 作者:行者123 更新时间:2023-11-29 05:19:33 25 4
gpt4 key购买 nike

我对使用 Java 开发 Web 应用程序还很陌生。我开发了一个小应用程序,它是一个登录和注册页面,两者都运行良好。现在,我决定制作一个管理页面(使用 jsp)。在我的 java 代码中,我控制 jsp 页面的重定向(如果 user!="admin"then home.jsp else user=="admin"then admin.jsp)。在我的管理页面中,我想要做的是我希望管理员能够查看所有注册的用户并可以编辑他们的详细信息或删除他们。有人可以建议我如何实现这一目标。

登录 Servlet.java(我在管理员和普通用户之间做出决定的代码)

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String email = request.getParameter("email");
String password = request.getParameter("password");
String errorMsg = null;
String name;
if(email == null || email.equals("")){
errorMsg ="User Email can't be null or empty";
}
if(password == null || password.equals("")){
errorMsg = "Password can't be null or empty";
}

if(errorMsg != null){
RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
PrintWriter out= response.getWriter();
out.println("<font color=red>"+errorMsg+"</font>");
rd.include(request, response);
}else{

Connection con = (Connection) getServletContext().getAttribute("DBConnection");
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = con.prepareStatement("select id, name, email,country from Users where email=? and password=?");
ps.setString(1, email);
ps.setString(2, password);
rs = ps.executeQuery();

if(rs != null && rs.next()){

User user = new User(rs.getString("name"), rs.getString("email"), rs.getString("country"), rs.getInt("id"));
name=rs.getString("name");
System.out.println("Name:"+ name);
//if(rs.getString("name")!="admin")
if(!name.equalsIgnoreCase("admin"))
{
logger.info("User found with details="+user);
HttpSession session = request.getSession();
session.setAttribute("User", user);
response.sendRedirect("home.jsp");
}
// String rs1=rs.getString();
else if(name.equalsIgnoreCase("admin"))
{
logger.info("Admin found with details="+user);
HttpSession session = request.getSession();
session.setAttribute("User", user);
response.sendRedirect("admin.jsp");
}

}else{
RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
PrintWriter out= response.getWriter();
logger.error("User not found with email="+email);
out.println("<font color=red>No user found with given email id, please register first.</font>");
rd.include(request, response);
}
} catch (SQLException e) {
e.printStackTrace();
logger.error("Database connection problem");
throw new ServletException("DB Connection problem.");
}finally{
try {
rs.close();
ps.close();
} catch (SQLException e) {
logger.error("SQLException in closing PreparedStatement or ResultSet");;
}

}
}

首页.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page import="com.javadbproject.util.User"%>
<%@ page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Home Page</title>

<link rel="stylesheet" type="text/css" href="<c:url value='/loginstyle.css'/>">

</head>
<body>
<%User user = (User) session.getAttribute("User"); %>
<h3>Hi <%=user.getName() %></h3>
<strong>Your Email</strong>: <%=user.getEmail() %><br>
<strong>Your Country</strong>: <%=user.getCountry() %><br>
<br>
<form action="Logout" method="post">
<input type="submit" value="Logout" >

</form>
</body>
</html>

AuthenticationServlet

package com.javadbproject.servlet.filters;


import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

@WebFilter("/AuthenticationFilter")
public class AuthenticationFilter implements Filter {

private Logger logger = Logger.getLogger(AuthenticationFilter.class);

public void init(FilterConfig fConfig) throws ServletException {
logger.info("AuthenticationFilter initialized");
}

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;

String uri = req.getRequestURI();
logger.info("Requested Resource::"+uri);

HttpSession session = req.getSession(false);

if(session == null && !(uri.endsWith("html") || uri.endsWith("Login") || uri.endsWith("Register"))){
logger.error("Unauthorized access request");
res.sendRedirect("login.html");
}else{
// pass the request along the filter chain
chain.doFilter(request, response);
}


}

public void destroy() {
//close any resources here
}

}

我希望按照与 home.jsp 类似的方式开发我的 admin.jsp

谢谢!!

最佳答案

  1. 你需要一个数据库mysql开始会很好。

  2. 你需要有一个 mysql connector jar file .

  3. 例如,创建一个类用户

    public class User{
    String iduser;
    String name;
    String username;
    String password;

    //setters and getters
    }
  4. 在 mysql 或您拥有的任何数据库中为用户创建一个表。

    创建表 sampleapplication.user ( iduser INT NOT NULL AUTO_INCREMENT , 名称 VARCHAR(45) NULL , 用户名 VARCHAR(45) NULL , usercol VARCHAR(45) NULL , 主键 (iduser) );

  5. 让我们用 java 启动数据库。 :) 在您的构建路径中添加 mysql 连接器 jar 文件 (右键单击项目 > 构建路径 > 配置构建路径 > 单击添加外部 jar > 找到 mysql 连接器),并将其粘贴到您的 web -inf>lib 文件夹。

  6. 为数据库事务创建一个。对于reference

    public class DatabaseTransaction{

    public List<User> readDataBase() throws Exception {
    try {
    // this will load the MySQL driver, each DB has its own driver
    Class.forName("com.mysql.jdbc.Driver");
    // setup the connection with the DB.
    connect = DriverManager
    .getConnection("jdbc:mysql://localhost/database?"
    + "user=sqluser&password=sqluserpw");

    // statements allow to issue SQL queries to the database
    statement = connect.createStatement();
    // resultSet gets the result of the SQL query
    resultSet = statement
    .executeQuery("select * from user");

    List<User> listOfUsers=new ArrayList<User>();
    User userToAdd;

    while (resultSet.next()) {
    userToAdd = new User();
    userToAdd.setUsername(resultSet.getString("username"));
    userToAdd.setPassword(resultSet.getString("pword"));
    userToAdd.setUserid(resultSet.getString("userid"));
    userToAdd.setName(resultSet.getString("name"));
    listOfUsers.add(userToAdd);
    }
    }
    }
  7. DatabaseTransaction 调用到您的 filter/controller/servlet

    DatabaseTransaction databaseTransaction = DatabaseTransaction();

    //use your `HttpServletRequest`
    //parameters are key and value
    //store as attribute to access in jsp page
    request.setAttribute("userList",databaseTransaction.readDataBase());

    //then forward the page using `HttpServletRequest`
    //dont use response.redirect(); you wont be able to use the attribute because you are using a response
    //filename of the jsp
    request.getRequestDispatcher("adminpage").forward(request, response);
  8. 在您的 jsp 页面中。使用 JSTL

     //import the core tag library
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

    //lastly loop through the list attribute
    <table>
    <thead>
    <tr>
    <td>id</td>
    <td>Name</td>
    <td>Username</td>
    </tr>
    </thead>

    <tbody>
    <c:foreach items="${userList}" var="user">
    <tr>
    <td><c:out value="${user.iduser}"/></td>
    <td><c:out value="${user.name}"/></td>
    <td><c:out value="${user.username}"/></td>
    </tr>
    </c:foreach>
    </tbody>
    </table>

就是这样:)

关于java - 关于使用 jsp 创建管理页面的建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25318809/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com