JavaWeb

JavaBean

实体类

JavaBean有特定的写法:

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

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

ORM :对象关系映射

  • 表--->类
  • 字段-->属性
  • 行记录---->对象
peron
nameagelike
周钢1号22下棋
周钢2号22打球
周钢3号22编程
package com.zhou.entity;

public class peron {
    private String name;
    private int    age;
    private String like;
}

//可以通过有参构造存值
class A{
new peron ("周钢1号",22,"下棋");
new peron ("周钢2号",22,"打球");
new peron ("周钢3号",22,"编程");
}

Jsp标签存值

<!--id:自己设置的对象,任意设
    class:实体类的路径
    scope:作用域
    setProperty:存值。相当于set
    getProperty:取值。相当于get
    <jsp:getProperty name="peron" property="name"/>等价于out.println(pe.getName());
-->


<jsp:useBean id="peron" class="com.zhou.entity.peron" scope="page">
    <jsp:setProperty name="peron" property="name" value="周钢"/>
    <jsp:setProperty name="peron" property="age" value="22"/>
    <jsp:setProperty name="peron" property="like" value="下棋"/>
</jsp:useBean>

姓名:<jsp:getProperty name="peron" property="name"/>
年龄:<jsp:getProperty name="peron" property="age"/>
爱好:<jsp:getProperty name="peron" property="like"/>


<%
com.zhou.entity.peron pe=new peron();
pe.setName("周钢");
pe.setAge(22);
pe.setLike("下棋");
out.println("姓名:"+pe.getName());
out.println("年龄:"+pe.getAge());
out.println("爱好:"+pe.getLike());
%>

MVC三层架构

什么是MVC: Model view Controller 模型、视图、控制器

早些年

 用户直接访问控制层,控制层就可以直接操作数据库

servlet--CRUD-->数据库
弊端:程序十分臃肿,不利于维护
servlet的代码中:处理请求、响应、视图跳转、处理JDBC、处理业务代码、处理逻辑代码
架构:没有什么是加一层解决不了的!
程序猿调用
|
JDBC
|
Mysql Oracle SqlServer ....

MVC三层架构

 Model

  • 业务处理 :业务逻辑(Service)
  • 数据持久层:CRUD (Dao)

View

  • 展示数据
  • 提供链接发起Servlet请求 (a,form,img…)

Controller (Servlet)

  • 接收用户的请求 :(req:请求参数、Session信息….)
  • 交给业务层处理对应的代码
  • 控制视图的跳转
登录--->接收用户的登录请求--->处理用户的请求(获取用户登录的参数,username,
password)---->交给业务层处理登录业务(判断用户名密码是否正确:事务)--->Dao层查询用
户名和密码是否正确-->数据库

Filter (重点)

Filter:过滤器 ,用来过滤网站的数据

  • 处理中文乱码
  • 登录验证….

Filter开发步骤:

1.导包

2.编写过滤器 

      导包不要错

 实现Filter接口(其实Filter继承了servlet,所有Filter就是servlet),重写对应的方法即可

public class CharacterEncodingFilter implements Filter {
    //初始化:web服务器启动,就以及初始化了,随时等待过滤对象出现!
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("CharacterEncodingFilter初始化");
    }
    //FilterChain : 链
/*
1. 过滤中的所有代码,在过滤特定请求的时候都会执行
2. 必须要让过滤器继续同行
filterChain.doFilter(servletRequest,servletResponse);
*/

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setCharacterEncoding("utf-8");
        servletResponse.setContentType("text/html;charset=UTF-8");
        System.out.println("CharacterEncodingFilter执行前....");
        filterChain.doFilter(servletRequest, servletResponse); //让我们的请求继续走,如果不写,程序到这里就被拦截停止!
        System.out.println("CharacterEncodingFilter执行后....");

    }

    //销毁:web服务器关闭的时候,过滤会销毁
    public void destroy() {
        System.out.println("CharacterEncodingFilter销毁");
    }
}

servlet测试

public class ShowServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("周钢");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

