Servlet学习小结

时间:2023-03-08 19:03:31

最近有点小累啊,上课平均一天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>

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