使用servlet 做一个登录系统

今天终于做出了一个用户功能通过servlet,解决了这几天都没有相同的问题,下面做个总结

首先ajax是异步javascript和xml,这种方式服务器代码嵌套在jsp界面上的,这样对于客户端和服务器开发都不是特别方便,我们可以使用servlet技术做一个简单的客户端与服务器分离登录功能。这个登录界面的具体操作是,如果操作成功就跳转到一个成功的界面,如果用户名和密码错误则提示登录错误停留在原来的界面。具体实现如下:

1、使用eclipse创建一个动态的web工程

2、在/WebContent目录下创建一个登录界面叫做login.jsp,具体代码如下;

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<%
String path = request.getContextPath();  
out.print("path="+path);
String basepath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
out.print("path="+basepath);
%> 
%>
<div>
<style>
#usernamelab, #userpwdlab{
width:70px;
}
#username, #userpwd{
   width:150px;
}
</style>
<form id="loginform" name="loginform" method="post" action="login">
<lab id="usernamelab" name="usernamelab">用户名:</lab>
<input type="text" id="username" name="username"/></br>
<lab id="userpwdlab" name="userpwdlab">密码:</lab>
<input type="password" id="userpwd" name="userpwd" /></br>
<input type="submit" value="登录"/>
</form>
<font color="red" size="2"> ${msg }</font>  
</div>
</body>

</html>

这里需要注意的是 :

(1)id指的是前端属性,而name通常是后端属性服务器端通过name访问前端数据

(2)注意action的值,尤其注意是"login",而不是"/login",因为这里写成"login"请求到项目虚拟目录之下,而“/login”请求到的不是虚拟目录之下而是localhost:8080的根目录之下,这里值得特别注意

3、在webcontent目录下创建一个登录成功的JSP,welcome.jsp代码如下:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<p>登陆成功</p>
</body>

</html>

4、接下来可以就是在java Resources目录之下的src目录创建服务器程序,代码如下:

package login;
import java.io.IOException;  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse; 
import loginDao.userDao;
public class loginServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
// super.doPost(req, resp);
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
String username=req.getParameter("username").trim();
System.out.println("username="+username);
String userpwd=req.getParameter("userpwd").trim();
String pwd=new userDao().FindUsername(username);
if(pwd==null||pwd.equals(""))
{
req.setAttribute("msg", "登录失败");
req.getRequestDispatcher("/login.jsp").forward(req, resp);
}
if(pwd.equals(userpwd)) {
req.setAttribute("msg", "登录成功");
req.getRequestDispatcher("/welcome.jsp").forward(req, resp);

}else {
req.setAttribute("msg", "登录失败");
req.getRequestDispatcher("/login.jsp").forward(req, resp);
}
}

}

这里需要注意的是:

(1)getRequestDispatcher("/login.jsp")里面的“/”不能去掉去掉

(2)super.dopost()这个语句一定要注释或者删掉,如果保留的话在后续的跳转getRequestDispatcher().forward();会报错(Cannot forward after response has beencommitted)

5、这是连接数据库的类

package loginDao;
import java.sql.*;
public class userDao {
public String FindUsername(String username) {
String pwd=null;
Connection con=null;
PreparedStatement prest=null;
ResultSet rs=null;
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/login";
String user="root";
String password="123456";
try {
Class.forName(driver);
con=DriverManager.getConnection(url,user,password);
String sql="select * from tblogin where username=?";
prest=con.prepareStatement(sql);
prest.setString(1, username);
rs=prest.executeQuery();
System.out.println("rs:"+rs);
if(rs==null) {
return null;
}
if(rs.next()) {
return rs.getString("userpwd");
}else {
return null;
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(prest!=null) {
try {
prest.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(con!=null) {
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return pwd;
}
}

6、我们连接的是MYsql数据库,在java里面通常没有连接MYsql的包,因此我们需要导入maysql连接的java包,具体操作如下:(1)通过这个链接(http://dev.mysql.com/downloads/connector/j/)下载  并且解压jar包 ,然后在src目录下建立一个目录不妨叫做jars,将解压的包放到这个目录之下。

(2)选中项目 buildpath--->configure buildpath-->add jars选中刚刚创建的jars目录下的jar包,应用确定

7、xml配置创建一个web.xml,xml是放在webcontent-->WEB-INF的目录之下,这个位置是固定的,配置代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>test</display-name>
  <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
  <servlet-name>login</servlet-name>
  <servlet-class>login.loginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  <servlet-name>login</servlet-name>
  <url-pattern>/login</url-pattern>
  </servlet-mapping>

</web-app>

需要注意的是  servlet-name名字随意,但是要保证上述两个servlet-name一致,servlet-class可以扫描到src目录下的包

,url-pattern这个也是随意的,但是要与之前的那个action保持一致比如,只是注意没有那个“/”而已

8、在mysql创建一个login数据库,然后在数据库里面创建一个tblogin的表包含(username,userpwd)

最终整个程序完成:

值得注意的是在新安装的eclipse很多事没有servers的,这时我们需要配置

help-->Install new software然后在workwith文本框里输入:http://download.eclipse.org/releases/kepler,其中的kepler是eclipse的版本,更换成自己eclipse对应的版本然后加载以后选择Web,XML, Java EE and OSGi Enterprise Development ->JST Server AdaptersExtensions(打勾上该选项)完成安装



猜你喜欢

转载自blog.csdn.net/qq_23335979/article/details/80007399