木舟0基础学习Java的第二十六天(JavaWeb)

设置响应头

resp.setHeader("key","nihao");//推荐使用英文 中文会乱码

案例:模拟登录

 jdbc.properties

driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?verifyServerCertificate=false&useSSL=false
name=root
password=123456

JDBCUtil

public class JDBCUtil {
    static String driverClass=null;
    static String url=null;
    static String name=null;
    static String password=null;
    static{
        Properties properties=new Properties();
        InputStream is=null;
        try {
            is=JDBCUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
            properties.load(is);
            driverClass=properties.getProperty("driverClass");
            url=properties.getProperty("url");
            name=properties.getProperty("name");
            password=properties.getProperty("password");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public static Connection getConn(){
        Connection conn=null;
        try {
            Class.forName(driverClass);
            conn= DriverManager.getConnection(url,name,password);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return conn;
    }
    private static void closeConn(Connection conn){
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }finally{
                conn=null;
            }
        }
    }
    private static void closePs(PreparedStatement ps){
        if(ps!=null){
            try {
                ps.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }finally{
                ps=null;
            }
        }
    }
    private static void closeRs(ResultSet rs){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }finally{
                rs=null;
            }
        }
    }
   public static void release(Connection conn,PreparedStatement ps,ResultSet rs){
       closeRs(rs);
       closePs(ps);
       closeConn(conn);
   }
    public static void release(Connection conn,PreparedStatement ps){
        closePs(ps);
        closeConn(conn);
    }
}

T_user

需要实现序列化 Serializable接口

public class T_user implements Serializable{
    private int id;
    private String name;
    private String pwd;

    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 String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    @Override
    public String toString() {
        return "T_user{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}

UserDao

public interface UserDao {
    public T_user login(String uname, String pwd);
}

UserDaoImpl

public class UserDaoImpl implements UserDao {
    //处理数据连接数据库
    Connection conn=null;
    PreparedStatement ps=null;
    ResultSet rs=null;
    T_user user=null;
    @Override
    public T_user login(String uname, String pwd) {
        try {
            conn= JDBCUtil.getConn();
            String sql="select * from t_user where uname=? and pwd=?";
            ps=conn.prepareStatement(sql);
            ps.setString(1,uname);
            ps.setString(2,pwd);
            rs=ps.executeQuery();
            while(rs.next()){
                String uname1 = rs.getString("uname");
                String pwd1 = rs.getString("pwd");
                user=new T_user();
                user.setName(uname1);
                user.setPwd(pwd1);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally{
            JDBCUtil.release(conn,ps,rs);
        }
        return user;
    }
}

LoginService

@WebServlet("/LoginService")
public class LoginService extends HttpServlet {
    private UserDao UserDao;
    public LoginService() {
        UserDao=new UserDaoImpl();
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String uname = req.getParameter("uname");
        String pwd = req.getParameter("pwd");
        System.out.println("uname:" + uname + "\tpwd:" + pwd);
        T_user user=UserDao.login(uname,pwd);
        if(user!=null){
            resp.getWriter().write("<font color='red' size=30>登录成功,欢迎"+user.getName()+"回来!</font>");
        }else{
            resp.getWriter().write("<font color='red' size=30>登录失败,账号或密码错误!</font>");
        }
    }
}

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="LoginService" method="post">
  用户名:<input type="text" name="uname">
  密码:<input type="password" name="pwd">
    爱好:<input type="checkbox" name="hobby" value="抽烟">抽烟
    <input type="checkbox" name="hobby" value="喝酒">喝酒
    <input type="checkbox" name="hobby" value="烫头">烫头
    <input type="checkbox" name="hobby" value="蹦迪">蹦迪
  <input type="submit" value="提交">
</form>
</body>
</html>

请求转发重定向

请求转发

特点:路径不会发生改变

缺点:每次刷新页面 就相当于重新提交

请求转发 在登录场景 和 转账场景不能使用
req.getRequestDispatcher("success.html").forward(req,resp);

重定向

缺点:不能携带数据

 resp.sendRedirect("success.html");

servlet跳转servlet

//将数据以键值对的方式存入
            req.setAttribute("user", user);//key,value
            req.getRequestDispatcher("HanderServlet").forward(req, resp);
@WebServlet("/HanderServlet")
public class HanderServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       T_user user = (T_user)req.getAttribute("user");//利用getAttribute获取值
       resp.getWriter().write("<h1>系统提示</h1>");
       resp.getWriter().write("<hr/>");
       resp.getWriter().write("<font color='red'>欢迎,"+user.getUname()+"登录成功!</font>");
    }
}

Cookie

cookie技术是浏览器端的数据存储技术 解决了同一个工程下不同请求需要使用相同数据的问题 我们把请求需要共享的请求数据 存储在浏览器端 避免用户进行重复书写请求数据 

特点:适合少量数据 键值对 不安全

注意:一个cookie对象存储一条数据 多条数据 可以创建多个cookie对象进行存储

作用:Cookie技术解决不同请求发送之间的数据共享问题

Cookie的使用

@WebServlet("/LoginSerlet")
public class LoginUser extends HttpServlet {
    private com.dao.UserDao UserDao;

    public LoginUser() {
        UserDao = new UserDaoImpl();
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        String uname = req.getParameter("uname");
        String pwd = req.getParameter("pwd");
        System.out.println("uname:" + uname + "\tpwd:" + pwd);
        T_user user=UserDao.login(uname,pwd);
        if(user!=null){
            //将数据存储到Cookie当中
            Cookie c1=new Cookie("name",user.getUname());
            Cookie c2=new Cookie("pwd",user.getPwd());
            //设置三天免登录 默认不设置时间 关闭浏览器立即失效
            c1.setMaxAge(24*3600*3);
            //把存储了登录信息的Cookie 通过响应resp 响应到浏览器中
            resp.addCookie(c1);
            resp.addCookie(c2);
            resp.sendRedirect("success");
        }else{
            req.getRequestDispatcher("login.html").forward(req, resp);
        }
    }
}
@WebServlet("/success")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        //通过浏览器携带的cookie name=admin pwd=123456 找tomcat中cookie对象的数据
        //获取cookie
        Cookie[] cookies = req.getCookies();//键值对
        String value=null;
        //遍历所有cookie 找cookie的key是user的cookie对象
        for (Cookie c : cookies) {
            if("name".equals(c.getName())) {
                value = c.getValue();
                System.out.println("name:"+value);
            }
            if("pwd".equals(c.getName())) {
                value = c.getValue();
                System.out.println("pwd:"+value);
            }
        }
        resp.getWriter().write("<h1>系统提示</h1>");
        resp.getWriter().write("<hr/>");
        resp.getWriter().write("<font color='red'>欢迎,"+value+"登录成功!</font>");

    }
}

