Java Web实现用户登录功能
java web 学习记录一下
-
mvc结构实现mysql 连接
-
什么是mvc
- MVC是模型(model)、视图(view)、控制(controller)这三个单词上的首字母组成。它是一种应用模型,它的目的是实现Web系统的职能分工。避免all in one 所有代码全部写在一个文件里的一种分工模型。
-
实现简单登录功能
- 登录成功,进入sccess.jsp界面,失败返回首页,并输出密码错误
数据库准备
- 创建数据库
create database student;
- 创建表
create table tbl_user(
userId varchar(11) not null
primary key,
passWord varchar(255) not null
);
- 导入数据
insert into tbl_user (userId,passWord) values ('admin','1234');
insert into tbl_user (userId,passWord) values ('张三','1234');
项目创建与编写
idea上准备工作
- 创建一个干净的meavn项目
- 把该项目添加web项目
导入依赖
- junit 是为了便于测试
- 其他是一些基础包
- mysql 连接数据库
- servlet-api servlet服务
- jsp-api
- jstl 写el表达式
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2.1-b02</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
</dependencies>
连接数据库
- 使用idea连接本地数据库
编写实体类User
public class User {
private String userId;
private String passWord;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
}
UserDao层接口
public interface UserDao {
public boolean getUser(String userID,String userPassWord);
}
UserDaoImpl实现类
public class UserDaoImpl implements UserDao{
private String driver = "com.mysql.cj.jdbc.Driver";
private String url = "jdbc:mysql://localhost:3306/student";
private String root = "root";
private String password = "123456";
@Override
public boolean getUser(String userID,String userPassWord) {
boolean flag = false;
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
String sql = "select * from tbl_user where userId = ? and passWord = ?";
try {
Class.forName(driver);
conn = DriverManager.getConnection(url,root,password);
pstm = conn.prepareStatement(sql);
pstm.setString(1,userID);
pstm.setString(2,userPassWord);
rs = pstm.executeQuery();
if(rs.next()){
flag = true;
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
rs.close();
pstm.close();
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
return flag;
}
}
UserService层接口
public interface UserService {
public boolean Login(String userId,String userPassWord);
}
UserServiceImpl实现类
public class UserServiceImpl implements UserService{
@Override
public boolean Login(String userId, String userPassWord) {
boolean flag = false;
UserDao userDao = new UserDaoImpl();
flag = userDao.getUser(userId,userPassWord);
return flag;
}
}
编写LoginServlet服务层
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
boolean flag = false;
String userId = req.getParameter("userName");
String userPassWord = req.getParameter("userPassWord");
UserService userService = new UserServiceImpl();
flag = userService.Login(userId,userPassWord);
if(flag){
User user = new User();
user.setUserId(userId);
user.setPassWord(userPassWord);
req.getSession().setAttribute("user",user);
resp.sendRedirect("jsp/success.jsp");
}else{
req.setAttribute("msg","用户错误");
req.getRequestDispatcher("login.jsp").forward(req,resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
配置web.xml文件
- servlet3.0之后可以使用注解,不用配置这个文件,但是是初学者,还是先学会配置web.xml文件
<servlet>
<servlet-name>loginServlet</servlet-name>
<servlet-class>com.hjk.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
编写login.jsp 界面
- 简单的写了一下,一个表单的提交功能
<form action="login" method="post">
<table>
<tr><span style="color: aquamarine">${requestScope.msg}</span></tr>
<tr>
<td>用户名:</td><td><input type="text" name="userName"/></td>
</tr>
<tr>
<td>密码</td><td><input type="password" name="userPassWord"/></td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="submit"/>
<input type="reset" value="reset">
</td>
</tr>
</table>
</form>
- 写一个登录成功界面sccess.jsp
-这个文件在web问价夹下面,本来想写一个拦截器,没有登录不能直接访问后面的界面,现在还没有写
<h1><span style="text-align: center"><span style="color: deeppink" >欢迎您,${sessionScope.user.userId}登录成功</span></span></h1>
- 如果登录失败就返回登录界面
idea默认会先访问index.jsp界面,这里在web.xml配置一下,让他直接访问login.jsp
<welcome-file-list>
<welcome-file>/login.jsp</welcome-file>
</welcome-file-list>
乱码处理
已经可以登录了,但是还是存在中文乱码,编写一个过滤器CharacterEncoding,让它处理中文乱码
- 这个包必须导入
import javax.servlet.*;
public class CharacterEncoding implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("utf-8");
servletRequest.setCharacterEncoding("utf-8");
//不执行filterChain就会一直卡在这里,相当于一直拦截
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
}
}
- 为过滤文件配置web.xml
<filter>
<filter-name>characterEncoding</filter-name>
<filter-class>com.hjk.filter.CharacterEncoding</filter-class>
</filter>
<filter-mapping>
<filter-name>characterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
结果展示
-
初始界面
-
登录失败界面
-
登录成功;不加过滤器张山是不能登录成功的
-
admin
-
张三
文件的整体结构
一些注意点
- 导包的时候一定要到对
- idea有可能在测试的时候没有lib包这个时候需要自己添加lib问价夹,并且把相应的依赖都添加进去
- 服务器报404 一般是路径错误(比较好解决)
- 500 可能是一些代码错误,或者jar没到入