3. 在web.xml中配置 Filter

 <filter>
        <filter-name>filter</filter-name>
        <filter-class>com.zhou.Filter.CharacterEncodingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>filter</filter-name>
        <!--设置在路径servlet下的所有路径进行过滤-->
        <url-pattern>/servlet/*</url-pattern>
    </filter-mapping>


<servlet>
    <servlet-name>servlet</servlet-name>
    <servlet-class>com.zhou.Servlet.ShowServlet</servlet-class>
</servlet>
    <servlet-mapping>
        <servlet-name>servlet</servlet-name>
        <url-pattern>/servlet/s1</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>servlet</servlet-name>
        <url-pattern>/s1</url-pattern>
    </servlet-mapping>

4.启动Tamcat访问localhost:8080/s1,此时浏览器会显示乱码,因为没有走过滤器;

访问localhost:8080/servlet/s1,此时浏览器会显示出周钢,因为走了过滤器。

监听器

实现一个监听器的接口;(有N种)

1. 编写一个监听器

     实现监听器的接口…

//统计网站在线人数 : 统计session
public class ServletContextListener implements HttpSessionListener {
    //创建session监听: 看你的一举一动
//一旦创建Session就会触发一次这个事件!
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        ServletContext cox = httpSessionEvent.getSession().getServletContext();
        System.out.println(httpSessionEvent.getSession().getId());
        Integer session = (Integer) cox.getAttribute("aa");
        if (session == null) {
            session = new Integer(1);
        } else {
            int cont = session.intValue();
            session = new Integer(cont + 1);
        }
        cox.setAttribute("aa", session);
    }

    //销毁session监听
//一旦销毁Session就会触发一次这个事件!
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        ServletContext cox = httpSessionEvent.getSession().getServletContext();
        Integer session = (Integer) cox.getAttribute("aa");
        if (session == null) {
            session = new Integer(0);
        } else {
            int cont = session.intValue();
            session = new Integer(cont - 1);
        }
        cox.setAttribute("aa", session);
    }
    /*
Session销毁:
1. 手动销毁 getSession().invalidate();
2. 自动销毁
*/
}

 JSP获取session

<h1>当前有<span style="color: blue"><%=
this.getServletConfig().getServletContext().getAttribute("aa")
%></span>人</h1>

2. web.xml中注册监听器

<listener>
        <listener-class>com.zhou.Listener.ServletContextListener</listener-class>
    </listener>

过滤器、监听器常见应用

监听器:GUI编程中经常使用

public class TestPanel {
    public static void main(String[] args) {
        Frame frame = new Frame("中秋节快乐"); //新建一个窗体
        Panel panel = new Panel(null); //面板
        frame.setLayout(null); //设置窗体的布局
        frame.setBounds(300,300,500,500);
        frame.setBackground(new Color(0,0,255)); //设置背景颜色
        panel.setBounds(50,50,300,300);
        panel.setBackground(new Color(0,255,0)); //设置背景颜色
        frame.add(panel);//添加面版到窗体
        frame.setVisible(true);//设置视图开启

        //监听事件,监听关闭事件
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowOpened(WindowEvent e) {
                System.out.println("打开");
            }

            @Override
            public void windowClosed(WindowEvent e) {
                System.out.println("关闭ed");
            }

            @Override
            public void windowClosing(WindowEvent e) {
                System.out.println("关闭ing");
                System.exit(0);
            }

            @Override
            public void windowActivated(WindowEvent e) {
                System.out.println("激活");
            }

            @Override
            public void windowDeactivated(WindowEvent e) {
                System.out.println("未激活");
            }
        });
    }
}

过滤器实现用户登录权限

1.编写登录页面Long.jsp

<form action="${pageContext.request.contextPath}/Long" method="get" style="text-align: center">
    <h1>登录</h1>
    <h3>姓名:<input type="text" name="username" style="height: 30px;width: 80px"></h3><br>
    <input type="submit" value="登录">
</form>

