这学期开J2EE这门课,第一次实验课要求如下:
开发一个Servlet,要求能够获取客户端发送的用户名和密码(客户端可以以GET和POST两种方式发送),并判断用户名和密码是否正确,并最终在浏览器中打印是否验证通过的信息提示。说明:(1)用户名、密码分别是“admin”和“123456”或“张三”和“1234”的时候正确;(2)正确的用户名、密码的值不能编码到Servlet中。
题目比较简单,关键在于第二个要求,方法有两种:一、将正确的用户名、密码存在文件里,当用户发送请求时,读取文件中的数据进行验证;二、将正确的用户名、密码定义到web.xml文件中,当用户发送请求时,Servlet调用web.xml中的参数进行验证。
我选择第二种方法,关键代码如下:
1、在web.xml中定义正确的用户名和密码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1 <context-param> 2 <description>first user</description> 3 <param-name>user1</param-name> 4 <param-value>admin</param-value> 5 </context-param> 6 <context-param> 7 <description>second user</description> 8 <param-name>user2</param-name> 9 <param-value>张三</param-value> 10 </context-param> 11 <context-param> 12 <description>first user password</description> 13 <param-name>password1</param-name> 14 <param-value>123456</param-value> 15 </context-param> 16 <context-param> 17 <description>second user password</description> 18 <param-name>password2</param-name> 19 <param-value>1234</param-value> 20 </context-param>
2、在Servlet中用ServletContext类型的context获取web.xml中定义的参数,在Servlet中的doGet方法中添加如下
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1 ServletContext context = getServletConfig().getServletContext(); 2 String user1 = context.getInitParameter("user1"); 3 String user2 = context.getInitParameter("user2"); 4 String psw1 = context.getInitParameter("password1"); 5 String psw2 = context.getInitParameter("password2"); 6 7 if((username.equals(user1) && password.equals(psw1)) 8 || (username.equals(user2) && password.equals(psw2))){ 9 out.println("用户名:" + username + "<br>"); 10 out.println("密 码:" + password + "<br>"); 11 }else{ 12 out.println("用户名或密码错误,请重新登录!" + "<br>"); 13 }
运行程序,在浏览器地址栏中输入Servlet文件地址和用户名、密码,我的url如下:http://localhost:8080/hello/servlet/LoginServlet?username=admin&password=123456
运行结果:
用户名:admin
密 码:123456