运行Javaweb登录界面时,数据库中有用户信息,但是登录时会跳转到没有用户信息的界面,
登录界面Java代码如下
package com.guming.web;
import com.guming.mapper.UserMapper;
import com.guming.pojo.User;
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 javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.接受用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
//2.调用Mybatis完成查询
//2.1获取SqlSessionFactory
String resource = "/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.2获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// SqlSession sqlSession = sqlSessionFactory.openSession();
//2.3获取Mapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//2.4调用方法
User user = userMapper.select(username, password);
// User user = userMapper.select(username, password);
//2.5释放资源
sqlSession.close();
// sqlSession.close();
//获取字符输出流,并设置content-type
response.setContentType("text/html;charset=utf-8");
PrintWriter writer = response.getWriter();
//3.判断user是否为null;
if (user !=null){
writer.write("登录成功");
}else {
writer.write("用户名不存在,请注册后再登录!");
}
/* if (user !=null){
//用户登录成功
writer.write("登录成功");
}else {
//登录失败
writer.write("用户名不存在,请注册后再登录!");
}*/
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
登录界面HTML代码如下:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
<link href="css/login.css" rel="stylesheet">
</head>
<body>
<div id="loginDiv">
<form action="/Tomcat_Demo/loginServlet" method="post" id="form"><!--action后面接虚拟目录,即项目名字-->
<h1 id="loginMsg">登录</h1>
<p>用户名:<input id="username" name="username" type="text"></p>
<p>密 码:<input id="password" name="password" type="password"></p>
<div id="subDiv">
<input type="submit" class="button" value="登录">
<input type="reset" class="button" value="重置">
<a href="register.html">没有账号?点击注册</a>
</div>
</form>
</div>
</body>
</html>
mapper代码如下:
@Select("select * from tb_user where username = #{username} and password = #{password}")
User select(@Param("username") String username, @Param("password") String password);
```