2024-06-25 02:46:10
第一步:web.xml
Java code?
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<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>loginServlet</servlet-name>
<servlet-class>com.servlet.loginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginServlet</servlet-name>
<url-pattern>/loginServlet</url-pattern>
</servlet-mapping>
</web-app>
第二步:数据库
Java code?
/*
SQLyog Ultimate v8.32
MySQL - 5.5.23 : Database - student
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`student` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `student`;
/*Table structure for table `user` */
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user` varchar(50) NOT NULL,
`pwd` varchar(50) NOT NULL,
`name` varchar(50) NOT NULL,
`age` int(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
/*Data for the table `user` */
insert into `user`(`id`,`user`,`pwd`,`name`,`age`) values (1,'zhangsan','123','张三',21);
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
第三步:登录login.jsp
Java code?
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>xx系统</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<div align="center"> <font size=" 2" color="#FF6633">用户登录</font>
</div>
<form id="form1" name="form1" method="post" action="loginServlet">
<table width="357" border="0" align="center">
<tr>
<td width="128">用户名:</td>
<td width="219"><label>
<input name="user" type="text" id="user" />
</label></td>
</tr>
<tr>
<td>密 码:</td>
<td><label>
<input name="pwd" type="password" id="pwd" />
</label></td>
</tr>
<tr>
<td><label>
<input type="submit" name="Submit" value="登录" />
</label></td>
</tr>
</table>
<p> </p>
</form>
</body>
</html>
第四步:success.jsp
Java code
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
${address }</br>
${port }</br>
</body>
</html>
第五步:loginServlet.java
Java code
package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.sql.SQLException;
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 com.dao.Dao;
public class loginServlet extends HttpServlet {
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = new String(request.getParameter("user").getBytes(
"ISO8859_1"), "GBK");
String pwd = new String(request.getParameter("pwd").getBytes(
"ISO8859_1"), "UTF-8");
User user = new User();
user.setUser(name);
user.setPwd(pwd);
Dao dao = new Dao();
boolean isLogin;
try {
isLogin = dao.logoin(user);
if (isLogin) {
InetAddress inetAddress = InetAddress.getLocalHost();
String m = inetAddress.getHostAddress();
int n = request.getRemotePort();
System.out.println(m+"*********"+ n);
HttpSession session = request.getSession();
session.setAttribute("address", m);
session.setAttribute("port", n);
response.sendRedirect("success.jsp");
} else {
response.sendRedirect("index.jsp");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void init() throws ServletException {
}
}
Java code
package com.servlet;
public class User {
private String user;
private String pwd;
private String name;
private int age;
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Java code?
package com.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class GetConnection {
//通过静态方法注册驱动,获得连接
public static Connection getConnection(){
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/student";
Connection con = null;
try {
Class.forName(driver);
try {
con = DriverManager.getConnection(url,"root","123456");
} catch (SQLException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("已获得数据库的连接");
return con;
}
/*public static void main(String args[]){
getConnection();
}*/
}
Java code?
package com.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.servlet.User;
import com.util.GetConnection;
public class Dao {
private Connection conn;
private PreparedStatement pstat;
String sql = "";
/**
*
* 用户登录
*/
public boolean logoin(User user) throws SQLException {
conn = GetConnection.getConnection();
boolean i = false;
sql = "select * from user where user=? and pwd=?";
pstat = conn.prepareStatement(sql);
pstat.setString(1, user.getUser());
pstat.setString(2, user.getPwd());
ResultSet rs1 = (ResultSet) pstat.executeQuery();
if (rs1.next()) {
i = true;
rs1.close();
pstat.close();
} else {
i = false;
rs1.close();
pstat.close();
}
conn.close();
return i;
}
/**
* 用户注册
*/
public void addUser(User user) {
conn = GetConnection.getConnection();
sql = "insert into user values(?,?,?,?)";
try {
pstat = conn.prepareStatement(sql);
pstat.setString(1, user.getUser());
pstat.setString(2, user.getPwd());
pstat.setString(3, user.getName());
pstat.setInt(5, user.getAge());
pstat.executeUpdate();
pstat.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
注意事项:1.数据库用户密码;2.访问地址。
2024-06-25 16:01:12
//连接数据库的,需要导入驱动包
import java.sql.Connection;
import java.sql.DriverManager;
public class BaseDao {
public static final String Driver="com.mysql.jdbc.Driver";
public static final String url="jdbc:mysql://localhost:3306/库名";
public static final String dbname="root";
public static final String pwd="密码";
//获取数据库连接
public static Connection getCon(){
Connection conn=null;
try {
Class.forName(Driver);
conn=
DriverManager.getConnection(url,dbname,pwd);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
//释放资源
public static void close(Connection conn){
try {
if(conn!=null){
conn.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
System.out.println(BaseDao.getCon());
}
}
//登录的server文件
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 entity.User;
public class LoginUser extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
String pwd = request.getParameter("pwd");
try{
UserDao dao=new UserDaoJdbcImpl();
boolean user=dao.logintf(username, pwd);
Connection conn = BaseDao.getCon();
String sql = "select * from t_user";
Statement stmt = conn.createStatement();
java.sql.ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String usernamejdbc=rs.getString("username");
String pwdjdbc=rs.getString("pwd");
if (usernamejdbc.equals(userName)&&pwdjdbc.equals(password)) {
system.out.println("登录成功!");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
//jsp文件
<%@page pageEncoding="utf-8" contentType="text/html; charset = utf-8"%>
<body>
<h1 align="center">
Login
</h1>
<hr />
<form action="login" method="post">
<li>
用户名:š
<input type="text" name="username" id="text" />
</li>
<li>
密 码:š
<input type="password" name="pwd" id="text" //>
</li>
<br/>
<input type="submit" value="登录•" />
</form>
</body>
</html>
//实体类
public class User {
private Integer id;
private String username;
private String pwd;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
这几个文件你自己再整理一下,应该就行了,不过数据库要建有