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
package com.ly; import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class Login extends HttpServlet { /**
*
*/
private static final long serialVersionUID = 1L; /**
* Constructor of the object.
*/
public Login() {
super();
} /**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
} /**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { //业务逻辑
try{ //中文乱码
response.setContentType("text/html;charset=gbk"); PrintWriter pw=response.getWriter(); //字符流用来向jsp界面输出字符串 //返回登录界面
pw.println("<html>");
pw.println("<body>");
pw.println("<h1>登录界面</h1>"); //判断用户名是否为空
String info=request.getParameter("info");
if(info!=null)
{
pw.println("<h1>你的用户名为空!</h1><br>");
}
pw.println("<form action=logincl method=post>");
pw.println("用户名:<input type=text name=usrename><br>");
pw.println("密码: <input type=password name=passwd><br>");
pw.println("<input type=hidden name=sex value=男><br>");
pw.println("<input type=submit value=loging><br>");
pw.println("</form>");
pw.println("</body>");
pw.println("</html>"); }catch(Exception ex)
{
ex.printStackTrace();
}
} /**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { this.doGet(request, response);
} /**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
} }
Logincl.java
package com.ly; import java.io.IOException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.*; public class Logincl extends HttpServlet { /**
*
*/
private static final long serialVersionUID = 1L; /**
* Constructor of the object.
*/
public Logincl() {
super();
} /**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
} /**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html;charset=gbk"); //驱动名
String driver="com.mysql.jdbc.Driver";
//数据库的URL
String url="jdbc:mysql://127.0.0.1:3306/lydb";
//mysql的用户名和密码
String user="root";
String password="123"; Connection conn=null;
Statement statement=null;
ResultSet rs=null;
//PrintWriter pw=response.getWriter(); //字符流用来向jsp界面输出字符串
try{ //接受用户名和密码
String u=request.getParameter("usrename");
String p=request.getParameter("passwd");
String e=request.getParameter("sex"); //加载驱动
Class.forName(driver); //连接数据库
conn=DriverManager.getConnection(url, user, password); if(!conn.isClosed())
System.out.println("Successed connection to the Database!"); //创建statement 来执行SQL语句
statement=conn.createStatement();
//结果集(解决sql漏洞)
String sql="select passwd from users where username='"+u+"'";
rs=statement.executeQuery(sql); if(rs.next())
{
//用户存在
String dbPasswd=rs.getString(1); if(dbPasswd.equals(p))
{
//合法用户 跳转 //将用户名和密码的信息写入session
//得到session HttpSession hs=request.getSession(true);
//修改session的存在时间(s为单位)
hs.setMaxInactiveInterval(20);
hs.setAttribute("uname",u);
hs.setAttribute("uPass", p);
hs.setAttribute("uSex", e);
response.sendRedirect("wel"); //serverlet的URL }
}
else
{
//说明用户名不存在
response.sendRedirect("Login");
} }catch(Exception ex)
{ ex.printStackTrace();
}finally
{
try {
if(rs!=null)
rs.close();
if(statement!=null)
statement.close();
if(conn!=null)
conn.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String username=null;
String passwd=null;
String mail=null;
String grade=null;
String u=request.getParameter("usrename");
String sql="select * from users where username='"+u+"'";
try {
username=rs.getString("username");
System.out.println(username);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace(); }
} /**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { this.doGet(request, response);
} /**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
} }
wel.java
package com.ly; import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; public class Wel extends HttpServlet { /**
*
*/
private static final long serialVersionUID = 1L; /**
* Constructor of the object.
*/
public Wel() {
super();
} /**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
} /**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { //得到session
HttpSession hs=request.getSession(true);
String u=(String) hs.getAttribute("uname");
String p=(String) hs.getAttribute("uPass");
String e=(String) hs.getAttribute("uSex");
if(u==null)
{ try {
//PrintWriter pw=response.getWriter();
//非法登陆
//pw.write("<script>alert('你的用户名为空');</script>");
response.sendRedirect("Login?info=error");
return ;
} catch (Exception ex) {
// TODO: handle exception
ex.printStackTrace();
} }
//得到logincl传递的用户名
//String u=request.getParameter("uname"); //得到密码
//String p=request.getParameter("uPass"); //得到性别
//String e=request.getParameter("uSex");
try{
// response.setContentType("text/html;charset=gbk");
PrintWriter out = response.getWriter();
out.println("Hello!!!"+u+" password="+p+"Sex="+e);
}
catch(Exception ex)
{
ex.printStackTrace();
}
} /**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { this.doGet(request, response);
} /**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
} }
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>Login</servlet-name>
<servlet-class>com.ly.Login</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping> <servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>Logincl</servlet-name>
<servlet-class>com.ly.Logincl</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>Logincl</servlet-name>
<url-pattern>/logincl</url-pattern>
</servlet-mapping> <servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>Wel</servlet-name>
<servlet-class>com.ly.Wel</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>Wel</servlet-name>
<url-pattern>/wel</url-pattern>
</servlet-mapping> <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
还有其中设计了数据登录是的注入漏洞的知识(明天补上)
Servlet学习小结的更多相关文章
- Servlet 学习小结
一.是什么 是用java编写的服务器端程序.从狭义来讲,servlet是java语言实现的一个接口:广义的servlet是指任何实现了这个servlet接口的类.一般情况下,人们将servlet理解为 ...
- flex学习小结
接触到flex一个多月了,今天做一个学习小结.如果有知识错误或者意见不同的地方.欢迎交流指教. 画外音:先说一下,我是怎么接触到flex布局的.对于正在学习的童鞋们,我建议大家没事可以逛逛网站,看看人 ...
- Python 学习小结
python 学习小结 python 简明教程 1.python 文件 #!/etc/bin/python #coding=utf-8 2.main()函数 if __name__ == '__mai ...
- react学习小结(生命周期- 实例化时期 - 存在期- 销毁时期)
react学习小结 本文是我学习react的阶段性小结,如果看官你是react资深玩家,那么还请就此打住移步他处,如果你想给一些建议和指导,那么还请轻拍~ 目前团队内对react的使用非常普遍,之 ...
- objective-c基础教程——学习小结
objective-c基础教程——学习小结 提纲: 简介 与C语言相比要注意的地方 objective-c高级特性 开发工具介绍(cocoa 工具包的功能,框架,源文件组织:XCode使用介绍) ...
- pthread多线程编程的学习小结
pthread多线程编程的学习小结 pthread 同步3种方法: 1 mutex 2 条件变量 3 读写锁:支持多个线程同时读,或者一个线程写 程序员必上的开发者服务平台 —— DevSt ...
- ExtJs学习笔记之学习小结LoginDemo
ExtJs学习小结LoginDemo 1.示例:(登录界面) <!DOCTYPE html> <html> <head> <meta charset=&quo ...
- JSP&Servlet学习手册
JSP&Servlet学习手册 沙琪玛 书 目录 JSP 指令... 3 书写方式... 3 指令列表... 3 JSP 内置对象... 3 内置对象特点... 3 常用内置对象... 3 o ...
- 点滴的积累---J2SE学习小结
点滴的积累---J2SE学习小结 什么是J2SE J2SE就是Java2的标准版,主要用于桌面应用软件的编程:包括那些构成Java语言核心的类.比方:数据库连接.接口定义.输入/输出.网络编程. 学习 ...
随机推荐
- pH计
pH计 测量原理 pH计主要用于测量液体中的氢离子浓度.准确地说是测量氢离子活性,得出酸性.中性还是碱性的数值,在自来水.河水.饮料.食品.污水.医疗和化工等领域广泛地使用工业用液体分析仪. pH计原 ...
- 【Potplayer】视频播放器
Potplayer——视频播放器
- oracle 事务 数据伪列
在用户进行数据更新操作(DML)事务一定会起作用. 事务的出现会保证数据的完整性.一致性.在整个事务的处理过程之中主要使用两个操作命令: · 事务的提交(COMMIT):是真正的向数据库之中发出更新指 ...
- dategate的用法
菜鸟教程上的说法是这样: delegate() 方法为指定的元素(属于被选元素的子元素)添加一个或多个事件处理程序,并规定当这些事件发生时运行的函数. 使用 delegate() 方法的事件处理程序适 ...
- 转载: 国内的go get无法连接问题的解决
转载自CSDN的文章 https://blog.csdn.net/gongpulin/article/details/80972806 国内的go get问题的解决 go get golang.org ...
- [arc081F]Flip and Rectangles-[黑白染色]
Description 传送门 Solution 有一个神秘的结论..我不知道大佬是怎么场上推出来的. 一个黑白染色图,每次可以任意翻转行或列的颜色,如果每个2*2的子矩阵内黑色格子都是偶数个,则可以 ...
- python基础学习1-面向对象
#!/usr/bin/env python # -*- coding:utf-8 -*- class Foo:#定义类 def mail(self,email,message):#定义类的方法 pri ...
- 11 基于django的图书管理系统 多表
1.需求 作业需求:1.列出图书列表.出版社列表.作者列表2.点击作者,会列出其出版的图书列表3.点击出版社,会列出旗下图书列表4.可以创建.修改.删除 图书.作者.出版社 踩分点:1.满足需求1,2 ...
- [WC2011]最大XOR和路径 线性基
[WC2011]最大XOR和路径 LG传送门 需要充分发掘经过路径的性质:首先注意不一定是简单路径,但由于统计的是异或值,重复走是不会被统计到的,考虑对于任意一条从\(1\)到\(n\)的路径的有效部 ...
- JetBrains全家桶使用攻略
JetBrains全家桶使用攻略 今天狠狠心某宝买了一个key,可以使用15款开发软件,在此进行记录. 全家桶链接:https://www.jetbrains.com/products.html?fr ...