JSP动态页面
静态页面:HTML,写什么代码显示什么效果。
动态页面:JSP,在页面中可以嵌入Java代码。
Sevlet在Java程序中嵌入HTML代码,JSP在HTML中嵌入Java代码。
Jsp引擎:将整个Jsp页面解析成一个servlet类。使用out对象通过字符串拼接输出前端代码。
常用标签
- <% %>:用于定义局部变量以及方法的调用。在标签内的代码相当于在一个方法中。
- <%! %>:用于定义全局变量以及定义方法。
- <%= %>:输出变量到页面。
- <%@ %>:导包
请求响应对象
发送给服务器的所有数据都是通过拼接在url后传递的。
-
request(请求):tomcat把当前数据封装成一个HttpServletRequest对象。
获取表单数据:通过request获得的数据都是String
request.getParameter():根据表单的name属性获取数据
request.getParameterValues():获取多选框数据
<% //通过表单的name获取数据 String name = request.getParameter("name"); String pwd = request.getParameter("pwd"); %>
-
response(响应):tomcat把服务器想交给客户端的数据封装成一个HttpServletResponse对象。
<% //response对象通过输出流把html代码输出到客户端 PrintWriter pw = response.getWriter(); if (user != null){ pw.write("登录成功"); pw.write(user.getId()); pw.write(user.getName()); }else{ pw.write("用户名或密码错误"); } pw.close(); %>
请求方式
get:把表单数据全部以键值对的形式显示在地址栏,对地址的长度有限制。
post:不会在地址栏显示表单数据,并且对请求数据的长度没有要求。
跳转页面
在HTTP中有无连接(一次连接与回复后断开连接),无状态(当连接被回复后摧毁request对象)的特征。
在Jsp页面中,一个页面若想使用另一个页面的数据,需要用到请求转发,或重定向时在URL后拼接上数据。
-
请求转发:
/* 如果两个页面需要进行大量数据传递,那么使用请求转发 从a页面请求转发到b页面,地址栏是a页面的链接 两个页面共享request对象 */ request.getRequestDispatcher("index.jsp").forward(request, response);
-
重定向:
/* 客户端在整个过程中发送了两次请求 从a页面重定向到b页面,地址栏是b页面的链接 两个页面不共享request对象。 */ response.sendRedirect("login.jsp"); /response.sendRedirect("login.jsp?error=用户名或者密码错误");
Cookie
Web项目中用于保存用户数据的方式。将数据保存在用户机上。
Cookie:经过用户同意以后在服务器一端产生的数据,然后通过服务器发送给客户端, 并且以文本的形式保存在客户端.然后客户端每次和该服务器产生交互的时候都会把和该服务器相关的cookie发送给服务器
使用步骤:
-
前端表单设置
<form action="isLogin.jsp" method="post"> 用户名:<input type="text" name="name" id="name" value="<%=name%>"><p></p> 密码:<input type="password" name="pwd" id="pwd" value="<%=pwd%>"><p></p> <input type="checkbox" name="isRemember" value="remember" checked="checked">记住用户名密码<p></p> <input type="submit" value="登录"> </form>
-
创建Cookie
//获取表单数据 String isRemember = request.getParameter("isRemember"); /* Cookie默认无法保存中文,如果非要保存中文需要通过转码(加密) URLEncoder:把汉字转码成16进制的编码 URLDecoder把16进制的编码转换成汉字 */ //代表记住用户名密码被选中,创建此cookie前先判断是否登录成功 if ("remember".equals(isRemember)){ Cookie nameCookie=new Cookie("nameC", URLEncoder.encode(name, "utf-8")); Cookie pwdCookie = new Cookie("pwdC",pwd); }
-
设置Cookie有效时间
nameCookie.setMaxAge(10*24*60*60); pwdCookie.setMaxAge(10*24*60*60);
-
设置Cookie保存路径
nameCookie.setPath("/"); pwdCookie.setPath("/");
-
发送给客户端
response.addCookie(nameCookie); response.addCookie(pwdCookie);
-
客户端接收Cookie
<% String name = ""; String pwd = ""; Cookie[] cs = request.getCookies(); if (cs != null){ for (Cookie c : cs) { if ("nameC".equals(c.getName())){ name = URLDecoder.decode(c.getValue(),"utf-8"); } if ("pwdC".equals(c.getName())){ pwd = c.getValue(); } } } %>
四大作用域
-
page:
作用域只在本页面有效,相当于Java中的全局变量。
-
request:
放到request作用域中的数据只在本次请求有效,一般用来页面之间传递数据(前提是页面之间使用请求转发)
拼接在URL后的数据相当于表单数据,使用getParameter()获取这些数据。
-
session(HttpSession):
会话,用于记录用户的登录状态。在一个session作用域中共享所有数据。
在服务器产生session对象,对象产生以后会生成一个sessionID保存在cookie缓存中,表示用户登录成功并开启一个会话,之后该客户端的每次请求都会带上sessionID,只有客户端发送的sessionID和服务器端保存的sessionID一致才表示在一个会话,否则会话结束。
session失效:用户关闭浏览器(缓存清除),客户端注销session(默认30分钟)
session在一定时间内将在服务器留下数据,所有除非必要不往session里面放数据(尤其是大量数据)
-
application(ServletContext):
服务器一旦启动,就给每一个项目生成一个application对象,里面放置了关于web项目的一些配置信息,数据是所有客户端共享的。
<% /******************登录成功后执行********************/ //统计当前在线人数 Integer num = (Integer)application.getAttribute("num"); if(num = null){ num = 1; }else{ num++; } /****使用监听器,当session断开,num--******/ application.setAttribute("num"); %>
内置对象
JSP有九个内置对象(又叫隐含对象),不需要预先声明就可以在脚本代码和表达式中随意使用。
-
request
获取客户端传递到服务器的信息。
常用的方法:
getParameter():获得客户端传递给服务器一个参数的值。
getParameterNames():获得客户端传递给服务器的所有参数的名字。
getParameterValues():获取一个参数的所有值(如checkBox的情况)。
setAttribute(),getAttribute(),removeAttribute():这三个方法主要用于struts框架中,必须在同一个请求中设置的属性才能获得。
getCookies():把个人信息存放到客户端。
setCharacterEncoding()/getCharacterEncoding():设置/获得字符编码。
getContextLength():获得整个网页的长度(长度不确定时返回-1).
getRequestURL():返回当前网页的地址(http://localhost:8080/项目名/具体页面.jsp)。
getRequestURI():返回项目名/具体网页.jsp。
getMethod():获得网页提交的方法,默认为get,还可以设置为post。
getRemoteAddr():获得远程地址。
getRemoteHost():获得远程主机的名称。
getServerPort():端口号(一般默认是8080)。
getServletPath():/具体网页.jsp。
getContextPath():/项目名,获得的是上下文路径。
getHeader(),getHeaders(),getHeaderNames():request.getHeader("Referer");获得来自的网页。
-
response
向客户端浏览器输出信息,对客户的请求进行响应。
-
out
向客户端输出信息,常用的有out.print();或out.println()
-
session
会话对象。每个用户的会话空间是隔离的,互不影响。
-
application
应用对象。Application、Session、request都可以通过setAttribute来设置属性,通过getAttribute来获取属性的值。但是它们的可见范围是不一样的。
Application对象所设置的属性不会过期,它在整个服务器运行过程中都是有效的,直到服务器重启。
Session对象所设置的属性只有在同一个session中可见。
request对象所设置的属性只有在同一次请求之间可见。
通过Application.getRealPath();可以获得其真实路径。
-
page
JSP网页在翻译时会转换成一个servlet(而此servlet是一个类)。
它是JSP网页本身,page对象是当前网页转换后的servlet类的实例。
-
config
一般用来配置指定的JSP参数。
-
exception
用exception对象获取错误信息。
-
pageContext
获取其它八大对象的句柄
pageContext.getOut(); //获得out对象的句柄
pageContext.getRequest(); //获得request对象的句柄
pageContext.getResponse(); //获得response对象的句柄
pageContext.getSession(); //获得session对象的句柄
pageContext.getServletContext();//获得application对象的句柄
pageContext.getServletConfig(); //获得config对象的句柄
pageContext.getException(); //获得exception对象的句柄
pageContext.getPage(); //获得page对象的句柄
图片上传
将图片上传到本地服务器的硬盘中,在将图片的相对路径存储到数据库中,实现图片的上传功能。
简易登录功能实现
<!------------------jsp前端代码-------------------->
<!------------------login.jsp--------------------->
<form action="isLogin.jsp" method="post">
用户名:<input type="text" name="name" id="name"><p></p>
密码:<input type="password" name="pwd" id="pwd"><p></p>
<input type="submit" value="登录">
</form>
<!-----------------isLogin.jsp-------------------->
<!--专门用来判断登录验证的jsp页面-->
<%
//在接收表单数据之前设置请求以及响应的字符编码
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
//获取表单数据
String name = request.getParameter("name");
String pwd = request.getParameter("pwd");
//调用JDBC完成验证
UserService us = new UserServiceImpl();
User user = us.loginUser(name,pwd);
//response对象通过输出流把html代码输出到客户端
PrintWriter pw = response.getWriter();
if (user != null){
pw.write("登录成功");
pw.write(user.getId());
pw.write(user.getName());
}else{
pw.write("用户名或密码错误");
}
pw.close();
%>
/***************后端查询逻辑*******************/
/***************UserService*******************/
/*服务层,jsp页面不能直接调用dao层,必须通过service层调用。先判断用户名密码是否为空,不为空再调用dao类对数据库查询*/
//接口
public interface UserService {
public User loginUser(String name, String password);
}
//实现类
public class UserServiceImpl implements UserService {
private UserDao ud = new UserDaoImpl();
@Override
public User loginUser(String name, String password) {
//如果用户名密码输出不为空再调用dao层对数据库进行查询
if ("".equals(name)||name==null||"".equals(password)||password==null){
return null;
}else{
User user = new User();
user.setName(name);
user.setPassword(password);
user = ud.loginUser(user);
return user;
}
}
}
/******************UserDao*********************/
/*对数据库进行查询*/
public interface UserDao {
User loginUser(User userInfo);
}
public class UserDaoImpl implements UserDao {
private Connection conn;
private PreparedStatement ps;
private ResultSet rs;
@Override
public User loginUser(User user) {
try {
String sql = "select * from users where name = ? and password = ?";
conn = JDBCUtil.init().getConnection();
ps = conn.prepareStatement(sql);
ps.setString(1,user.getName());
ps.setString(2,user.getPassword());
rs = ps.executeQuery();
//如果rs有值,说明登录成功,取出用户的其他数据一起返回
if (rs.next()){
user.setId(rs.getInt("id"));
return user;
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
}
/****************User实体类*****************/
public class User {
private int id;
private String name;
private String password;
//get和set方法
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 getPassword() {return password;}
public void setPassword(String password) {this.password = password;}
}