中央仓库(jar包下载)

Maven Repository: Central (mvnrepository.com)icon-default.png?t=O83Ahttps://mvnrepository.com/repos/central

 Session

首先创建Session Session在tomcat容器中 有且只有一个

Session默认时间30分钟 在开发中一般都使用Session存储用户登录信息

@WebServlet("/SessionLogin")
public class SessionLogin extends HttpServlet {
    UserService service;

    public SessionLogin() {
        service = new UserServiceImpl();
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        String uname = req.getParameter("uname");
        String pwd = req.getParameter("pwd");
        T_stu stu = service.login(uname, pwd);
        if(stu!=null){
            //创建session
            HttpSession session = req.getSession();
            //将数据以键值对的方式存入
            session.setAttribute("stu", stu);
            resp.sendRedirect("SessionUser");
        }else{
            req.getRequestDispatcher("login.html").forward(req, resp);
        }

    }
}
@WebServlet("/SessionUser")
public class SessionUser extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        //创建session
        HttpSession session = req.getSession();
        //获取数据
        T_stu stu =(T_stu)session.getAttribute("stu");
            resp.getWriter().write("<h1>系统提示</h1>");
            resp.getWriter().write("<hr/>");
            resp.getWriter().write("<h1>登录成功,欢迎"+stu.getUname()+"登录!</h1>");
            resp.getWriter().write("<a href='exit'>退出</a>");
    }
}
@WebServlet("/exit")
public class SessionExit extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        HttpSession session = req.getSession();
        //关闭session
        session.invalidate();
        resp.sendRedirect("login.html");
    }
}

ServletContext(上下文对象携带数据)

生命周期 程序启动到结束

作用域 在项目内

创建

        //第一种创建方式 有就创建 没有就获取
        ServletContext sc1= this.getServletContext();
        //第二种
        ServletContext sc2=req.getSession().getServletContext();
        //第三种
        ServletContext c3=this.getServletConfig().getServletContext();

得到

 ServletContext sc = this.getServletContext();
        String a =(String) sc.getAttribute("a");
        String b =(String) sc.getAttribute("b");
        String c =(String) sc.getAttribute("c");
        resp.getWriter().write("a:"+a+"b:"+b+"c:"+c);

删除

ServletContext sc = this.getServletContext();
        //删除b
        sc.removeAttribute("b");

读取配置文件的配置信息

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <context-param>
        <param-name>name</param-name>
        <param-value>木舟</param-value>
    </context-param>
</web-app>
String city = sc.getInitParameter("city");
        System.out.println(city);

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值