后台学习2
今天学习的内容比较难懂,主要根据案例来学习。
首先学习了一些,基础的定义和内容。
Respone对象,它能够设置响应信息。
设置响应行:HTTP/1.1 200 ok 状态码:setStatus(int sc)
设置响应头:setHeader(String name,String value)
设置响应体:1、获取输出流:字符流 PrintWrite pw = respone.getWrite() 字节流 ServletOutputStream sos = respone.getOutputStream();
数据由服务器端传到客户端。
package ServletLearning; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.*; import java.io.IOException; import java.io.PrintWriter; //输出字符流数据 @WebServlet(name = "Demo3", value = "/Demo3") public class Demo3 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request,response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //客户端字符的解码方式 request.setCharacterEncoding("UTF-8"); //设置浏览器解码方式 response.setContentType("text/html;charset=utf-8"); PrintWriter pw = response.getWriter(); pw.write("<h2>hello world</h2>"); pw.write("<h2>hello 世界</h2>"); } }
常用请求头 Accept:告诉服务器,客户端接收数据类型 Accept-Language:服务器接收的语言类型(zh en),User-Agent:浏览器的信息 Host:请求服务器ip和端口号
GET请求:
①method = Get
②a标签
③link引入css
④script引入html
⑤img引入图片
⑥iframe在html引入框架
⑦在浏览器地址栏中输入url
POST请求
method=post
请求重定向:客户端向服务端发出请求,服务端给出另一地址,客户端使用新地址访问
package ServletLearning; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.*; import java.io.IOException; /* * 请求重定向 * 客户端给服务器端发送请求,服务器给客户端另一地址去访问 * */ @WebServlet(name = "Demo1", value = "/Demo1") public class Demo1 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("Demo1.............."); //设置状态码 response.setStatus(302); //设置响应头 response.setHeader("location","/Demo2"); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request,response); } }
package ServletLearning; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.*; import java.io.IOException; @WebServlet(name = "Demo2", value = "/Demo2") public class Demo2 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("Demo2-------"); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request,response); } }
接下来通过几个案例来学习Servlet
登陆案例,可以当模板使用,需要提前写一个Druid工具类
package Bean; //实现一个登录功能 public class User { private String username; private String password; public User() { } public User(String username, String password) { this.username = username; this.password = password; } 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; } @Override public String toString() { return "User{" + "username='" + username + '\'' + ", password='" + password + '\'' + '}'; } }
package dao; import Bean.User; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import utils.JDBCUtils; //存放操作数据库的类 public class UserDao { private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource()); public User login(User user){ try { String sql = "select * from user where username = ? and password = ?"; User user1 = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), user.getUsername(), user.getPassword()); return user1; }catch (Exception e){ e.printStackTrace(); return null; } } }
package Servlet; import Bean.User; import dao.UserDao; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.*; import java.io.IOException; @WebServlet(name = "Login", value = "/Login") public class Login extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); String username = request.getParameter("username"); String password = request.getParameter("password"); User user = new User(); user.setUsername(username); user.setPassword(password); UserDao userDao = new UserDao(); User user1 = userDao.login(user); if(user1 != null){ response.getWriter().append("登陆成功,欢迎你"); }else{ response.getWriter().append("登陆失败,用户名或密码错误"); } } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登录</title> </head> <body> <form action="/Login" method="post"> 用户名:<input type="text" name="username"><br> 密码:<input type="password" name="password"><br> <input type="submit" value="登录"> </form> </body> </html>
验证码案例,直接在Servlet中写即可
package ServletLearning; import javax.imageio.ImageIO; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; //实现一个验证码 @WebServlet(name = "CheckCode", value = "/CheckCode") public class CheckCode extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //创建一个对象 int width = 100; int height = 50; BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR); //填充背景颜色 Graphics g = image.getGraphics();//画笔 g.setColor(Color.cyan);//设置画笔颜色 g.fillRect(0,0,width,height); //画边框 g.setColor(Color.black); g.drawRect(0,0,width-1,height-1); //随机码 String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; Random ran = new Random(); for(int i=1;i<=4;i++){ int index = ran.nextInt(str.length()); char ch = str.charAt(index); g.drawString(ch+"",width/5*i,height/2); } //写验证码 // g.drawString("a",20,25); // g.drawString("b",40,25); // g.drawString("c",60,25); // g.drawString("d",80,25); //随机划线 g.setColor(Color.BLUE); for(int i=1;i<10;i++){ int x1 = ran.nextInt(width); int y1 = ran.nextInt(height); int x2 = ran.nextInt(width); int y2 = ran.nextInt(height); g.drawLine(x1,y1,x2,y2); } //图片输出 ImageIO.write(image,"png",response.getOutputStream()); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request,response); } }
如果为了方便测试,可以写一个html界面测试(这个验证码很初级,不建议直接使用)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>注册验证码</title> <script> onload = function (){ //获取图片对象 var img = document.getElementById("checkcode"); //绑定单击事件 img.onclick = function () { var date = new Date().getTime(); img.src = "/CheckCode?"+date } } </script> </head> <body> <img src="/CheckCode" id="checkcode"> </body> </html>
今天学习完之后,感觉后台的学习很枯燥,需要熟练运用各种方法,很费心力,还是需要多加练习。
明天将继续学习后台技术。