注意:mysql连接驱动包 jstl.jar包不要 忘了
任名名称:基于 JSP 实现,JSTL 和 EL 表达式操作
任务目标:业务目标:使用 JSP,JSTL 和 EL 实现页面数据的动态显示技能目标: 熟悉 JSP 页面,使用 JSTL 和 EL 表达式
任务概述:随着互联网的发展,很多小企业的官网已经不局限于几个静态页面,小璞
的公司最近就接到了一个项目,要做一家公司的官网,官网会不定时更新公司
产品信息,并且潜在用户还可以注册账号成为公司的 VIP 用户,如何实现这些
产品信息的动态更新和展示?Html 已经远远不能满足这个要求,你能用所学知
识处理这个问题吗?
1.注册页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<style>
* {
margin: 0;
padding: 0;
}
div {
margin-left: 40px;
margin-top: 20px;
}
li{
margin-top: 20px;
}
ul{
list-style: none;
}
</style>
</head>
<body>
<div>
<form action="${pageContext.request.contextPath}/register" method="post">
<h1>注册</h1>
<ul>
<li>请输入注册的用户名:<input name="username" type="text"></li>
<li>请输入注册的密码 :<input name="password" type="text"></li>
<li><input type="submit" value="提交">
<%-- <input type="reset" value="重置">--%>
</li>
<li><button οnclick=window.open("login.jsp")>返回登陆界面</button> </li>
</ul>
</form>
</div>
</body>
</html>
2.登陆页面
<%@ page import="java.util.Date" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
<style>
* {
margin: 0;
padding: 0;
}
div {
margin-top: 50px;
margin-left: 50px;
}
li{
list-style: none;
padding-top: 20px;
}
</style>
</head>
<body>
<%
request.setAttribute("now", new Date());
%>
<div>
<h3>现在的时间为<fmt:formatDate value="${now}" pattern="yyyy-MM-dd HH:mm"></fmt:formatDate> </h3>
<br><br>
<h2>请登录您的账号</h2>
<form action="${pageContext.request.contextPath}/login" method="post" name="myform" >
<ul>
<li>用户名:<input type="text" name="username" ><br></li>
<li>密 码:<input type="text" name="password"><br></li>
<li><input type="submit" value="登陆" >
<button onclick=window.open("${pageContext.request.contextPath}/register.jsp")>注册</button>
</ul>
</form>
</div>
</body>
</html>
包括头heider.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title></title>
</head>
<body>
<h1 align="center">欢迎来到本网站</h1>
</body>
</html>
尾botom.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title></title>
<style>
#a{
text-align: center;
}
</style>
</head>
<body>
<div id="a">
<a href="https://www.baidu.com" >友情链接</a>
</div>
</body>
</html>
3.产品添加页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>$Title$</title>
<style>
.aa{
width:1000px;
height:60px;
align-content: center;
}
.bb{
width:25%;
height:50px;
}
#b{
height: 250px;
}
</style>
</head>
<body>
<%@ include file="header.jsp"%>
<div>
<table border="1px" width="100%">
<tr class="aa">
<%-- <td class="bb" align="center">产品id</td>--%>
<td class="bb" align="center">产品名称</td>
<td class="bb" align="center">产品价格</td>
<td class="bb" align="center">产品描述</td>
<td class="bb" align="center">操作</td>
</tr>
<form action="${pageContext.request.contextPath}/productAdd" method="post">
<tr class="aa" height="200px">
<%-- <td class="bb" align="center"> <input class="cc" type="text" name="id" value=""/></td>--%>
<td class="bb" align="center"> <input class="cc" type="text" name="productName" value=""/></td>
<td class="bb" align="center"> <input class="cc" type="text" name="price" value=""/></td>
<td class="bb" align="center"> <input class="cc" type="text" name="description" value=""/></td>
<td class="bb" align="center"> <input class="cc" type="submit" value="提交"/></td>
</tr>
<%-- <input type="submit" value="提交"/>--%>
</form>
</table>
</div>
<div id="b">
</div>
</body>
<%@ include file="bottom.jsp"%>
</html>
4.产品显示页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>$Title$</title>
<style>
.aa{
width:1000px;
height:60px;
}
.bb{
width:25%;
height:50px;
}
#b{
height: 250px;
}
</style>
</head>
<body>
<%@ include file="header.jsp"%>
<div>
<table border="1px" width="100%">
<tr class="aa">
<td class="bb">产品id</td>
<td class="bb">产品名称</td>
<td class="bb">产品价格</td>
<td class="bb">产品描述</td>
</tr>
<c:forEach items="${productList}" var="p" varStatus="vs">
<tr class="aa" height="200px">
<td class="bb"> <input class="cc" type="text" name="id" value="${p.id}"/></td>
<td class="bb"> <input class="cc" type="text" name="productName" value="${p.productName}"/></td>
<td class="bb"> <input class="cc" type="text" name="price" value="${p.price}"/></td>
<td class="bb"> <input class="cc" type="text" name="description" value="${p.description}"/></td>
</tr>
</c:forEach>
</table>
</div>
<button onclick=window.open("${pageContext.request.contextPath}/productAdd.jsp")>添加</button>
<%-- <a href="${pageContext.request.contextPath}/productAdd.jsp">添加</a>--%>
<div id="b">
</div>
</body>
<%@ include file="bottom.jsp"%>
</html>
5.使用的工具类
package com.lx.utils;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;
public class JdbcUtils {
private static String url ;
private static String user ;
private static String password ;
private static String driver;
static {
Properties pro = new Properties();
//这里是通过类加载器获取jdbc.propertise的绝对路径
//首先获取类的加载器,然后通过类的加载器获取src路径下资源的绝对路径
//这里的意思是不管模块如何移植,只要在模块当中,就能通过相对路径找到
//绝对路径
ClassLoader loader = JdbcUtils.class.getClassLoader();
//通过类加载器获取scr路径下的资源的绝对路径
URL res = loader.getResource("JDBC.properties");
//获取绝对路径
String path = res.getPath();
try {
pro.load(new FileReader(path));
} catch (IOException e) {
e.printStackTrace();
}
url = pro.getProperty("url");
user = pro.getProperty("user");
password = pro.getProperty("password");
driver = pro.getProperty("driver");
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,user,password);
}
public static void close(Statement stmt, Connection conn){
if (stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(ResultSet rs,Statement stmt, Connection conn){
if (rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
6.user类
package com.lx.vo;
public class User {
private String username;
private String password;
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;
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
public User() {
}
}
7.product类
package com.lx.vo;
public class Product {
private Integer id;
private String productName;
private double price;
private String description;
public Product() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Product(Integer id, String productName, double price, String description) {
this.id = id;
this.productName = productName;
this.price = price;
this.description = description;
}
}
8. 注册的servlet
package com.lx.servlet;
import com.lx.dao.UserDao;
import com.lx.daoImpl.UserDaoImpl;
import com.lx.vo.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
private UserDao dao = new UserDaoImpl();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
//获得用户名和密码
String username = request.getParameter("username");
String pwd = request.getParameter("password");
//调用方法将用户名和密码存到数据库
User u = new User();
u.setUsername(username);
u.setPassword(pwd);
int i=0;
try {
i = dao.addUser(u);
} catch (SQLException e) {
e.printStackTrace();
}
if(i>0){
//添加成功
response.sendRedirect(request.getContextPath()+"/login.jsp");
}else{
response.sendRedirect(request.getContextPath()+"/register.jsp");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
doGet(request, response);
}
}
9.登录的servlet
package com.lx.servlet;
import com.lx.dao.UserDao;
import com.lx.daoImpl.UserDaoImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private UserDao dao = new UserDaoImpl();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
//获得用户输入的用户名和密码
String username = request.getParameter("username");
String pwd = request.getParameter("password");
//从数据库查询用户名和密码
String password=null;
//根据用户名查询密码
//password = jdbcConnection.getResult(String name).get(username);
try {
password=dao.findPassword(username);
} catch (SQLException e) {
e.printStackTrace();
}
//User u = new User();
//u.setUsername(username);
//u.setPassword();
//request.setAttribute();
if(pwd.equals(password)){
//登录成功
response.sendRedirect(request.getContextPath()+"/productList");
}else{
//失败
response.sendRedirect("/login.jsp");
//request.getRequestDispatcher("/login.jsp").forward(request, response);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
doGet(request, response);
}
}
10.产品显示页面
package com.lx.servlet;
import com.lx.dao.UserDao;
import com.lx.daoImpl.UserDaoImpl;
import com.lx.vo.Product;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
@WebServlet("/productList")
public class ProductListServlet extends HttpServlet {
private UserDao dao = new UserDaoImpl();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
List<Product> productList = null;
try {
productList= dao.findAllProduct();
} catch (SQLException e) {
e.printStackTrace();
}
request.setAttribute("productList",productList);
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
doGet(request, response);
}
}
11.产品 添加页面
package com.lx.servlet;
import com.lx.dao.UserDao;
import com.lx.daoImpl.UserDaoImpl;
import com.lx.vo.Product;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
@WebServlet("/productAdd")
public class ProductAddServlet extends HttpServlet {
private UserDao dao = new UserDaoImpl();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
//获取用户输入的数据
String productName = request.getParameter("productName");
String price = request.getParameter("price");
double price1 = Double.parseDouble(price);
String description = request.getParameter("description");
//创建producrt对象
Product p = new Product();
p.setProductName(productName);
p.setPrice(price1);
p.setDescription(description);
//定义一个flag
int flag = 0;
try {
//调用到Impl中方法将用户输入的数据存入数据库
flag = dao.addProduct(p);
} catch (SQLException e) {
e.printStackTrace();
}
if(flag>0){
//添加product成功
//重定向到productList.jsp,需要先经过ProductListServlet处理数据并展示
response.sendRedirect(request.getContextPath()+"/productList");
}else{
//失败则转发到添加页面
request.getRequestDispatcher("/productAdd.jsp").forward(request, response);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
doGet(request, response);
}
}
12.userDao接口
package com.lx.dao;
import com.lx.vo.Product;
import com.lx.vo.User;
import java.sql.SQLException;
import java.util.List;
public interface UserDao {
//根据用户名查密码
String findPassword(String username) throws SQLException;
//注册,增加用户
int addUser(User u) throws SQLException;
//增加产品
int addProduct(Product p) throws SQLException;
List<Product> findAllProduct() throws SQLException;
}
13.UserDao 实现类
package com.lx.daoImpl;
import com.lx.dao.UserDao;
import com.lx.utils.JdbcUtils;
import com.lx.vo.Product;
import com.lx.vo.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* @ClassName UserDaoImpl
* @Description TODO
* @Author lixin
* @Date 2021-01-18 20:17
* @Version 1.0
*/
public class UserDaoImpl implements UserDao {
private JdbcUtils jdbcUtils;
Connection conn = null;
public UserDaoImpl() {
jdbcUtils = new JdbcUtils();
}
/**
* 根据用户名查找
* @param
* @return
* @throws SQLException
*/
@Override
public String findPassword(String username) throws SQLException {
conn=jdbcUtils.getConnection();
String sql="select password from user where username=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, username);
ResultSet rs = ps.executeQuery();
String pwd =null;
while(rs.next()){
pwd= rs.getString("password");
}
conn.close();
ps.close();
return pwd;
}
/**
* 注册时添加用户
* @param u
* @return
* @throws SQLException
*/
@Override
public int addUser(User u) throws SQLException {
conn=jdbcUtils.getConnection();
String sql="insert into user(username,password) values(?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, u.getUsername());
ps.setString(2, u.getPassword());
int i = ps.executeUpdate();
conn.close();
ps.close();
return i;
}
/**
* 添加产品
* @param p
* @throws SQLException
*/
@Override
public int addProduct(Product p) throws SQLException {
conn=jdbcUtils.getConnection();
String sql="insert into product(productName,price,description) values(?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, p.getProductName());
ps.setDouble(2, p.getPrice());
ps.setString(3, p.getDescription());
int i = ps.executeUpdate();
conn.close();
ps.close();
return i;
}
/**
* 查找所有的产品
* @return
* @throws SQLException
*/
@Override
public List<Product> findAllProduct() throws SQLException {
conn=jdbcUtils.getConnection();
String sql="select * from product";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery(sql);
List<Product> productList = new ArrayList<Product>();
Product p = new Product();
//for(int i=0;i<3;i++){
// while(rs.next()){
// //productList = new ArrayList<Product>();
// int id = rs.getInt("id");
// String productName = rs.getString("productName");
// Double price = rs.getDouble("price");
// String desc = rs.getString("desc");
// p.setId(id);
// p.setProductName(productName);
// p.setPrice(price);
// p.setDesc(desc);
// productList.add(p);
// }
//}
while(rs.next()){
Product product = new Product();
int id = rs.getInt("id");
String productName = rs.getString("productName");
Double price = rs.getDouble("price");
String description = rs.getString("description");
product.setId(id);
product.setProductName(productName);
product.setPrice(price);
product.setDescription(description);
productList.add(product);
}
return productList;
}
}
14.使用的jsbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/javaweb2?serverTimezone=GMT%2B8
user=root
password=root
总结:使用jdbc的时候在这个返回结果取值放入到product中,再放入到List中。需要在外面创建List,因为查询用ArrayList性能还不错,所以List实现类使用的是ArrayList,这个放入到list中的product,要在while(rs.next())中去创建对象, 数据添加到product中后,再添加到list中,list对象不要在里面创建,否则会出现循环只存入最后一组数据的情况,表字段起名字也不能取和关键字,有冲突。