Use servlet to make a login system

Today, I finally made a user function through servlet, which solved the same problem these days. Let's make a summary

First of all, ajax is asynchronous javascript and xml. In this way, the server code is nested on the jsp interface, which is not particularly convenient for client and server development. We can use servlet technology to make a simple client and server separate login function. The specific operation of this login interface is that if the operation is successful, it will jump to a successful interface, and if the user name and password are wrong, it will prompt the login error to stay in the original interface. The specific implementation is as follows:

1. Use eclipse to create a dynamic web project

2. Create a login interface called login.jsp in the /WebContent directory, the specific code is as follows;

<%@ 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>

The things to note here are:

(1) id refers to the front-end attribute, and name is usually the back-end attribute. The server accesses the front-end data through name

(2) Pay attention to the value of action, especially "login", not "/login", because "login" is written here to request the virtual directory of the project, and "/login" request is not under the virtual directory but It is under the root directory of localhost:8080, which deserves special attention here

3. Create a JSP with a successful login in the webcontent directory. The welcome.jsp code is as follows:

<%@ 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. The next step is to create a server program in the src directory under the java Resources directory. The code is as follows:

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);}}






}

The things to note here are:

(1) The "/" in getRequestDispatcher("/login.jsp") cannot be removed

(2) The statement super.dopost() must be commented or deleted. If it is retained, it will report an error in the subsequent jump getRequestDispatcher().forward(); (Cannot forward after response has been committed)

5. This is the class that connects to the database

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. We are connected to the MYsql database. There is usually no package connected to MYsql in java, so we need to import the java package connected to maysql. The specific operations are as follows: (1) Through this link ( http://dev.mysql.com/ downloads/connector/j/ ) to download and decompress the jar package, then create a directory under the src directory called jars, and put the decompressed package under this directory.

(2) Select the project buildpath--->configure buildpath-->add jars Select the jar package in the jars directory just created, and the application is determined

7, xml configuration Create a web.xml, xml is placed under the directory of webcontent-->WEB-INF, this location is fixed, the configuration code is as follows:

<?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>

It should be noted that the name of the servlet-name is arbitrary, but to ensure that the above two servlet-names are consistent, the servlet-class can scan the packages in the src directory

, url-pattern is also optional, but it should be consistent with the previous action. For example, just note that there is no "/"

8. Create a login database in mysql, and then create a tblogin table in the database containing (username, userpwd)

Finally the whole program is completed:

It is worth noting that there are many things in the newly installed eclipse without servers, then we need to configure

help-->Install new software and then enter in the workwith text box: http://download.eclipse.org/releases/kepler, where kepler is the version of eclipse, replace it with the version corresponding to your own eclipse and then select Web after loading, XML, Java EE and OSGi Enterprise Development ->JST Server AdaptersExtensions (check this option) to complete the installation



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324651549&siteId=291194637