summarize
httpServletResponse跟 Request一个是响应一个是请求,获得客户端请求方式 用getMethod 得到的是String类型,
response:属于重定向请求、地址栏URL会发生改变、想服务器发送两次请求 response解决中文乱码:response.setContentType("text/html;charset=utf-8");
request:属于请求转发,成对创建,客户端请求一次,地址栏不改变,真正给资源的是Servlet02 。获取请求转发可以直接写转发的路径,无需写项目目录,因服务器内部行为,这也是与重定向的区别
何时用重定向 何时用请求转发?看需求,如果从servlet01带数据给servlet02 就用请求转发 ,若不带数据用重定向或看地址拦:需要地址栏改变用重定向,不需要改变用请求转发
HttpServletRequest
request代表请求,通过该对象,分别获得HTTP请求的 请求行、请求头、请求体
1.通过request获得请求行
步骤:
获得客户端请求方式:String getMethod()
获取请求资源:
String getRequestURI():返回除去host(域名或者ip)部分的路径
StringBuffer getRequestURL():返回全路径
String getContextPath():获取web应用名称(项目名)
String getQueryString():获取get提交url地址后的参数字符串 例如:username=zhangsan&password=123
新建个项目 WEB06-在建login.jsp 页面--在建一个Servlet
请求行 代码演示
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="/WEB06/LineServlet" method="get"> <input type="text" name="username"><br> <input type="password" name="pwd"><br> <input type="submit" value="提交"> </form> </body> </html> ------------------------------------ package com.oracle.demo01; //通过request获得请求行里面的信息 import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LineServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取请求方式 String method=request.getMethod(); System.out.println("请求方式为"+method); // 获取请求 URI String URI=request.getRequestURI(); System.out.println("URI为"+URI); // 获取获取 URL StringBuffer URL=request.getRequestURL(); System.out.println("URL为"+URL); // 获取WEB应用名称 String name=request.getContextPath(); System.out.println("WEB应用名称为"+name); // 获取get请求后url后的字符串 String query=request.getQueryString(); System.out.println("get请求参数为:"+query); // 获取客户端的IP地址 String ip=request.getRemoteAddr(); System.out.println("ip地址为: "+ip); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
以上代码的方法就是请求行里获取的信息
URI和URL的区别
URI:uniform resource identifier,统一资源标识符,用来唯一的标识一个资源。
URL:uniform resource locator,具体的URI,可以用来标识一个资源,指明了如何locate这个资源
总结:URL是一种具体的URI,它不仅唯一标识资源,而且还提供了定位该资源的信息。URI是抽象概念,可以是绝对,也可以是相对,而URL则必须提供足够的信息来定位,so,是绝对的
request获得请求头
referer头的作用 做防盗链 代码:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <!-- 防盗链 --> <a href="/WEB06/RefereServlet">我就是我</a> </body> </html> --------------------------------
新建个Servlet让jsp指向这个Servlet package com.oracle.demo01; //通过request的 防盗链 import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class RefereServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取refere头 String refere=request.getHeader("Referer"); String content=null; // 判断refere地址以什么开头 必须加上http:// if(refere.startsWith("http://localhost:8080")){ content="真的离婚了!"; }else{ content="你是小偷"; } // 解决response的中文乱码 response.setContentType("text/html;charset=utf-8"); response.getWriter().write(content); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
请求头的作用就是,可做防盗链,当在网页打开一个链接,为了防止打开的这链接会被盗链,可以给地址设置一个地址的开头:看图得知
当我们点开这个链接时,会进入另一个地址,判断这个刚要打开的地址是以谁开头,用.startsWith后面必须+ http://localhost:8080,如果是它开头则是真的,如果不是,则显示你是小偷
通过request获得请求体
以上面参数为例,通过一下方法获得请求参数:
String
getParameter(
String name) ---获得单个值
String[]
getParameterValues(
String name) -----获得多个值
Enumeration
getParameterNames()
代码:
------------->通过getparametermap获取所有参数,得到map集合
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="/WEB06/BodyServlet" method="post"> <input type="text" name="username"> <input type="radio" name="sex" value="woman">女 <input type="radio" name="sex" value="man">男 <br> <input type="checkbox" name="hobby" value="pqq"> 乒乓球 <input type="checkbox" name="hobby" value="pq"> 皮球 <input type="checkbox" name="hobby" value="wq"> 网球 <br> <input type="submit" value="提交"> </form> </body> </html> -------------------------------------------- package com.oracle.demo01; //request获得请求体的方法获得参数 import java.io.IOException; import java.util.Map; import java.util.Set; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.swing.plaf.synth.SynthSeparatorUI; public class BodyServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// post解决中文乱码
request.setCharacterEncoding("utf-8");//在获取参数前修改就是把整个请求体里的乱码
// 获取请求参数
// 1.获取单个值的参数 获取单个的值就parameter方法
String name=request.getParameter("username");//name属性名
// get方式解决乱码: 必须每一个带中文的都来一遍 表单提交:正常人不用get
// name=new String(name.getBytes("ISO-8859-1"),"UTF-8");
String sex=request.getParameter("sex");//获得单选框的值
System.out.println(name+"..."+sex);//打印上面俩名字
// 2.获取多个值
String[] hobbys=request.getParameterValues("hobby");
System.out.println(hobbys);//打印数组
// 3.获取所有请求参数Map
Map<String,String[]> map=request.getParameterMap();
// 遍历
Set<String> set=map.keySet();
for(String str:set){
String[] value=map.get(str);
for(String v:value){
System.out.println(str+"..."+v);
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
解决post提交中文乱码:
解决中文乱码:在获取参数之前+一行代码
request.setCharacterEncoding("utf-8"); 注意:在获取参数以前设置
在最顶上设置中文乱码后,解决整个请求体里所有参数都可接收中文 看加上代码后的效果显示图
解决get提交乱码:parameter = new String(parameter.getbytes("iso8859-1"),"utf-8");
一般人不会用这个 麻烦
pm
request其他功能
1.request 是一个域对象----存储数据的区域对象 Servlet一共三个域对象,功能一样,作用域范围不一样。
方法:
setAttribute(
String name,
Object o)
存值
getAttribute(
String name)
取值
removeAttribute(
String name)
注意:request域的作用范围:一次请求中
request 请求转发 原理图:
重定向:特点:1客户端请求两次 2地址栏改变 举例原理:客户端向servlet01借钱,servlet01回复客户端没钱,并告诉客户端Servlet 02有钱,然后servlet又向02发送请求借钱
请求转发:跟重定向功能一样:客户端发送一次请求,地址栏不变。举例原理:客户端向servlet01请求借钱,servlet01没钱,但他又向servlet02借钱给客户端,实际上是servlet02借给客户端,这种行为是服务器内部行为,servlet01请求servlet02,客户端只发送一次
(1)request完成请求转发
获得请求转发器----path
是转发的地址
RequestDispatcher getRequestDispatcher(
String path)
通过转发器对象转发
requestDispathcer.forward(
ServletRequest request,
ServletResponse response)
package com.oracle.demo02; //request完成请求转发 import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Servlet01 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 请求转发 获得转发器 forward方法
request.getRequestDispatcher("/Servlet02").forward(request, response);//因为是服务器内部行为,无需写/WEB目录,so:是重定向区别
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
} ------------------------------------ package com.oracle.demo02; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Servlet02 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 从request域中取值 get是取值 String name=(String)request.getAttribute("name"); // 解决resonance中文乱码 response.setContentType("text/html;charset=utf-8"); response.getWriter().write("hello sensen..."+name); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
做一个注册web页面
创建 Shop动态项目
导入3个包
创建三层包
register.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head></head> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>会员注册</title> <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" /> <script src="js/jquery-1.11.3.min.js" type="text/javascript"></script> <script src="js/bootstrap.min.js" type="text/javascript"></script> <!-- 引入自定义css文件 style.css --> <link rel="stylesheet" href="css/style.css" type="text/css" /> <style> body { margin-top: 20px; margin: 0 auto; } .carousel-inner .item img { width: 100%; height: 300px; } font { color: #3164af; font-size: 18px; font-weight: normal; padding: 0 10px; } </style> </head> <body> <!-- 引入header.jsp --> <jsp:include page="/header.jsp"></jsp:include> <div class="container" style="width: 100%; background: url('image/regist_bg.jpg');"> <div class="row"> <div class="col-md-2"></div> <div class="col-md-8" style="background: #fff; padding: 40px 80px; margin: 30px; border: 7px solid #ccc;"> <font>会员注册</font>USER REGISTER <form class="form-horizontal" style="margin-top: 5px;" action="/Shop/RegisterServlet" method="post"> <div class="form-group"> <label for="username" class="col-sm-2 control-label">用户名</label> <div class="col-sm-6"> <input type="text" class="form-control" id="username" placeholder="请输入用户名" name="username"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">密码</label> <div class="col-sm-6"> <input type="password" class="form-control" id="inputPassword3" placeholder="请输入密码" name="password"> </div> </div> <div class="form-group"> <label for="confirmpwd" class="col-sm-2 control-label">确认密码</label> <div class="col-sm-6"> <input type="password" class="form-control" id="confirmpwd" placeholder="请输入确认密码"> </div> </div> <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">Email</label> <div class="col-sm-6"> <input type="email" class="form-control" id="inputEmail3" placeholder="Email" name="email"> </div> </div> <div class="form-group"> <label for="usercaption" class="col-sm-2 control-label">姓名</label> <div class="col-sm-6"> <input type="text" class="form-control" id="usercaption" placeholder="请输入姓名" name="name"> </div> </div> <div class="form-group opt"> <label for="inlineRadio1" class="col-sm-2 control-label">性别</label> <div class="col-sm-6"> <label class="radio-inline"> <input type="radio" name="sex" id="sex1" value="male"> 男 </label> <label class="radio-inline"> <input type="radio" name="sex" id="sex2" value="female"> 女 </label> </div> </div> <div class="form-group"> <label for="date" class="col-sm-2 control-label">出生日期</label> <div class="col-sm-6"> <input type="date" class="form-control" name="birthday"> </div> </div> <div class="form-group"> <label for="date" class="col-sm-2 control-label">验证码</label> <div class="col-sm-3"> <input type="text" class="form-control" name="checkCode"> </div> <div class="col-sm-2"> <img src="./image/captcha.jhtml" /> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <input type="submit" width="100" value="注册" name="submit" style="background: url('./images/register.gif') no-repeat scroll 0 0 rgba(0, 0, 0, 0); height: 35px; width: 100px; color: white;"> </div> </div> </form> </div> <div class="col-md-2"></div> </div> </div> <!-- 引入footer.jsp --> <jsp:include page="/footer.jsp"></jsp:include> </body> </html>
RegisterServlet
package com.oracle.web; RegisterServlet import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Map; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.beanutils.BeanUtils; import com.oracle.domain.Users; import com.oracle.service.UserService; public class RegisterServlet extends HttpServlet { private UserService userService=new UserService(); public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 解决request的中文乱码 request.setCharacterEncoding("UTF-8"); // 获取所有请求参数的map集合 Map<String,String[]> map=request.getParameterMap(); // 创建Users对象 Users users=new Users(); // 用BeanUtiles中的方法将map集合中的参数封装到Users对象中 // 原理:根据map中的key跟user对象中的属性名一一映射 try { BeanUtils.populate(users,map); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 封装uid 唯一一个随机产生36位不重复字符串 users.setUid(UUID.randomUUID().toString()); // 调用Service方法 userService.register(users); // 认为注册成功,重定向登录页面 response.sendRedirect(request.getContextPath()+"/login.jsp"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
JDBCUtils
package com.oracle.tools; import java.io.FileInputStream; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; //JDBC工具类 public class JDBCUtils { //获取连接对象的方法 public static Connection getConn(){ Connection conn=null; Properties pro=new Properties(); try { //1.注册驱动 Class.forName("com.mysql.jdbc.Driver"); //2.获取链接对象 String url="jdbc:mysql://localhost:3306/store_v1.0?useUnicode=true&characterEncoding=UTF-8";//0603后面插这句=红娘 String user="root"; String password="123456"; conn=DriverManager.getConnection(url,user,password); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } return conn; } //释放资源1 public static void close(Connection conn,Statement sta){ if(sta!=null){ try { sta.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(conn!=null){ try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } //释放资源2 public static void close(Connection conn,Statement sta,ResultSet rs){ if(rs!=null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if(sta!=null){ try { sta.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
Users
package com.oracle.domain; public class Users { private String uid; private String username; private String password; private String name; private String email; private String telephone; private String birthday; private String sex; private int state; private String code; public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getState() { return state; } public void setState(int state) { this.state = state; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } @Override public String toString() { return "Users [uid=" + uid + ", username=" + username + ", password=" + password + ", name=" + name + ", email=" + email + ", telephone=" + telephone + ", birthday=" + birthday + ", sex=" + sex + ", state=" + state + ", code=" + code + "]"; } }
创建 UsersDao
package com.oracle.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import com.oracle.domain.Users; import com.oracle.tools.JDBCUtils; public class UsersDao { // 登录 需要导包 public void register(Users users) throws SQLException{ // 获得连接对象 Connection conn=JDBCUtils.getConn(); // 获得sql语句 // String sql="insert into users(uid,username,password,email,name,sex,birthday) values(?,?,?,?,?,?,?)"; String sql="insert into users(uid,username," + "password,email,name,sex,birthday) " + "values(?,?,?,?,?,?,?)"; PreparedStatement pst=conn.prepareStatement(sql); pst.setString(1,users.getUid()); pst.setString(2,users.getUsername()); pst.setString(3,users.getPassword()); pst.setString(4,users.getEmail()); pst.setString(5,users.getName()); pst.setString(6,users.getSex()); pst.setString(7,users.getBirthday()); // 执行sql pst.executeUpdate(); // 释放资源 JDBCUtils.close(conn,pst); } }
创建 UserService
package com.oracle.service; import java.sql.SQLException; import com.oracle.dao.UsersDao; import com.oracle.domain.Users; public class UserService { private UsersDao usersDao=new UsersDao(); // 注册 public void register(Users users){ try { usersDao.register(users); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // 登录 public int login(String username,String password){ // 处理异常 int count=0; try { count=usersDao.login(username, password); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return count; } }