java Servlet学习小结

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java Servlet学习小结相关的知识,希望对你有一定的参考价值。

  最近有点小累啊,上课平均一天6小时,再去修一修代码就没什么多的时间了。现在写我最近学习的成果:
想想最近软件工程老师留的题目,我还有一些重要的地方没有想清楚。题目是这样的:生成四则运算的题目,算术题目包括随机生成生成计算数字,随机的运算符,题目可以避免重复,可以定制打印方式、数量,但是要考虑是否带括号。最后一个要求让我有点纠结啊,我的方法是:
考虑到随机生成n个数,可以最多有n-1个左括号的情况,再依次考虑右括号的具体位置,但是还有右括号的位置有些问题:若每次左括号都未生成,默认最后一次有左括号,这样的情况排除。其他情况并不好找到括号。所以我考虑分情况讨论:分为随机的参数不大于5和不大于10两种情况。分开讨论,但是这样到了输入输出还是很麻烦,所以写的我有点疲倦了,但是还是要写完应该在明后天。
前两天把老师布置的JavaEE的作业搞得差不多了,自己主要使用的Servlet写的,同时把重要的知识点罗列了一下,大致如下:
          1.servlet的开发方式有三种:同过servlet接口来开发;继承GenericServlet接口;主要是继承HttpServlet的方式。
          2.开发HttpServlet的时候只需要重写doPost()和doGet()方法实现。get和post方法存在一定的区别。其中通常在doPost()中写this.doGet(res,req);
          3.最后在web.xml中进行部署。注意一一对应和一些细节的地方。(我会在接下来的代码中去体现)。

我按照老师的要求编写一个小的登录系统的实例来加深和巩固学习这个知识。
三个servelet之间的数据传输和数据显示。
  Login.java(登录)->Logincl.java(验证登陆)->wel.java(欢迎界面)最后连接mysql数据库进行验证。
在开始的时候我选用sendRedirect()提交,但是发现在跳转到另一个界面的时候会在跳转的地址后面加上相应的跳转的信息,
用户的信息容易泄漏。后来选用session进行数据的交互。以下:是我学习的笔记。

通过sendRedirect(url?uname=..)传递数据

      1.url 代表要跳转的servlet的url

    2.servelet url名和变量之间有?符号
    3.要传两个以上的值要用“&”分开

    4.传送过程时的中文要改编码方式

而通过使用session来共享数据:
    1.得到session

        Httpsession hs=resquest.getSession(true);
    2.向session添加属性
      hs.setAttibute(String name,Object val);
    3.从session得到某一个属性
      String name=hs.getAttibute
    4.session中删除某个属性
      hs.removeAttibute(String name);
注意:session中的属性存在时间是30min(是间隔时间)
session可以看成一个数据表格 session中的各个属性都要占用服务器内存。

