设置响应头
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;}@Overridepublic 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;@Overridepublic 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();}@Overrideprotected 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,valuereq.getRequestDispatcher("HanderServlet").forward(req, resp);
@WebServlet("/HanderServlet")
public class HanderServlet extends HttpServlet {@Overrideprotected 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();}@Overrideprotected 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 {@Overrideprotected 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对象的数据//获取cookieCookie[] 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)https://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();}@Overrideprotected 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){//创建sessionHttpSession 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 {@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {req.setCharacterEncoding("UTF-8");resp.setContentType("text/html;charset=UTF-8");//创建sessionHttpSession 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 {@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {req.setCharacterEncoding("UTF-8");resp.setContentType("text/html;charset=UTF-8");HttpSession session = req.getSession();//关闭sessionsession.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();//删除bsc.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);