Javaweb入门到实战过滤器拦截器jdbc详解

Posted ꧁༺空༒白༻꧂

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Javaweb入门到实战过滤器拦截器jdbc详解相关的知识,希望对你有一定的参考价值。

9、JavaBean

实体类

JavaBean有特定的写法:

  • 必须要有一个无参构造
  • 属性必须私有化
  • 必须有对应的get/set方法;

一般用来和数据库的字段做映射 ORM

ORM:对象关系映射

  • 表–>类
  • 字段–>属性
  • 行记录–>对象

person

idnameageaddress
1空空24西安
2圆圆14西安
3100西安
  • person实体类
public class person {
    private char id;
    private char name;
    private  int age;
    private  char address;

    public person() {

    }

    public person(char id, char name, int age, char address) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.address = address;
    }

    public char getId() {
        return id;
    }

    public void setId(char id) {
        this.id = id;
    }

    public char getName() {
        return name;
    }

    public void setName(char name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public char getAddress() {
        return address;
    }

    public void setAddress(char address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "person{" +
                "id=" + id +
                ", name=" + name +
                ", age=" + age +
                ", address=" + address +
                '}';
    }
}
  • javaBean.jsp
<jsp:useBean id="person" class="com.kongkong.jsps.person" scope="page"/>

<jsp:setProperty name="person" property="id" value="1"/>
<jsp:setProperty name="person" property="age" value="12"/>
<jsp:setProperty name="person" property="name" value="qing"/>
<jsp:setProperty name="person" property="address" value="guangzhou"/>


<jsp:getProperty name="person" property="id"/>
<jsp:getProperty name="person" property="name"/>
<jsp:getProperty name="person" property="age"/>
<jsp:getProperty name="person" property="address"/>

10、MVC三层架构

  • Model(模块)
    • 业务处理:业务逻辑
    • 数据持久层:CRUD
  • View(视图层)
    • 展示数据
    • 提供连接发起Servlet
  • Controller(控制层)
    • 接收用户的请求
    • 交给业务层处理对应的代码
    • 控制视图的跳转

执行流程

登录–>接收用户的登录请求–>处理用户的请求(获取用户的账号密码)–>业务层处理登录业务(判断密码正确性)–>Dao层查询用户账户和密码是否正确–>数据库

11、过滤器

  • web.xml配置
<filter>
        <filter-name>charFilter</filter-name>
        <filter-class>com.kongkong.jsps.charFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>charFilter</filter-name>