Login.java

  1 package com.ly;
  2 
  3 import java.io.IOException;
  4 import java.io.PrintWriter;
  5 
  6 import javax.servlet.ServletException;
  7 import javax.servlet.http.HttpServlet;
  8 import javax.servlet.http.HttpServletRequest;
  9 import javax.servlet.http.HttpServletResponse;
 10 
 11 public class Login extends HttpServlet {
 12 
 13     /**
 14      * 
 15      */
 16     private static final long serialVersionUID = 1L;
 17 
 18     /**
 19      * Constructor of the object.
 20      */
 21     public Login() {
 22         super();
 23     }
 24 
 25     /**
 26      * Destruction of the servlet. <br>
 27      */
 28     public void destroy() {
 29         super.destroy(); // Just puts "destroy" string in log
 30         // Put your code here
 31     }
 32 
 33     /**
 34      * The doGet method of the servlet. <br>
 35      *
 36      * This method is called when a form has its tag value method equals to get.
 37      * 
 38      * @param request the request send by the client to the server
 39      * @param response the response send by the server to the client
 40      * @throws ServletException if an error occurred
 41      * @throws IOException if an error occurred
 42      */
 43     public void doGet(HttpServletRequest request, HttpServletResponse response)
 44             throws ServletException, IOException {
 45 
 46         //业务逻辑
 47         try{
 48             
 49             //中文乱码
 50             response.setContentType("text/html;charset=gbk");
 51             
 52             PrintWriter pw=response.getWriter();   //字符流用来向jsp界面输出字符串
 53             
 54             //返回登录界面
 55             pw.println("<html>");
 56             pw.println("<body>");
 57             pw.println("<h1>登录界面</h1>");
 58             
 59             //判断用户名是否为空
 60             String info=request.getParameter("info");
 61             if(info!=null)
 62             {
 63                 pw.println("<h1>你的用户名为空!</h1><br>");
 64             }
 65             pw.println("<form action=logincl method=post>");
 66             pw.println("用户名:<input type=text name=usrename><br>");
 67             pw.println("密码: <input type=password name=passwd><br>");
 68             pw.println("<input type=hidden name=sex value=男><br>");
 69             pw.println("<input type=submit value=loging><br>");
 70             pw.println("</form>");
 71             pw.println("</body>");
 72             pw.println("</html>");
 73             
 74         }catch(Exception ex)
 75         {
 76             ex.printStackTrace();
 77         }
 78     }
 79 
 80     /**
 81      * The doPost method of the servlet. <br>
 82      *
 83      * This method is called when a form has its tag value method equals to post.
 84      * 
 85      * @param request the request send by the client to the server
 86      * @param response the response send by the server to the client
 87      * @throws ServletException if an error occurred
 88      * @throws IOException if an error occurred
 89      */
 90     public void doPost(HttpServletRequest request, HttpServletResponse response)
 91             throws ServletException, IOException {
 92 
 93      this.doGet(request, response);
 94     }
 95 
 96     /**
 97      * Initialization of the servlet. <br>
 98      *
 99      * @throws ServletException if an error occurs
100      */
101     public void init() throws ServletException {
102         // Put your code here
103     }
104 
105 }

