栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java(JavaWeb05)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java(JavaWeb05)

Java(JavaWeb05)

参考视频:30. smbms项目搭建(狂神)

15. SMBMS项目搭建
  • 基本框架:

  • 数据库:

  • 项目如何搭建?

    • 要不要用Maven?依赖以及jar包?

 

15.1 项目搭建的准备工作:
  1. 搭建一个Maven Web项目

  2. 配置Tomcat

  3. 测试项目是否能跑起来

  4. 导入项目中会遇到的jar包
    servlet-api
    javax.servlet.jsp-api
    mysql-connector-java
    jstl-api
    standard

  5. 创建项目包结构

  6. 编写实体类
    ORM映射:表-类 映射

  7. 编写基础公共类
    1.数据库配置文件
    2.编写数据库的公共类
    3.编写字符编码过滤器

  8. 导入静态资源

1. 配置文件
  • pom.xml



	4.0.0
	
	com.zach
	smbms
	1.0-SNAPSHOT
	war
	
	
		
			javax.servlet
			servlet-api
			2.5
		
		
			javax.servlet.jsp
			javax.servlet.jsp-api
			2.3.3
		
		
			mysql
			mysql-connector-java
			5.1.47
		
		
		
			javax.servlet.jsp.jstl
			jstl-api
			1.2
		
		
		
			taglibs
			standard
			1.1.2
		
	

  • web.xml




	
	
		CharacterEncodingFilter
		com.zach.filter.CharacterEncodingFilter
	
	
		CharacterEncodingFilter
		/*
	
	

2. 实体类
  • User
package com.zach.pojo;

import java.util.Calendar;
import java.util.Date;

public class User {
    private Integer id; //id
    private String userCode;    //用户编码
    private String userName;    //用户名称
    private String userPassword;    //用户密码
    private Integer gender; //性别
    private Date birthday;  //出生日期
    private String phone;   //电话
    private String address; //地址
    private Integer userRole;   //用户角色
    private Integer createdBy;  //创建者
    private Integer modifyBy;   //创建时间
    private Date creationDate;  //更新者
    private Date modifyDate;    //更新时间
    
    private Integer age;    //年龄
    private String userRoleName;    //用户角色名称
    
    public Integer getId() {
        return id;
    }
    
    public void setId(Integer id) {
        this.id = id;
    }
    
    public String getUserCode() {
        return userCode;
    }
    
    public void setUserCode(String userCode) {
        this.userCode = userCode;
    }
    
    public String getUserName() {
        return userName;
    }
    
    public void setUserName(String userName) {
        this.userName = userName;
    }
    
    public String getUserPassword() {
        return userPassword;
    }
    
    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }
    
    public Integer getGender() {
        return gender;
    }
    
    public void setGender(Integer gender) {
        this.gender = gender;
    }
    
    public Date getBirthday() {
        return birthday;
    }
    
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    
    public String getPhone() {
        return phone;
    }
    
    public void setPhone(String phone) {
        this.phone = phone;
    }
    
    public String getAddress() {
        return address;
    }
    
    public void setAddress(String address) {
        this.address = address;
    }
    
    public Integer getUserRole() {
        return userRole;
    }
    
    public void setUserRole(Integer userRole) {
        this.userRole = userRole;
    }
    
    public Integer getCreatedBy() {
        return createdBy;
    }
    
    public void setCreatedBy(Integer createdBy) {
        this.createdBy = createdBy;
    }
    
    public Integer getModifyBy() {
        return modifyBy;
    }
    
    public void setModifyBy(Integer modifyBy) {
        this.modifyBy = modifyBy;
    }
    
    public Date getCreationDate() {
        return creationDate;
    }
    
    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }
    
    public Date getModifyDate() {
        return modifyDate;
    }
    
    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }
    
    public Integer getAge() {
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int nowYear = calendar.get(Calendar.YEAR);
        calendar.setTime(birthday);
        int birthYear = calendar.get(Calendar.YEAR);
        
        return nowYear - birthYear;
    }
    
    public void setAge(Integer age) {
        this.age = age;
    }
    
    public String getUserRoleName() {
        return userRoleName;
    }
    
    public void setUserRoleName(String userRoleName) {
        this.userRoleName = userRoleName;
    }
    
}
  • Role
package com.zach.pojo;

import java.util.Date;

public class Role {
    private Integer id; //id
    private String roleCode;    //角色编码
    private String roleName;    //角色名称
    private Integer createdBy;  //创建者
    private Integer modifyBy;   //创建时间
    private Date creationDate;  //更新者
    private Date modifyDate;    //更新时间
    
    public Integer getId() {
        return id;
    }
    
    public void setId(Integer id) {
        this.id = id;
    }
    
    public String getRoleCode() {
        return roleCode;
    }
    
    public void setRoleCode(String roleCode) {
        this.roleCode = roleCode;
    }
    
    public String getRoleName() {
        return roleName;
    }
    
    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }
    
    public Integer getCreatedBy() {
        return createdBy;
    }
    
    public void setCreatedBy(Integer createdBy) {
        this.createdBy = createdBy;
    }
    
    public Integer getModifyBy() {
        return modifyBy;
    }
    
    public void setModifyBy(Integer modifyBy) {
        this.modifyBy = modifyBy;
    }
    
    public Date getCreationDate() {
        return creationDate;
    }
    
    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }
    
    public Date getModifyDate() {
        return modifyDate;
    }
    
    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }
}
  • Provider
package com.zach.pojo;

import java.util.Date;

public class Provider {
    private Integer id; //id
    private String proCode; //供应商编码
    private String proName; //供应商名称
    private String proDesc; //供应商描述
    private String proContact;  //供应商联系人
    private String proPhone;    //供应商电话
    private String proAddress;  //供应商地址
    private String proFax;  //供应商传真
    private Integer createdBy;  //创建者
    private Integer modifyBy;   //创建时间
    private Date creationDate;  //更新者
    private Date modifyDate;    //更新时间
    
    public Integer getId() {
        return id;
    }
    
    public void setId(Integer id) {
        this.id = id;
    }
    
    public String getProCode() {
        return proCode;
    }
    
    public void setProCode(String proCode) {
        this.proCode = proCode;
    }
    
    public String getProName() {
        return proName;
    }
    
    public void setProName(String proName) {
        this.proName = proName;
    }
    
    public String getProDesc() {
        return proDesc;
    }
    
    public void setProDesc(String proDesc) {
        this.proDesc = proDesc;
    }
    
    public String getProContact() {
        return proContact;
    }
    
    public void setProContact(String proContact) {
        this.proContact = proContact;
    }
    
    public String getProPhone() {
        return proPhone;
    }
    
    public void setProPhone(String proPhone) {
        this.proPhone = proPhone;
    }
    
    public String getProAddress() {
        return proAddress;
    }
    
    public void setProAddress(String proAddress) {
        this.proAddress = proAddress;
    }
    
    public String getProFax() {
        return proFax;
    }
    
    public void setProFax(String proFax) {
        this.proFax = proFax;
    }
    
    public Integer getCreatedBy() {
        return createdBy;
    }
    
    public void setCreatedBy(Integer createdBy) {
        this.createdBy = createdBy;
    }
    
    public Integer getModifyBy() {
        return modifyBy;
    }
    
    public void setModifyBy(Integer modifyBy) {
        this.modifyBy = modifyBy;
    }
    
    public Date getCreationDate() {
        return creationDate;
    }
    
    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }
    
    public Date getModifyDate() {
        return modifyDate;
    }
    
    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }
}
  • Bill
package com.zach.pojo;

import java.util.Date;

public class Bill {
    private Integer id; //id
    private String billCode;    //账单编码
    private String productName; //商品名称
    private String productDesc; //商品描述
    private String productUnit; //商品单位
    private Double productCount;    //商品数量
    private Double totalPrice;  //总金额
    private Integer isPayment;  //是否支付
    private Integer createdBy;  //供应商ID
    private Integer modifyBy;   //创建者
    private Date creationDate;  //创建时间
    private Date modifyDate;    //更新者
    private Integer providerId; //更新时间
    
    private String providerName;    //供应商名称
    
    public Integer getId() {
        return id;
    }
    
    public void setId(Integer id) {
        this.id = id;
    }
    
    public String getBillCode() {
        return billCode;
    }
    
    public void setBillCode(String billCode) {
        this.billCode = billCode;
    }
    
    public String getProductName() {
        return productName;
    }
    
    public void setProductName(String productName) {
        this.productName = productName;
    }
    
    public String getProductDesc() {
        return productDesc;
    }
    
    public void setProductDesc(String productDesc) {
        this.productDesc = productDesc;
    }
    
    public String getProductUnit() {
        return productUnit;
    }
    
    public void setProductUnit(String productUnit) {
        this.productUnit = productUnit;
    }
    
    public Double getProductCount() {
        return productCount;
    }
    
    public void setProductCount(Double productCount) {
        this.productCount = productCount;
    }
    
    public Double getTotalPrice() {
        return totalPrice;
    }
    
    public void setTotalPrice(Double totalPrice) {
        this.totalPrice = totalPrice;
    }
    
    public Integer getIsPayment() {
        return isPayment;
    }
    
    public void setIsPayment(Integer isPayment) {
        this.isPayment = isPayment;
    }
    
    public Integer getCreatedBy() {
        return createdBy;
    }
    
    public void setCreatedBy(Integer createdBy) {
        this.createdBy = createdBy;
    }
    
    public Integer getModifyBy() {
        return modifyBy;
    }
    
    public void setModifyBy(Integer modifyBy) {
        this.modifyBy = modifyBy;
    }
    
    public Date getCreationDate() {
        return creationDate;
    }
    
    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }
    
    public Date getModifyDate() {
        return modifyDate;
    }
    
    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }
    
    public Integer getProviderId() {
        return providerId;
    }
    
    public void setProviderId(Integer providerId) {
        this.providerId = providerId;
    }
    
    public String getProviderName() {
        return providerName;
    }
    
    public void setProviderName(String providerName) {
        this.providerName = providerName;
    }
}
  • Address
package com.zach.pojo;

import java.util.Date;

public class Address {
    private Integer id;
    private String contact;
    private String addressDesc;
    private String postCode;
    private String tel;
    private Integer createdBy;
    private Integer modifyBy;
    private Date creationDate;
    private Date modifyDate;
    private Integer userId;
    
    public Integer getId() {
        return id;
    }
    
    public void setId(Integer id) {
        this.id = id;
    }
    
    public String getContact() {
        return contact;
    }
    
    public void setContact(String contact) {
        this.contact = contact;
    }
    
    public String getAddressDesc() {
        return addressDesc;
    }
    
    public void setAddressDesc(String addressDesc) {
        this.addressDesc = addressDesc;
    }
    
    public String getPostCode() {
        return postCode;
    }
    
    public void setPostCode(String postCode) {
        this.postCode = postCode;
    }
    
    public String getTel() {
        return tel;
    }
    
    public void setTel(String tel) {
        this.tel = tel;
    }
    
    public Integer getCreatedBy() {
        return createdBy;
    }
    
    public void setCreatedBy(Integer createdBy) {
        this.createdBy = createdBy;
    }
    
    public Integer getModifyBy() {
        return modifyBy;
    }
    
    public void setModifyBy(Integer modifyBy) {
        this.modifyBy = modifyBy;
    }
    
    public Date getCreationDate() {
        return creationDate;
    }
    
    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }
    
    public Date getModifyDate() {
        return modifyDate;
    }
    
    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }
    
    public Integer getUserId() {
        return userId;
    }
    
    public void setUserId(Integer userId) {
        this.userId = userId;
    }
}
3. 数据库配置文件(以及对应公共类)
  • db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306?useUnicode=true&characterEncoding=utf-8&useSSL=false
username=root
password=123456
  • BaseDao(操作数据库的公共类)
package com.zach.dao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

//操作数据库的公共类
public class BaseDao {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;
    
    //静态代码块,类加载的时候就初始化了
    static{
        Properties properties = new Properties();
        //通过类加载器读取对应的资源
        InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
    
        try {
            properties.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        driver = properties.getProperty("driver");
        url = properties.getProperty("url");
        username = properties.getProperty("username");
        password = properties.getProperty("password");
        
    }
    
    //获取数据库的连接
    public static Connection getConnection(){
        Connection connection = null;
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }
    
    //编写查询公共类
    public static ResultSet execute(Connection connection,PreparedStatement preparedStatement,String sql,Object[] params) throws SQLException {
        //预编译的sql,在后面直接执行就可以了。不用传到preparedStatement.executeQuery();
        preparedStatement = connection.prepareStatement(sql);
    
        for (int i = 0; i < params.length; i++) {
            //setObject,占位符从1开始,但是我们的数组是从0开始!
            preparedStatement.setObject(i+1,params[i]);
        }
    
        resultSet = preparedStatement.executeQuery();
        return resultSet;
    }
    
    //编写增删改公共方法
    public static int execute(Connection connection,String sql,Object[] params,PreparedStatement preparedStatement) throws SQLException {
        preparedStatement = connection.prepareStatement(sql);
    
        for (int i = 0; i < params.length; i++) {
            //setObject,占位符从1开始,但是我们的数组是从0开始!
            preparedStatement.setObject(i+1,params[i]);
        }
    
        int updateRows = preparedStatement.executeUpdate();
        return updateRows;
    }
    
    //释放资源方法
    public static boolean closeResource(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet){
        boolean flag = true;
    
        if (resultSet!=null) {
            try {
                resultSet.close();
                //如果还在,让GC回收
                resultSet = null;
            } catch (SQLException e) {
                e.printStackTrace();
                flag = false;
            }
        }
        if (preparedStatement!=null) {
            try {
                preparedStatement.close();
                //如果还在,让GC回收
                preparedStatement = null;
            } catch (SQLException e) {
                e.printStackTrace();
                flag = false;
            }
        }
        if (connection!=null) {
            try {
                connection.close();
                //如果还在,让GC回收
                connection = null;
            } catch (SQLException e) {
                e.printStackTrace();
                flag = false;
            }
        }
        return flag;
    }
    
}
4. 字符编码过滤器
  • CharacterEncodingFilter (记得在web.xml中配置过滤器)
package com.zach.filter;

import javax.servlet.*;
import java.io.IOException;

public class CharacterEncodingFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    
    }
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        
        chain.doFilter(request,response);
    }
    
    @Override
    public void destroy() {
    
    }
}
15.2 登录功能实现

  1. 编写前端页面
  2. 设置首页(配置)
  • web.xml
	
	
		login.jsp
	
  1. 编写dao层登录用户 登录的接口
package com.zach.dao.user;

import com.zach.pojo.User;

import java.sql.Connection;
import java.sql.SQLException;

//面向接口编程
public interface UserDao {
    
    //得到需要登录的用户
    public User getLoginUser(Connection connection, String userCode) throws SQLException;

}
  1. 编写dao接口 的实现类
package com.zach.dao.user;

import com.zach.dao.BaseDao;
import com.zach.pojo.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImpl implements UserDao{
    @Override
    public User getLoginUser(Connection connection, String userCode) {
    
        PreparedStatement pstm = null;
        ResultSet rs = null;
        User user = null;
        
        if (connection!=null){
            String sql = "select * from smbms_user where userCode=?;";
            Object[] params = {userCode};
            
            try {
                rs = BaseDao.execute(connection, pstm, rs, sql, params);
    
                if (rs.next()) {
                    user = new User();
                    user.setId(rs.getInt("id"));
                    user.setUserCode(rs.getString("userCode"));
                    user.setUserName(rs.getString("userName"));
                    user.setUserPassword(rs.getString("userPassword"));
                    user.setGender(rs.getInt("gender"));
                    user.setBirthday(rs.getDate("birthday"));
                    user.setPhone(rs.getString("phone"));
                    user.setAddress(rs.getString("address"));
                    user.setUserRole(rs.getInt("userRole"));
                    user.setCreatedBy(rs.getInt("createdBy"));
                    user.setCreationDate(rs.getTimestamp("creationDate"));
                    user.setModifyBy(rs.getInt("modifyBy"));
                    user.setModifyDate(rs.getTimestamp("modifyDate"));
                }
                BaseDao.closeResource(connection,pstm,rs);
                
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        
        return user;
    }
}
  1. 业务层接口
  • UserService
package com.zach.service.user;

import com.zach.pojo.User;

public interface UserService {
    //用户登录
    public User login(String userCode, String password);
}
  1. 业务层实现类
  • UserServiceImpl
package com.zach.service.user;

import com.zach.dao.BaseDao;
import com.zach.dao.user.UserDao;
import com.zach.dao.user.UserDaoImpl;
import com.zach.pojo.User;
import org.junit.Test;

import java.sql.Connection;
import java.sql.SQLException;

public class UserServiceImpl implements UserService{
    //业务层都会调用dao层,所以我们要引入Dao层
    private UserDao userDao;
    public UserServiceImpl(){
        userDao = new UserDaoImpl();
    }
    
    @Override
    public User login(String userCode, String password) {
        Connection connection = null;
        User user = null;

        try {
            connection = BaseDao.getConnection();
            //通过业务层调用对应的具体的数据库操作
            user = userDao.getLoginUser(connection,userCode);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            BaseDao.closeResource(connection, null,null);
        }
        return user;
    }
    
}
  1. 编写Servlet
  • LoginServlet
package com.zach.servlet.user;

import com.zach.pojo.User;
import com.zach.service.user.UserService;
import com.zach.service.user.UserServiceImpl;
import com.zach.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    //Servlet:控制层,调用业务层代码
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
        
        System.out.println("LoginServlet--start...");
        
        //获取用户名和密码
        String userCode = req.getParameter("userCode");
        String userPassword = req.getParameter("userPassword");
        
        //和数据库中的密码进行对比,调用业务层
        UserService userService = new UserServiceImpl();
        User user = userService.login(userCode, userPassword);
        
        if (user!=null){//调用该接口查询后 有返回值 发现查有此人
            //将用户的信息放到Session中
            req.getSession().setAttribute(Constants.USER_SESSION,user);
            //跳转到主页
            resp.sendRedirect("jsp/frame.jsp");
        }else {//查无此人,无法登陆
            //转发回登录页面,顺便提示他:用户名或密码错误
            req.setAttribute("error","用户名或密码错误!");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
  1. 注册Servlet
  • web.xml
	
	
		LoginServlet
		com.zach.servlet.user.LoginServlet
	
	
		LoginServlet
		/login.do
	
  1. 测试访问,确保以上功能成功!
  • 可能出现的问题:
  • No database selected
    在db.properties中添加smbms:url=jdbc:mysql://localhost:3306/smbms?useUnicode=true&characterEncoding=utf-8&useSSL=false
15.3 登录功能优化
  • 注销功能:
  • 思路:移除Session,返回登录页面。
  • LogoutServlet
package com.zach.servlet.user;

import com.zach.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LogoutServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //移除用户的Session:Constants.USER_SESSION //req请求 resp响应
        req.getSession().removeAttribute(Constants.USER_SESSION);
        resp.sendRedirect(req.getContextPath()+"/login.jsp");//返回登录页面
        //resp.sendRedirect("/smbms/login.jsp");//返回登录页面
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
  • web.xml
	
		LogoutServlet
		com.zach.servlet.user.LogoutServlet
	
	
		LogoutServlet
		/jsp/logout.do
	

 

  • 登录拦截优化:
  • 编写一个过滤器,并注册。
package com.zach.filter;

import com.zach.pojo.User;
import com.zach.util.Constants;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SysFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    
    }
    
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;//为了获取session
        HttpServletResponse response = (HttpServletResponse) resp;//为了重定向
    
        //过滤器,从Session中获取用户
        User user = (User) request.getSession().getAttribute(Constants.USER_SESSION);
        if (user==null) {//已经注销或者溢出或者未登录。
            response.sendRedirect("/smbms/error.jsp");
        }else {
            chain.doFilter(req,resp);
        }

    }
    
    @Override
    public void destroy() {
    
    }
}
  • web.xml
	
	
		SysFilter
		com.zach.filter.SysFilter
	
	
		SysFilter
		/jsp/*
	
  • 测试,登录,注销,权限,都要保证OK!

 

  • 登录时缺少的密码验证:
  • LoginServlet
if (user!=null&&user.getUserPassword().equals(userPassword)){
...
}

 
 

—————— THE END ——————
 
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/975981.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号