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语言核心的类.比方:数据库连接.接口定义.输入/输出.网络编程. 学习 ...
随机推荐
- DBlink的创建与删除
创建方式一: create [public] database link link名称 connect to 对方数据库用户identified by 对方数据库用户密码 using '对方数据库i ...
- BZOJ2595: [Wc2008]游览计划(斯坦纳树,状压DP)
Time Limit: 10 Sec Memory Limit: 256 MBSec Special JudgeSubmit: 2030 Solved: 986[Submit][Status][ ...
- JavaWeb基础—JS学习小结
JavaScript是一种运行在浏览器中的解释型的编程语言 推荐:菜鸟教程一.简介js:javascript是基于对象[哪些基本对象呢]和和事件驱动[哪些主要事件呢]的语言,应用在客户端(注意与面向对 ...
- Matlab 装自定义模块
Matlab for Mac 右上角有一个set path选项. 点进去再点击 add with subfolders. 把你下载好的且解压过的工具箱添加进去 然后点save. 重启,就可以直接用了.
- mfc 函数模板
函数模板的使用 一. 函数模板的使用 使用函数模板可以简化 形参个数相同,而类型不同的函数. template<typename T> //可以用class替换typename int m ...
- K近邻算法小结
什么是K近邻? K近邻一种非参数学习的算法,可以用在分类问题上,也可以用在回归问题上. 什么是非参数学习? 一般而言,机器学习算法都有相应的参数要学习,比如线性回归模型中的权重参数和偏置参数,SVM的 ...
- SQL Server 中SELECT INTO 和 INSERT INTO SELECT 两种表复制语句
1.INSERT INTO SELECT语句 语句形式为:Insert into Table2(field1,field2,...) select value1,value2,... from Tab ...
- 使用cJSON库解析JSON
cJSON库的下载 cJSON是一个基于C的JSON解析库,这个库非常简单,只有cJSON.c和cJSON.h两个文件,支持JSON的解析和封装,需要调用时,只需要#include "cJS ...
- 一个导致MGR数据混乱Bug的分析和修复
1.背景 MGR是个好东西,因为他从本质上解决了数据不一致的问题.不光是解决了问题,而且出自名门正派(Oracle的MySQL团队),对品质和后续的维护,我们是可以期待的. 但是在调研的过程中,发现有 ...
- C#,清晨随手写
关于昨晚“猜拳”的博客 大家一定要记得,C#的书写规范是很严格的 很严格很严格很严格 简单的说 下面这样就没办法取值 但是这样就可以取值 插眼,开撸