Logincl.java

  1 package com.ly;
  2 
  3 import java.io.IOException;
  4 
  5 import javax.servlet.ServletException;
  6 import javax.servlet.http.HttpServlet;
  7 import javax.servlet.http.HttpServletRequest;
  8 import javax.servlet.http.HttpServletResponse;
  9 import javax.servlet.http.HttpSession;
 10 import java.sql.*;
 11 
 12 public class Logincl extends HttpServlet {
 13 
 14     /**
 15      * 
 16      */
 17     private static final long serialVersionUID = 1L;
 18 
 19     /**
 20      * Constructor of the object.
 21      */
 22     public Logincl() {
 23         super();
 24     }
 25 
 26     /**
 27      * Destruction of the servlet. <br>
 28      */
 29     public void destroy() {
 30         super.destroy(); // Just puts "destroy" string in log
 31         // Put your code here
 32     }
 33 
 34     /**
 35      * The doGet method of the servlet. <br>
 36      *
 37      * This method is called when a form has its tag value method equals to get.
 38      * 
 39      * @param request the request send by the client to the server
 40      * @param response the response send by the server to the client
 41      * @throws ServletException if an error occurred
 42      * @throws IOException if an error occurred
 43      */
 44     public void doGet(HttpServletRequest request, HttpServletResponse response)
 45             throws ServletException, IOException {
 46 
 47         response.setContentType("text/html;charset=gbk");
 48         
 49         //驱动名
 50         String driver="com.mysql.jdbc.Driver";
 51         //数据库的URL
 52         String url="jdbc:mysql://127.0.0.1:3306/lydb";
 53         //mysql的用户名和密码
 54         String user="root";
 55         String password="123";
 56         
 57         Connection conn=null;
 58         Statement statement=null;
 59         ResultSet rs=null;
 60         //PrintWriter pw=response.getWriter();   //字符流用来向jsp界面输出字符串
 61         try{    
 62             
 63             //接受用户名和密码
 64             String u=request.getParameter("usrename");
 65             String p=request.getParameter("passwd");
 66             String e=request.getParameter("sex");
 67             
 68             //加载驱动
 69             Class.forName(driver);
 70             
 71             //连接数据库
 72              conn=DriverManager.getConnection(url, user, password);
 73             
 74             if(!conn.isClosed())
 75             System.out.println("Successed connection to the Database!");
 76             
 77             //创建statement 来执行SQL语句
 78              statement=conn.createStatement();
 79             //结果集(解决sql漏洞)
 80             String sql="select passwd from users where username=‘"+u+"‘";
 81             rs=statement.executeQuery(sql);
 82             
 83             
 84             
 85             if(rs.next())
 86             {
 87                 //用户存在
 88                 String dbPasswd=rs.getString(1);
 89                 
 90                 if(dbPasswd.equals(p))
 91                 {
 92                     //合法用户 跳转
 93                     
 94                     //将用户名和密码的信息写入session
 95                     //得到session
 96             
 97                     HttpSession hs=request.getSession(true);
 98                     //修改session的存在时间(s为单位)
 99                     hs.setMaxInactiveInterval(20);
100                 hs.setAttribute("uname",u);
101                 hs.setAttribute("uPass", p);
102                 hs.setAttribute("uSex", e);
103                 response.sendRedirect("wel");  //serverlet的URL    
104                 
105                 }
106             }
107             else
108             {
109                 //说明用户名不存在
110                 response.sendRedirect("Login");
111             }
112             
113         }catch(Exception ex)
114         {
115             
116             ex.printStackTrace();
117         }finally
118         {
119             try {
120                 if(rs!=null)
121                 rs.close();
122                 if(statement!=null)
123                 statement.close();
124                 if(conn!=null)
125                 conn.close();
126             } catch (Exception e) {
127                 // TODO Auto-generated catch block
128                 e.printStackTrace();
129             }
130         }
131         String username=null;
132         String passwd=null;
133         String mail=null;
134         String grade=null;
135         String u=request.getParameter("usrename");
136         String    sql="select * from users where username=‘"+u+"‘";
137         try {
138             username=rs.getString("username");
139             System.out.println(username);
140         } catch (SQLException e) {
141             // TODO Auto-generated catch block
142             e.printStackTrace();
143             
144         }
145     }
146 
147     /**
148      * The doPost method of the servlet. <br>
149      *
150      * This method is called when a form has its tag value method equals to post.
151      * 
152      * @param request the request send by the client to the server
153      * @param response the response send by the server to the client
154      * @throws ServletException if an error occurred
155      * @throws IOException if an error occurred
156      */
157     public void doPost(HttpServletRequest request, HttpServletResponse response)
158             throws ServletException, IOException {
159 
160          this.doGet(request, response);
161     }
162 
163     /**
164      * Initialization of the servlet. <br>
165      *
166      * @throws ServletException if an error occurs
167      */
168     public void init() throws ServletException {
169         // Put your code here
170     }
171 
172 }

