Index.jsp
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
request.setCharacterEncoding("utf-8");
String username =request.getParameter("username");
String password =request.getParameter("password");
Class.forName("com.mysql.jdbc.Driver");
String url ="jdbc:mysql://localhost:3306/book";
Connection connection = DriverManager.getConnection(url,"root","root");
String sql="select * from user where username= ? and password= ?";
PreparedStatement ps =connection.prepareStatement(sql);
ps.setString(1,username);
ps.setString(2,password);
ResultSet rs = ps.executeQuery();
if (rs.next()){
session.setAttribute("username",username);
out.print("登陆成功");
response.sendRedirect("home.jsp");
}else {
out.print("登陆失败,3秒之后跳转登陆页面");
response.setHeader("refresh","3;url=login.jsp");
}
%>
Login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录页面</title>
<link rel="stylesheet" href="css/bootstrap.css">
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/bootstrap.bundle.js"></script>
<style>
.container{
width: 20%;
height: 20%;
margin-top: 10%;
}
</style>
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<form role="form" method="post" action="index.jsp">
<h3 style="text-align: center">登录</h3>
<div class="form-group">
<label for="exampleInputEmail1">用户名:</label><input type="text" name="username" class="form-control" id="exampleInputEmail1" type="email" />
</div>
<div class="form-group">
<label for="exampleInputPassword1">密码:</label><input type="password" name="password" class="form-control" id="exampleInputPassword1" type="password" />
</div>
<button class="btn btn-default" type="submit">提交</button>
</form>
</div>
</div>
</div>
</body>
</html>
Register.jsp
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.Statement" %>
<jsp:useBean id="user" class="com.user"></jsp:useBean>
<jsp:setProperty name="user" property="*"></jsp:setProperty>
<%
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/book";
Connection connection= DriverManager.getConnection(url,"root","root");
Statement stmt=connection.createStatement();
String sql="insert into user(username,password,gender,age) values('"+user.getUsername()+"','"+user.getPassword()+"',2,11)";
//String sql="update user set age= 40 where id=5";
//String sql="delete from username where id=4";
int count=stmt.executeUpdate(sql);
if(count>0){
out.print("注册成功");
}else{
out.print("注册失败");
}
%>
Add.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
Class.forName("com.mysql.jdbc.Driver");
String url ="jdbc:mysql://localhost:3306/book";
Connection connection = DriverManager.getConnection(url,"root","root");
connection.setAutoCommit(false);
String sql ="insert into user (username,password,gender,age,id ) values (?,?,?,?,?)";
PreparedStatement ps =connection.prepareStatement(sql);
ps.setString(1,user.getUsername());
ps.setString(2,user.getPassword());
ps.setInt(3,user.getGender());
ps.setInt(4,user.getAge());
ps.setInt(5,0);
ps.addBatch();
ps.setString(1,user.getUsername()+"111");
ps.setString(2,user.getPassword()+"111");
ps.setInt(3,user.getGender());
ps.setInt(4,user.getAge());
ps.setInt(5,0);
ps.addBatch();
int[] count ={0};
try{
count =ps.executeBatch();
connection.commit();
}catch (SQLException e){
connection.rollback();
e.printStackTrace();
}
if(count[0] >0){
out.print("添加成功");
}else {
out.print("添加失败");
}
response.setHeader("refresh","3;url=home.jsp");
%>
Delete.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
Class.forName("com.mysql.jdbc.Driver");
String url ="jdbc:mysql://localhost:3306/book";
Connection connection = DriverManager.getConnection(url,"root","root");
String sql ="delete from user where id =?";
PreparedStatement ps =connection.prepareStatement(sql);
int id =Integer.parseInt(request.getParameter("id"));
ps.setInt(1,id);
int count =ps.executeUpdate();
if(count>0){
out.print("删除成功");
}else{
out.print("删除失败");
}
%>
<html>
<head>
<title>Title</title>
</head>
</html>
Edit.jsp
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="com.user" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>编辑页面</title>
<link rel="stylesheet" href="css/bookstrap.css">
<script src="js/jquery.min.js"></script>
<script src="js/bookstrap.js"></script>
<script src="js/bookstrap.bundle.js"></script>
<style>
.container {
width: 50%;
margin-top: 20px;
}
</style>
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<h3 style="text-align: center">编辑页面</h3>
<form method="post" action="update.jsp">
<%
int id=Integer.parseInt(request.getParameter("id"));
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/book";
Connection connection = DriverManager.getConnection(url,"root","root");
String sql ="select * from user where id = ?";
PreparedStatement ps=connection.prepareStatement(sql);
ps.setInt(1,id);
ResultSet rs = ps.executeQuery();
while (rs.next()){
out.print("<input type='hidden' name='id' value="+rs.getString("id")+">");
out.print("用户名:<input type='text'class='form-control' name='username' value="+rs.getString("username")+">");
out.print("密码:<input type='text'class='form-control' name='password' value="+rs.getString("password")+">");
out.print("性别:<input type='text'class='form-control' name='gender' value="+rs.getString("gender")+">");
out.print("年龄:<input type='text'class='form-control' name='age' value="+rs.getString("age")+">");
}
%>
<button type="submit" style="width: 100%" class="btn btn-info">提交</button>
</form>
</div>
</div>
</div>
</body>
</html>
Update.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
Class.forName("com.mysql.jdbc.Driver");
String url ="jdbc:mysql://localhost:3306/book";
Connection connection = DriverManager.getConnection(url,"root","root");
String sql ="update user set username =?,password =?,gender =?,age =? where id =?";
PreparedStatement ps =connection.prepareStatement(sql);
ps.setString(1,user.getUsername());
ps.setString(2,user.getPassword());
ps.setInt(3,user.getGender());
ps.setInt(4,user.getAge());
ps.setInt(5,user.getId());
int count =ps.executeUpdate();
if (count >0){
out.print("修改成功");
}
else{
out.print("修改失败");
}
response.setHeader("refresh","3;url=home.jsp");
%>
3、利用MVC的设计模式实现用户的管理功能
创建模型层
Userbean.java
public class UserBean {
private int id;
private String username;
private String password;
private int gender;
private int age;
private int status;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
loginservlet.Java
package com.servlet;
import com.util.DBUtil;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
* Servlet 注解配置信息
*/
@WebServlet(name = "LoginServlet",value = "/login")
public class LoginServlet extends HttpServlet {
/**
* post请求 会执行doPost方法
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
/**
* get请求 会执行doGet方法
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("servlet 请求");
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
HttpSession session = request.getSession();
if("1".equals(request.getParameter("invalidate")) && session.getAttribute("username") != null){
session.invalidate();
//session.removeAttribute("username");
response.sendRedirect("login.jsp");
}
try {
Connection connection = DBUtil.getConnection();
//sql 模板
String sql = "select * from user where username = ? and password = ?";
//使用PreparedStatement对象执行sql语句
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1,username);
ps.setString(2,password);
ResultSet rs = ps.executeQuery();
//response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
if(rs.next()){
//表示登录成功
session.setAttribute("username",username);
response.sendRedirect("home.jsp");
}else{
//表示登录未成功
out.print("登录失败,3秒之后跳转登录页面...");
response.setHeader("refresh","3;url=login.jsp");
}
//服务端跳转
//request.getRequestDispatcher("home.jsp").forward(request,response);
DBUtil.close(connection,ps,rs);
}catch (Exception e){
e.printStackTrace();
}
}
userservlet.java
package com.servlet;
userservlet.java
package com.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/user")
public class UserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
dbutil.java
package com.util;
dbutil.java
package com.util;
import java.sql.*;
public class DBUtil {
public static Connection getConnection(){
Connection connection = null;
try {
//加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
//建立数据库连接
String url = "jdbc:mysql://localhost:3306/book";
connection = DriverManager.getConnection(url,"root","root");
}catch (Exception e){
e.printStackTrace();
}
return connection;
}
public static void close(Connection connection, PreparedStatement ps, ResultSet rs){
//关闭数据库连接
if(rs != null){
try{
rs.close();
}catch (SQLException e){
e.printStackTrace();
}
}
if(ps != null){
try {
ps.close();
}catch (SQLException e){
e.printStackTrace();
}
}
if(connection != null){
try {
connection.close();
}catch (SQLException e){
e.printStackTrace();
}
}
}
}
charestfilter.java
package com.filter;
charestfilter.java
package com.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CharsetFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse)resp;
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
chain.doFilter(request, response);
}
public void init(FilterConfig config) throws ServletException {
}
}
loginfilter.java
package com.filter;
loginfilter.java
package com.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class LoginFilter implements Filter {
String[] ignores;
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse)resp;
HttpSession session = request.getSession();
String uri = request.getRequestURI();
if(session.getAttribute("username") != null || isIgnore(uri)){
chain.doFilter(request, response);//过滤链
}else{
response.sendRedirect("login.jsp");
}
}
private boolean isIgnore(String uri){
for (String str:ignores) {
if(uri.indexOf(str) != -1){
return true;
}
}
return false;
}
public void init(FilterConfig config) throws ServletException {
String ignore = config.getInitParameter("ignore");
ignores = ignore.split(",");
}
}
usercountlistener.java
package com.listener;
usercountlistener.java
package com.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.*;
@WebListener
public class UserCountListener implements ServletContextListener,HttpSessionListener,HttpSessionAttributeListener {
@Override
public void sessionCreated(HttpSessionEvent se) {
ServletContext application = se.getSession().getServletContext();
int userCount = (int)application.getAttribute("userCount");
userCount++;
application.setAttribute("userCount",userCount);
System.out.println("用户登录,系统当前在线人数:"+userCount);
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
ServletContext application = se.getSession().getServletContext();
int userCount = (int)application.getAttribute("userCount");
if(userCount != 0){
userCount--;
}else{
userCount = 0;
}
application.setAttribute("userCount",userCount);
System.out.println("用户注销,系统当前在线人数:"+userCount);
}
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext application = sce.getServletContext();
application.setAttribute("userCount",0);
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
@Override
public void attributeAdded(HttpSessionBindingEvent se) {
System.out.println("session添加属性");
}
@Override
public void attributeRemoved(HttpSessionBindingEvent se) {
}
@Override
public void attributeReplaced(HttpSessionBindingEvent se) {
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<filter>
<filter-name>charsetFilter</filter-name>
<filter-class>filter.CharsetFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>charsetFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>loginFilter</filter-name>
<filter-class>filter.LoginFilter</filter-class>
<init-param>
<param-name>ignore</param-name>
<param-value>/css,/js,/login.jsp,/login</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>