重点 :conxt是专门用来放全局对象的,因为所谓的登录权限就是通过LongServlet给session存值(用setAttribute存conxt里的aa,aa为键,getSession().getId()为值),如果直接登录success.jsp过滤器就会判断到aa是空的,就不能跳转到success.jsp,所谓的LongoutServlet(注销)就是清除aa的值,这样就达到登录权限的目的。第一次只要LongServlet给session存值成功,不清除值的话,就能直接登录success.jsp,反之过滤器判断到空值就会进行过滤。

public class conxt {
    public final static String aa="aa";
}

2.编写LongServlet

public class LongServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name=req.getParameter("username");
        if (name.equals("admin")){
            req.getSession().setAttribute("aa",req.getSession().getId());
            System.out.println(req.getSession().getId());
            resp.sendRedirect("/sys/success.jsp");
        }else {
            resp.sendRedirect("/erro.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

配置xml

<servlet>
        <servlet-name>long</servlet-name>
        <servlet-class>com.zhou.Servlet.LongServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>long</servlet-name>
        <url-pattern>/Long</url-pattern>
    </servlet-mapping>

3.编写success.jsp

<%--<%
String aa= (String) request.getSession().getAttribute("aa");
if (aa==null){
    response.sendRedirect("/Long.jsp");
}
%>--%>
<h1>主页</h1>
<p><a href="/Longout">注销</a></p>

4.编写LongoutServlet(注销)

public class LongoutServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String aa= (String) req.getSession().getAttribute("aa");
        if (aa!=null){
            req.getSession().removeAttribute("aa");
            resp.sendRedirect("/Long.jsp");
        }else {
            resp.sendRedirect("/Long.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

 配置xml

<servlet>
        <servlet-name>longout</servlet-name>
        <servlet-class>com.zhou.Servlet.LongoutServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>longout</servlet-name>
        <url-pattern>/Longout</url-pattern>
    </servlet-mapping>

5.编写erro.jsp

<h1>错误</h1>
<h3>没有权限,用户名</h3>
<p><a href="/Long.jsp">返回登录页面</a></p>

6.编写Filter过滤器

public class ServletFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse rep = (HttpServletResponse) servletResponse;
        String aa = (String) req.getSession().getAttribute("aa");
        if (aa == null) {
            rep.sendRedirect("/erro.jsp");
        }
        filterChain.doFilter(req, rep);
    }

    public void destroy() {

    }
}

配置xml

 <filter>
        <filter-name>ServletFilter</filter-name>
        <filter-class>com.zhou.Filter.ServletFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>ServletFilter</filter-name>
        <url-pattern>/sys/*</url-pattern>
    </filter-mapping>

7.注意:只把success.jsp放到sys包(自己设置的)下,不然都会过滤就报错了,总之哪个页面需要过滤就专门给它写个过滤器。

JDBC

什么是JDBC : Java连接数据库!

  • j:java
  • db:数据库
  • c:连接

需要jar包的支持:

  • java.sql
  • javax.sql
  • mysql-conneter-java… 连接驱动(必须要导入) 

实验环境搭建

CREATE TABLE users(
id INT PRIMARY KEY,
`name` VARCHAR(40),
`password` VARCHAR(40),
email VARCHAR(60),
birthday DATE
);
INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(1,'张三','123456','zs@qq.com','2000-01-01');
INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(2,'李四','123456','ls@qq.com','2000-01-01');
INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(3,'王五','123456','ww@qq.com','2000-01-01');
SELECT * FROM users;

导入数据库依赖(注意自己数据库的版本号)

<!--mysql的驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>

IDEA中连接数据库:

 JDBC 固定步骤:

1. 加载驱动

  • 数据库8.0
    com.mysql.cj.jdbc.Driver
  • 数据库5.0
    com.mysql.jdbc.Driver

2. 连接数据库,代表数据库

  • url:如果数据库是6.0以上的一定得加上时区
serverTimezone=UTC
  • 我自己的url:
    jdbc:mysql://localhost:3306/zhou?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
  • Connection connection = DriverManager.getConnection(url, username, password);

3. 向数据库发送SQL的对象Statement : CRUD

  • Statement statement = connection.createStatement()

4. 编写SQL (根据业务,不同的SQL)

5. 执行SQL

6. 关闭连接

public class TestJdbc {
public static void main(String[] args) throws ClassNotFoundException,
SQLException {
//配置信息
//useUnicode=true&characterEncoding=utf-8 解决中文乱码
String url="jdbc:mysql://localhost:3306/zhou?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC";
String username = "root";
String password = "123456";
//1.加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.连接数据库,代表数据库
Connection connection = DriverManager.getConnection(url, username,password);
//3.向数据库发送SQL的对象Statement,PreparedStatement : CRUD
Statement statement = connection.createStatement();
//4.编写SQL
String sql = "select * from users";
//5.执行查询SQL,返回一个 ResultSet : 结果集
ResultSet rs = statement.executeQuery(sql);
while (rs.next()){
System.out.println("id="+rs.getObject("id"));
System.out.println("name="+rs.getObject("name"));
System.out.println("password="+rs.getObject("password"));
System.out.println("email="+rs.getObject("email"));
System.out.println("birthday="+rs.getObject("birthday"));
}
//6.关闭连接,释放资源(一定要做) 先开后关
rs.close();
statement.close();
connection.close();
}
}

预编译SQL

public class TestJDBC2 {
public static void main(String[] args) throws Exception {
//配置信息
//useUnicode=true&characterEncoding=utf-8 解决中文乱码
String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC";
String username = "root";
String password = "123456";
//1.加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.连接数据库,代表数据库
Connection connection = DriverManager.getConnection(url, username,password);
//3.编写SQL
String sql = "insert into users(id, name, password, email,birthday) values (?,?,?,?,?);";
//4.预编译
PreparedStatement preparedStatement =connection.prepareStatement(sql);
preparedStatement.setInt(1,2);//给第一个占位符? 的值赋值为1;
preparedStatement.setString(2,"战神");//给第二个占位符? 的值赋值为战神;
preparedStatement.setString(3,"123456");//给第三个占位符? 的值赋值为123456;
preparedStatement.setString(4,"24736743@qq.com");//给第四个占位符? 的值赋值为24736743@qq.com;
preparedStatement.setDate(5,new Date(newjava.util.Date().getTime()));//给第五个占位符? 的值赋值为new Date(newjava.util.Date().getTime());
//5.执行SQL
int i = preparedStatement.executeUpdate();
if (i>0){
System.out.println("插入成功@");
}
//6.关闭连接,释放资源(一定要做) 先开后关
preparedStatement.close();
connection.close();
}
}

事务

要么都成功,要么都失败!

ACID原则:保证数据的安全。

开启事务
事务提交 commit()
事务回滚 rollback()
关闭事务
转账:
A:1000
B:1000
A(900) --100--> B(1100)

Junit单元测试

依赖

<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>

简单使用

@Test注解只有在方法上有效,只要加了这个注解的方法,就可以直接运行!

@Test
public void test(){
System.out.println("Hello");
}

失败的时候是红色:

 搭建一个环境

CREATE TABLE account(
id INT PRIMARY KEY AUTO_INCREMENT,
`name` VARCHAR(40),
money FLOAT
);
INSERT INTO account(`name`,money) VALUES('A',1000);
INSERT INTO account(`name`,money) VALUES('B',1000);
INSERT INTO account(`name`,money) VALUES('C',1000);
@Test
public void test() {
//配置信息
//useUnicode=true&characterEncoding=utf-8 解决中文乱码
String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC";
String username = "root";
String password = "123456";
Connection connection = null;
//1.加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库,代表数据库
connection = DriverManager.getConnection(url, username,password);
//3.通知数据库开启事务,false 开启
connection.setAutoCommit(false);
String sql = "update account set money = money-100 where name ='A'";
connection.prepareStatement(sql).executeUpdate();
//制造错误
//int i = 1/0;
String sql2 = "update account set money = money+100 where name ='B'";
connection.prepareStatement(sql2).executeUpdate();
connection.commit();//以上两条SQL都执行成功了,就提交事务!
System.out.println("success");
} catch (Exception e) {
try {
//如果出现异常,就通知数据库回滚事务
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值