wel.java

  1 package com.ly;
  2 
  3 import java.io.IOException;
  4 import java.io.PrintWriter;
  5 
  6 import javax.servlet.ServletException;
  7 import javax.servlet.http.HttpServlet;
  8 import javax.servlet.http.HttpServletRequest;
  9 import javax.servlet.http.HttpServletResponse;
 10 import javax.servlet.http.HttpSession;
 11 
 12 public class Wel extends HttpServlet {
 13 
 14     /**
 15      * 
 16      */
 17     private static final long serialVersionUID = 1L;
 18 
 19     /**
 20      * Constructor of the object.
 21      */
 22     public Wel() {
 23         super();
 24     }
 25 
 26     /**
 27      * Destruction of the servlet. <br>
 28      */
 29     public void destroy() {
 30         super.destroy(); // Just puts "destroy" string in log
 31         // Put your code here
 32     }
 33 
 34     /**
 35      * The doGet method of the servlet. <br>
 36      *
 37      * This method is called when a form has its tag value method equals to get.
 38      * 
 39      * @param request the request send by the client to the server
 40      * @param response the response send by the server to the client
 41      * @throws ServletException if an error occurred
 42      * @throws IOException if an error occurred
 43      */
 44     public void doGet(HttpServletRequest request, HttpServletResponse response)
 45             throws ServletException, IOException {
 46   
 47         
 48         //得到session
 49         HttpSession hs=request.getSession(true);
 50         String u=(String) hs.getAttribute("uname");
 51         String p=(String) hs.getAttribute("uPass");
 52         String e=(String) hs.getAttribute("uSex");
 53         if(u==null)
 54         {
 55             
 56             try {
 57                 //PrintWriter pw=response.getWriter(); 
 58                 //非法登陆
 59                 //pw.write("<script>alert(‘你的用户名为空‘);</script>");    
 60                 response.sendRedirect("Login?info=error");    
 61                 return ;
 62             } catch (Exception ex) {
 63                 // TODO: handle exception
 64                 ex.printStackTrace();
 65             }
 66           
 67         }
 68         //得到logincl传递的用户名
 69         //String u=request.getParameter("uname");
 70         
 71         //得到密码
 72         //String p=request.getParameter("uPass");
 73         
 74         //得到性别
 75         //String e=request.getParameter("uSex");
 76     try{
 77     //    response.setContentType("text/html;charset=gbk");    
 78       PrintWriter out = response.getWriter();
 79       out.println("Hello!!!"+u+" password="+p+"Sex="+e);
 80       }
 81   catch(Exception ex)
 82   {
 83       ex.printStackTrace();
 84   }
 85     }
 86 
 87     /**
 88      * The doPost method of the servlet. <br>
 89      *
 90      * This method is called when a form has its tag value method equals to post.
 91      * 
 92      * @param request the request send by the client to the server
 93      * @param response the response send by the server to the client
 94      * @throws ServletException if an error occurred
 95      * @throws IOException if an error occurred
 96      */
 97     public void doPost(HttpServletRequest request, HttpServletResponse response)
 98             throws ServletException, IOException {
 99 
100          this.doGet(request, response);
101     }
102 
103     /**
104      * Initialization of the servlet. <br>
105      *
106      * @throws ServletException if an error occurs
107      */
108     public void init() throws ServletException {
109         // Put your code here
110     }
111 
112 }

web.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app version="2.4" 
 3     xmlns="http://java.sun.com/xml/ns/j2ee" 
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 5     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
 6     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 7   <servlet>
 8     <description>This is the description of my J2EE component</description>
 9     <display-name>This is the display name of my J2EE component</display-name>
10     <servlet-name>Login</servlet-name>
11     <servlet-class>com.ly.Login</servlet-class>
12   </servlet>
13   
14     <servlet-mapping>
15     <servlet-name>Login</servlet-name>
16     <url-pattern>/Login</url-pattern>
17   </servlet-mapping>
18   
19   <servlet>
20     <description>This is the description of my J2EE component</description>
21     <display-name>This is the display name of my J2EE component</display-name>
22     <servlet-name>Logincl</servlet-name>
23     <servlet-class>com.ly.Logincl</servlet-class>
24   </servlet>
25   
26     <servlet-mapping>
27     <servlet-name>Logincl</servlet-name>
28     <url-pattern>/logincl</url-pattern>
29   </servlet-mapping>
30   
31   <servlet>
32     <description>This is the description of my J2EE component</description>
33     <display-name>This is the display name of my J2EE component</display-name>
34     <servlet-name>Wel</servlet-name>
35     <servlet-class>com.ly.Wel</servlet-class>
36   </servlet>
37 
38   <servlet-mapping>
39     <servlet-name>Wel</servlet-name>
40     <url-pattern>/wel</url-pattern>
41   </servlet-mapping>
42   
43   <welcome-file-list>
44     <welcome-file>index.jsp</welcome-file>
45   </welcome-file-list>
46 </web-app>

还有其中设计了数据登录是的注入漏洞的知识(明天补上)

以上是关于java Servlet学习小结的主要内容,如果未能解决你的问题,请参考以下文章

Servlet学习小结

jsp小结

JSP 学习笔记

Java EE - Servlet 小结

Servlet小结

java2小结(草稿)