public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=utf-8"); String username = req.getParameter("username"); String password = req.getParameter("password"); PrintWriter pw = resp.getWriter(); if (("admin").equals(username) &&("123").equals(password)){ User user = new User(); user.setUsername(username); user.setPassword(password); req.getSession().setAttribute("user",user); resp.sendRedirect("/Test05/IndexServlet"); }else { pw.write("用户名或密码错误,登录失败"); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
时间: 2024-04-05 17:32:55 浏览: 15
这是一个Java Servlet,用于处理用户登录请求。它覆盖了doGet()和doPost()方法,并使用HttpServletRequest和HttpServletResponse对象来处理HTTP请求和响应。在doGet()方法中,它获取用户名和密码参数,并将它们与硬编码的值进行比较。如果匹配成功,它将创建一个名为"user"的会话属性,并将其设置为User对象。然后它将重定向到另一个Servlet "/Test05/IndexServlet"。如果匹配失败,它会向响应输出流写入一条错误消息。在doPost()方法中,它只是调用doGet()方法。
相关问题
package com.qingruan.controller; import com.qingruan.bean.Users; import com.qingruan.dao.UserDao; 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("/loginServlet") public class UserLoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset=utf-8"); String username=req.getParameter("username"); String password=req.getParameter("password"); UserDao dao=new UserDao(); Users users=dao.usersLogin(username,password); if(users!=null){ req.setAttribute("users",users); req.getRequestDispatcher("/empQueryAll").forward(req,resp); }else{ System.out.println("登录失败"); resp.sendRedirect("login.jsp"); } } }
这是一个Java Servlet类,用于处理用户登录请求。它通过@WebServlet注解指示它可以处理来自“/loginServlet”URL路径的HTTP请求。该类继承了HttpServlet类,并重写了doGet和doPost方法,以便在处理HTTP GET和POST请求时调用相应代码。
在doPost方法中,首先设置请求和响应的编码格式为utf-8。然后获取用户通过请求提交的用户名和密码,并调用UserDao类的usersLogin方法进行验证。如果验证通过,将用户信息设置为请求属性,并将请求转发到“/empQueryAll”路径。如果验证失败,将响应重定向到“login.jsp”页面。
需要注意的是,这段代码中的“/empQueryAll”路径是另一个Servlet或JSP页面的路径,它用于显示所有员工的信息。如果需要使用此段代码,需要确保“/empQueryAll”路径指向正确的Servlet或JSP页面。
修改代码使其能够运行: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String user=req.getParameter("user"); String password=req.getParameter("password"); System.out.println("[Debug]" + user + " " + password); Employee employee=new EmployeeServiceMysqllmpl(). queryEmployeeByNameAndPassword(user,password); HttpSession session=req.getSession(); session.setAttribute("username",employee.getEname()); session.setAttribute("superuser",employee.getSuperuser()); System.out.println("[Debug] employee :"+employee.getEid()); if(employee.getEid()!=null){ resp.sendRedirect("/main.jsp"); }else { resp.sendRedirect("/error.jsp"); } }
这段代码是一个Servlet的doGet方法,用于处理HTTP GET请求。根据请求参数中的用户名和密码在数据库中查询员工信息,如果能够找到,则将员工姓名和是否为超级用户保存到Session中,并重定向到主页面;否则重定向到错误页面。
如果要使这段代码能够运行,需要添加以下几点修改:
1. 引入必要的类
在代码开头添加以下引用语句:
```java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
```
这些类用于处理Servlet请求和响应以及管理Session会话。
2. 定义Employee类
在代码中使用了Employee类,需要先定义该类。可以在代码中添加以下定义语句:
```java
class Employee {
private String eid;
private String ename;
private boolean superuser;
public String getEid() {
return eid;
}
public void setEid(String eid) {
this.eid = eid;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public boolean getSuperuser() {
return superuser;
}
public void setSuperuser(boolean superuser) {
this.superuser = superuser;
}
}
```
该类包含了员工的ID、姓名和是否为超级用户三个属性,以及相应的getter和setter方法。
3. 实现EmployeeServiceMysqllmpl类
在代码中使用了EmployeeServiceMysqllmpl类,需要先实现该类。可以添加以下实现语句:
```java
class EmployeeServiceMysqllmpl {
public Employee queryEmployeeByNameAndPassword(String name, String password) {
// TODO: 在数据库中查询员工信息,并返回Employee对象
return null;
}
}
```
该类包含了根据用户名和密码查询员工信息的方法,但是该方法还没有实现查询数据库的功能。
4. 修改方法实现
在queryEmployeeByNameAndPassword方法中添加查询数据库的实现,可以使用JDBC连接数据库进行查询,示例代码如下:
```java
class EmployeeServiceMysqllmpl {
public Employee queryEmployeeByNameAndPassword(String name, String password) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
// 加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
// 获取数据库连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
// 构造SQL语句
String sql = "select * from employee where name = ? and password = ?";
// 创建PreparedStatement对象
pstmt = conn.prepareStatement(sql);
// 设置参数
pstmt.setString(1, name);
pstmt.setString(2, password);
// 执行查询
rs = pstmt.executeQuery();
// 解析查询结果
if (rs.next()) {
Employee employee = new Employee();
employee.setEid(rs.getString("eid"));
employee.setEname(rs.getString("ename"));
employee.setSuperuser(rs.getBoolean("superuser"));
return employee;
} else {
return null;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
} catch (SQLException e) {
e.printStackTrace();
return null;
} finally {
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
该代码使用JDBC连接数据库,并查询数据库中的employee表,根据用户名和密码返回Employee对象。
5. 修改重定向路径
在代码中使用了resp.sendRedirect方法进行重定向,需要修改重定向路径,使其指向正确的JSP页面。可以将重定向路径修改为:
```java
if (employee != null) {
resp.sendRedirect(req.getContextPath() + "/main.jsp");
} else {
resp.sendRedirect(req.getContextPath() + "/error.jsp");
}
```
这样就可以将重定向路径改为使用相对路径,使其可以正确跳转到指定的JSP页面。
最终修改后的代码如下:
```java
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
class Employee {
private String eid;
private String ename;
private boolean superuser;
public String getEid() {
return eid;
}
public void setEid(String eid) {
this.eid = eid;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public boolean getSuperuser() {
return superuser;
}
public void setSuperuser(boolean superuser) {
this.superuser = superuser;
}
}
class EmployeeServiceMysqllmpl {
public Employee queryEmployeeByNameAndPassword(String name, String password) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
// 加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
// 获取数据库连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
// 构造SQL语句
String sql = "select * from employee where name = ? and password = ?";
// 创建PreparedStatement对象
pstmt = conn.prepareStatement(sql);
// 设置参数
pstmt.setString(1, name);
pstmt.setString(2, password);
// 执行查询
rs = pstmt.executeQuery();
// 解析查询结果
if (rs.next()) {
Employee employee = new Employee();
employee.setEid(rs.getString("eid"));
employee.setEname(rs.getString("ename"));
employee.setSuperuser(rs.getBoolean("superuser"));
return employee;
} else {
return null;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
} catch (SQLException e) {
e.printStackTrace();
return null;
} finally {
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String user = req.getParameter("user");
String password = req.getParameter("password");
System.out.println("[Debug]" + user + " " + password);
Employee employee = new EmployeeServiceMysqllmpl()
.queryEmployeeByNameAndPassword(user, password);
HttpSession session = req.getSession();
session.setAttribute("username", employee.getEname());
session.setAttribute("superuser", employee.getSuperuser());
System.out.println("[Debug] employee :" + employee.getEid());
if (employee != null) {
resp.sendRedirect(req.getContextPath() + "/main.jsp");
} else {
resp.sendRedirect(req.getContextPath() + "/error.jsp");
}
}
}
```
阅读全文