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语言核心的类.比方:数据库连接.接口定义.输入/输出.网络编程. 学习 ...
随机推荐
- STL容器与拷贝构造函数
所有容器提供的都是“value语意”而非“reference语意”.容器内进行元素的安插操作时,内部实施的是拷贝操作,置于容器内.因此STL容器 的每一个元素都必须能够拷贝.---<<C+ ...
- python 标准库简介
操作系统接口 os 模块提供了许多与操作系统交互的函数: >>> >>> import os >>> os.getcwd() # Return t ...
- NGS检测SNP
1,Fastq数据质控 2,Fastq转化成bam,包含头文件 bwa aln ref.fa test_1.fq > test_1.sai bwa aln ref.fa test_2.fq &g ...
- WPF 事件触发命令
方法一使用mvvmlight: xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Int ...
- 如何看数据库是否处在force_logging模式下
SQL> select log_mode, force_logging from v$database; LOG_MODE FOR------------ ---ARCHIVELOG ...
- PostgreSQL的PITR中,对 unfilled wal log 如何处理为好
磨砺技术珠矶,践行数据之道,追求卓越价值 回到上一级页面: PostgreSQL基础知识与基本操作索引页 回到顶级页面:PostgreSQL索引页 通过实验,可以发现,PostgreSQL中使 ...
- 2_C语言中的数据类型 (二)进制
1.1 二进制数.位.字节与字 我们习惯于十进制的数:10,12等 一个位只能表示0,或者1两种状态,简称bit,一个位是一个bit 一个字节为8个二进制,称为8位,简称BYTE,8个比特 ...
- restful framework之频率组件
一.频率简介 为了控制用户对某个url请求的频率,比如,一分钟以内,只能访问三次 二.自定义频率类.自定义频率规则 自定义的逻辑 #(1)取出访问者ip # (2)判断当前ip不在访问字典里,添加进去 ...
- iTerm的安装以及配置Oh My Zsh
iTerm说简单点就是Windows的命令提示符,可能说这个大家感觉没用过,其实也就是人们经常使用CMD,相当于苹果的终端,但是比自带的终端强大多了. 本文就是简单的说一下安装和简单的配置过程. 首先 ...
- selenium无法正常运行 Chrome浏览器,cannot find Chrome binary的问题
有些同学在运行selenium-chrome时会遇到这个问题, System.setProperty("webdriver.chrome.driver","files/c ...