零基础学习java------34---------登录案例,域,jsp(不太懂),查询商品列表案例(jstl标签)

一. 简单登录案例

流程图:

 

 

 

 项目结构图

 

前端代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>哈哈登录页面</h1>
<form action="login" method="post">
用户名<input type="text" name="username" /></br></br>
密码<input type="password" name="pwd" /></br></br>
<input type="submit" value="登录"/>
</form>
</body
View Code

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>day13</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>login</display-name>
    <servlet-name>login</servlet-name>
    <servlet-class>com._51doit.admin.login</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>login</servlet-name>
    <url-pattern>/login</url-pattern>
  </servlet-mapping>
</web-app>
View Code

 

 

 login部分代码

public class login extends HttpServlet {
    private static final long serialVersionUID = 1L;
    UserService userService = new UserServiceImpl();
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        try {
            // 获取前端数据
            String username = request.getParameter("username");
            String pwd = request.getParameter("pwd");
            System.out.println("password:"+pwd);
            // 登录处理
            User user = userService.login(username, pwd);
            if(user != null) {
                response.sendRedirect("/day13/success.html");
            }else {
                System.out.println("失败");
                response.sendRedirect("/day13/login.html");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
View Code

service层

UserService接口

public interface UserService {
    
    // 登录
    public User login(String username,String pwd) throws Exception;
    
}
View Code

UserService实现类(UserServiceImpl)

public class UserServiceImpl implements UserService{
    UserDao userDao = new UserDaoImpl();
    @Override
    public User login(String username, String pwd) throws Exception {
        User user = userDao.getUserFromdB(username, pwd);
        return user;
    }
}
View Code

dao层

UserDao接口

public interface UserDao {
    // 从数据库获取信息
    public User getUserFromdB(String username,String pwd) throws Exception;
}
View Code

UserDaoImpl(UserDao接口实现类)

public class UserDaoImpl  implements UserDao{
    static QueryRunner runner;
    static {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        runner = new QueryRunner(dataSource);
    }
    // 根据用户和密码名查询用户
    @Override
    public User getUserFromdB(String username, String pwd) throws Exception {
        String sql = "select * from user where username = ? and password = ?";
        User user = runner.query(sql, new BeanHandler<>(User.class),username,pwd);
        return user;
    }
}
View Code

pojo层

注意:此处一定要有无参构造方法

public class User {
    private int uid;
    private String username;
    private String nickname;
    private String password;
    private String phonenumber;
    private String email;
    public int getUid() {
        return uid;
    }
    public void setUid(int uid) {
        this.uid = uid;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getNickname() {
        return nickname;
    }
    public void setNickname(String nickname) {
        this.nickname = nickname;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getPhonenumber() {
        return phonenumber;
    }
    public void setPhonenumber(String phonenumber) {
        this.phonenumber = phonenumber;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    
    public User() {
        super();
    }
    public User(int uid, String username, String nickname, String password, String phonenumber, String email) {
        super();
        this.uid = uid;
        this.username = username;
        this.nickname = nickname;
        this.password = password;
        this.phonenumber = phonenumber;
        this.email = email;
    }
    @Override
    public String toString() {
        return "User [uid=" + uid + ", username=" + username + ", nickname=" + nickname + ", password=" + password
                + ", phonenumber=" + phonenumber + ", email=" + email + "]";
    }
}
View Code

 

改进:后端传user对象至前端并在前端页面显示出来

 思路:直观想法是直接将user传至前端,并显示出来,但html页面中并不能获取到user,解决方法:将user对象存入域中,使用jsp文件代替html文件并在jsp文件中使用EL表达式获取user对象的username属性。代码如下,此处只鞋跟上面的差别代码

前端部分(此处是jsp文件不是html文件):

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
<h1>登录成功     欢迎${user.username} </h1>
</body>
</html>
View Code

login部分

 

 

二. 域

1. 概念:

  存储数据,并且有一定访问范围的对象[任意数据   object]

2.web四大域

(1)page(配置域),一个servlet或是一个页面(访问范围)

(2)request(请求域),一次请求(访问范围),由于存在转发,所以可以多个servlet进行数据共享

(3)session(session域):一个用户(访问范围)

(4)application:整个web项目(访问范围)

3. 域存储数据(此处以session域为例)

session.setAttribute(“key”, object);

4.EL(Expression Language)表达式:${}

  其可以获取java对象,调用java方法,执行算术运算

5.jsp页面从域中取数据

         ${key}

三. jsp(java server page):在页面上写java代码

      为了防止java代码和html胶合,jsp文档只用EL展示数据,不写java代码,代码(获取请求参数,操作数据库,跳转页面)写在servlet中

 

四. 查询商品列表案例

 大致思路和上诉登录案例相似

此案例涉及新的知识点:jsq页面上遍历数据(使用jstl标签)(不在jsp文档中使用java代码,但又要遍历数据,所以使用jstl标签)

 代码结构图

 

 

 前端代码:涉及jstl标签的使用(不在jsp文档中使用java代码,但又要遍历数据,所以使用jstl标签)

p_list.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
    <button>
        <a href="/day13/GetAllProducts">查詢商品列表</a>
    </button>
    <br />
    <br />
    <br /> 
    <table border="1px" cellspacing="0" width="100%">
        <tr>
            <th>id</th>
            <th>name</th>
            <th>category</th>
            <th>pnum</th>
            <th>description</th>
            <th>描述</th>
        </tr>
        <!-- 迭代获取数据,即遍历 -->
        <c:forEach items="${p_list }" var="product">
            <tr>
                <td>${product.id}</td>
                <td>${product.name}</td>
                <td>${product.price}</td>
                <td>${product.category}</td>
                <td>${product.pnum}</td>
                <td>${product.description}</td>
        </c:forEach>
    </table>
</body>
</html>
View Code

重要代码(使用jstl标签遍历列表部分)

 

 后端部分

 GetAllProducts

public class GetAllProducts extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ProductsService productsService = new ProductsServiceImpl();
        try {
            List<Products> list = productsService.getAllProducts();
            System.out.println(list);
            HttpSession session = request.getSession();
            session.setAttribute("p_list", list);
            response.sendRedirect("/day13/p_list.jsp");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
View Code

 dao层

 ProductsDao接口

public interface ProductsDao {
    // 从数据库中获取product
    public List<Products> getProductsFromDB() throws Exception;
}
View Code

实现类ProductsDaoImpl

public class ProductsDaoImpl implements ProductsDao {
    // 数据库连接池的创建
    static QueryRunner runner;
    static {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        runner = new QueryRunner(dataSource);
    }
    // 从数据库中获取products
    @Override
    public List<Products> getProductsFromDB() throws Exception {
        String sql = "select * from products";
        List<Products> list = runner.query(sql, new BeanListHandler<>(Products.class));
        return list;
    }
}
View Code

service层

 ProductsServices接口

public interface ProductsService {
    public List<Products> getAllProducts() throws Exception;
}
View Code

实现类ProductsServicesImpl

public class ProductsServiceImpl implements ProductsService{
    // 调用Dao层,获取数据
    @Override
    public List<Products> getAllProducts() throws Exception {
        ProductsDao productsDao = new ProductsDaoImpl();
        List<Products> list = productsDao.getProductsFromDB();
        return list;
    }
}
View Code

pojo层

 Products

package com._51doit.pojo;

public class Products {
    int id ;
    String name ;
    double price ;
    String category ;
    int pnum ;
    String description ;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public String getCategory() {
        return category;
    }
    public void setCategory(String category) {
        this.category = category;
    }
    public int getPnum() {
        return pnum;
    }
    public void setPnum(int pnum) {
        this.pnum = pnum;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    
    public Products() {
        super();
    }
    public Products(int id, String name, double price, String category, int pnum, String description) {
        super();
        this.id = id;
        this.name = name;
        this.price = price;
        this.category = category;
        this.pnum = pnum;
        this.description = description;
    }
    @Override
    public String toString() {
        return "Products [id=" + id + ", name=" + name + ", price=" + price + ", category=" + category + ", pnum="
                + pnum + ", description=" + description + "]";
    }
}
View Code

运行结果:(点击查询商品列表按钮后)

 

 以上GetAllProducts代码有不足之处,即数据存储在session域中,一个用户的多个页面都可以获取这些数据,若是只想让某个页面获取这个数据就做不到了。解决办法---->将数据存储在request域中去,此时数据只能被某次请求获取,代码如下

 此处的url不需要加项目名,因为转发是服务器内部请求

 

 

 

 

 

 

 

 

 

posted @ 2019-10-06 12:02  一y样  阅读(229)  评论(0编辑  收藏  举报