结合前端,在本地运行实现登陆操作。
将在输入框的数据传给服务器,服务器再通过调用数据库的数据进行对比,实现简单的判断逻辑
到这里的我就感觉内容多了起来,在之前连接数据库,数据库操作的时候,跟着教程走,只是知道简单的用法也能在之后自行配置
这里的话数据库等操作变成了一个环节,还有其他很多新的操作,一下子不好上手的servlet等去花时间去学
简单实现servlet
package org.example.servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.example.entity.User;
import org.example.mapper.UserMapper;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
SqlSessionFactory factory;
@SneakyThrows
@Override
public void init() throws ServletException {
factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-config.xml"));
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//首先设置一下响应类型
resp.setContentType("text/html;charset=UTF-8");
//获取POST请求携带的表单数据
Map<String, String[]> map = req.getParameterMap();
//判断表单是否完整
if(map.containsKey("username") && map.containsKey("password")) {
String username = req.getParameter("username");
String password = req.getParameter("password");
try(SqlSession session = factory.openSession(true)) {
UserMapper userMapper= session.getMapper(UserMapper.class);
User user = userMapper.getUser(username,password);
if(user != null) {
resp.getWriter().write("用户"+username+"登录成功");
}
else
{
resp.getWriter().write("您登录的用户密码错误或者账户不存在");
}
}
//权限校验(待完善)
}else {
resp.getWriter().write("错误,您的表单数据不完整!");
}
}
}
```java
标签:java,9.19,resp,学习,session,org,import,servlet
From: https://www.cnblogs.com/zangbotao/p/18421281