文章目录[隐藏]
什么是 Model1?
使用JSP页面和JavaBean相结合的方式(Model1),由JSP页面来接收客户端请求,用JavaBean或其他服务完成业务逻辑、数据库操作和返回页面。我们这里的JavaBean主要是完成特定功能的Java类。
优点:架构简单,比较适合小型项目开发
缺点:JSP职责不单一,职责过重,不便于维护
代码如下
login.jsp
- <%@ page language=“java” contentType=“text/html; charset=UTF-8”
- pageEncoding=“UTF-8”%>
- <!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=UTF-8”>
- <title>Insert title here</title>
- </head>
- <body>
- <form action=“doLogin.jsp” method=“post”>
- <table width=“300” style=“margin:200px auto;” border=“1px solid #ccc”>
- <tr>
- <td><label for=“username”>用户名:</label></td>
- <td><input type=“text” name=“username” /></td>
- </tr>
- <tr>
- <td><label for=“password”>密码:</label></td>
- <td><input type=“password” name=“password” /></td>
- </tr>
- <tr>
- <td colspan=“2” align=“center”><input type=“submit” value=“登录” /></td>
- </tr>
- </table>
- </form>
- </body>
- </html>
doLogin.jsp
- <%@ page language=“java” contentType=“text/html; charset=UTF-8”
- pageEncoding=“UTF-8”%>
- <jsp:useBean id=“loginUser” class=“com.po.Users” scope=“page”/>
- <jsp:useBean id=“userDAO” class=“com.dao.UsersDAO” scope=“page”/>
- <jsp:setProperty property=“*” name=“loginUser”/>
- <%
- request.setCharacterEncoding(“utf-8”); //防止中文乱码
- //如果用户名和密码正确,则登录成功
- if(userDAO.usersLogin(loginUser)) {
- session.setAttribute(“loginUser”, loginUser.getUsername());
- request.getRequestDispatcher(“login_success.jsp”).forward(request, response);
- } else {
- response.sendRedirect(“login_failure.jsp”);
- }
- %>
Users.java
- package com.po;
- public class Users {
- private String username;
- private String password;
- public Users() {
- }
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- }
UsersDAO.java
- package com.dao;
- import com.po.Users;
- //用户逻辑类
- public class UsersDAO {
- public boolean usersLogin(Users u) {
- if(“admin”.equals(u.getUsername()) && “123456”.equals(u.getPassword())) {
- return true;
- } else {
- return false;
- }
- }
- }