<!--        只要是servlet文件就会经过这个过滤器-->
        <url-pattern>/servlet/*</url-pattern>
    </filter-mapping>
  • charFilter继承Filter类
public class charFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化");
    }

    /*
    Chain:链
    过滤器中所有代码,在过滤特定请求的时候都会执行
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        System.out.println("执行前");
        chain.doFilter(request, response);//请求能继续往下走,不让会被拦截
        System.out.println("执行后");
    }

    @Override
    public void destroy() {
        System.out.println("销毁");//在关闭程序运行时,过滤会销毁
    }
}
  • Servlet
public class servlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("你好世界");
    }

12、监听器

例子:做一个session监听

写一个监听方法类onlineListen

//session监听,统计在线人数
public class onlineListen implements HttpSessionListener {
    @Override
    //创建事件的监听
    public void sessionCreated(HttpSessionEvent se) {
        ServletContext servletContext = se.getSession().getServletContext();
        Integer onlineContext = (Integer) servletContext.getAttribute("onlineContext");
        if(onlineContext==null){
            onlineContext=new Integer(1);
        }else {
            int num=onlineContext.intValue();
            onlineContext=new Integer(num+1);
        }
        servletContext.setAttribute("onlineContext",onlineContext);


    }
    //销毁事件的监听
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext servletContext = se.getSession().getServletContext();
        Integer onlineContext = (Integer) servletContext.getAttribute("onlineContext");
        if(onlineContext==null){
            onlineContext=new Integer(0);
        }else {
            int num=onlineContext.intValue();
            onlineContext=new Integer(num-1);
        }
        servletContext.setAttribute("onlineContext",onlineContext);

    }

写一个页面的jsp

<body>
<h1>当前有<span><%=this.getServletConfig().getServletContext().getAttribute("onlineContext")%></span>人</h1>
</body>

配置web.xml

<listener>
    <listener-class>com.kongkong.jsps.onlineListen</listener-class>
</listener>

 //分钟为期限,刷新监听器
    <session-config>
        <session-timeout>1</session-timeout>
    </session-config>

然后测试,在不同的浏览器打开才会刷新在线用户

13、Filter过滤器拦截器的应用

编写一个简单的登录页面

  • 先写一个登录的页面,login.jsp
<form action="/servlet/login" method="post">
    用户名:<input type="text" name="username">
    登录:<input type="submit" name="submit">
</form>
  • 然后写一个登录的loginServlet类
public class loginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取前端的参数
        String username = req.getParameter("username");
        //trim()表示判断时候不会太严格,可以携带空格,注意只能在最后携带,不能插在中间
        if(username.trim().equals("kongkong")){
            req.getSession().setAttribute("userName",req.getSession().getId());
            resp.sendRedirect("/sucess.jsp");
        }else {
            resp.sendRedirect("/fail.jsp");
        }
    }
  • 登录失败的页面
<h1>登录失败,请重新登录</h1>
<a href="login.jsp">点击返回登录</a>
  • 登录失败的控制类loginOutServlet
public class loginOutServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Object userName = req.getSession().getAttribute("userName");
        if(userName!=null){
            req.getSession().removeAttribute("userName");
            resp.sendRedirect("/fail.jsp");
        }
    }
  • 写一个拦截器sysFile
public class sysFile implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request1 = (HttpServletRequest) request;
        HttpServletResponse request2 = (HttpServletResponse) response;

        if(((HttpServletRequest) request).getSession().getAttribute("userName")==null){
            ((HttpServletResponse) response).sendRedirect("/fail.jsp");
        }
        chain.doFilter(request1,request2);
    }
  • 配置web.xml文件
<servlet>
    <servlet-name>loginOutServlet</servlet-name>
    <servlet-class>com.kongkong.jsps.loginOutServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>loginOutServlet</servlet-name>
    <url-pattern>/servlet/logout</url-pattern>
</servlet-mapping>

<servlet>
    <servlet-name>loginServlet</servlet-name>
    <servlet-class>com.kongkong.jsps.loginServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>loginServlet</servlet-name>
    <url-pattern>/servlet/login</url-pattern>
</servlet-mapping>

<filter>
    <filter-name>file</filter-name>
    <filter-class>com.kongkong.jsps.sysFile</filter-class>
</filter>
<filter-mapping>
    <filter-name>file</filter-name>
    <url-pattern>/servlet/*</url-pattern>
</filter-mapping>

14、JDBC

实现步骤

  1. 在数据库中创建一张users表

    create table users(
    id int(2) primary key not null,
    `name` char(20) not null,
    `password` int(4) not null,
    address char(15) not null,
    )
    
  2. 新建一个maven项目

    在pom.xml文件下添加数据库依赖

    <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.47</version>
            </dependency>
    
  3. 编写一个测试类JDBCtest

    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //配置信息
        String url="jdbc:mysql://localhost:3306/jsp?useUnicode=true&characterEncoding=utf-8&useSSL=true";
        String username="root";
        String password="root";
        //1.加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2.连接数据库,代表数据库
        Connection connection= DriverManager.getConnection(url,username,password);
        //3.向数据库发送SQL的对象Statement:CRUD
        Statement statement = connection.createStatement();
        //4.编写SQL
        String sql="select * from jsp.users";
        //执行查询SQL,返回一个ResultSet:结果集
        ResultSet resultSet = statement.executeQuery(sql);
    
        while(resultSet.next()){
            System.out.println("id="+resultSet.getObject("id"));
            System.out.println("name="+resultSet.getObject("name"));
            System.out.println("password="+resultSet.getObject("password"));
            System.out.println("address="+resultSet.getObject("address"));
        }
        //关闭连接,释放资源
        resultSet.close();
        statement.close();
        connection.close();
    }
    
  4. 总结jdbc固定步骤

    • 加载驱动
    • 连接数据库,代表数据库
    • 向数据库发送SQL的对象statement:CRUD
    • 编写SQL
    • 执行SQL
    • 关闭连接
  5. 预编译

    //配置信息
    String url="jdbc:mysql://localhost:3306/jsp?useUnicode=true&characterEncoding=utf-8&useSSL=true";
    String username="root";
    String password="root";
    //1.加载驱动
    Class.forName("com.mysql.jdbc.Driver");
    //2.连接数据库,代表数据库
    Connection connection= DriverManager.getConnection(url,username,password);
    //3.编写SQL,?为占位符
    String sql="insert into users(id,name,password,address) values(?,?,?,?);";
    //4.预编译
    PreparedStatement preparedStatement = connection.prepareStatement(sql);
    
    preparedStatement.setInt(1,4);
    preparedStatement.setString(2,"喜喜");
    preparedStatement.setInt(3,4);
    preparedStatement.setString(4,"广西");
    
    //执行SQL
    int i=preparedStatement.executeUpdate();
    if(i>0){
        System.out.println("插入成功");
    }
    //关闭连接,释放资源
    preparedStatement.close();
    connection.close();
    
  6. jdbc事务

    1. 导入单元测试类junit依赖
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>compile</scope>
    </dependency>
    
    1. 数据库新建一个账户表

      CREATE TABLE account(
      id int PRIMARY KEY AUTO_INCREMENT,
      `name` char(20),
      money FLOAT
      );
      
    2. localhost处理事务

      start transaction ;#开启事务
      
      update account set money=money-10 where name='a';
      update account set money=money+10 where name='b';
      
      rollback;#回滚事务
      commit;#提交事务 
      
    3. java代码实现

      public class testJDBC {
          @Test
          public  void test() {
              //配置信息
              String url = "jdbc:mysql://localhost:3306/jsp?useUnicode=true&characterEncoding=utf-8&useSSL=true"JavaWeb——过滤器Filter和拦截器Interceptor

      JavaWEB-03-JDBC

      Spring Security4实战与原理分析视频课程( 扩展+自定义)

      Spring Security4实战与原理分析视频课程( 扩展+自定义)

      javaweb需要会啥技术

      JavaWeb - JDBC各个类详解工具类解决sql注入