jsp通讯录登录与添加

记录一下Javaee的学习

首先讲一下什么是jsp?

万事先百度。

    JSP全名为Java ServerPages,中文名叫java服务器页面,其根本是一个简化的Servlet设计,它是由Sun Microsystems公司倡导、许多公司参与一起建立的一种动态网页技术标准。JSP技术有点类似ASP技术,它是在传统的网页HTML(标准通用标记语言的子集)文件(*.htm,*.html)中插入Java程序段(Scriptlet)和JSP标记(tag),从而形成JSP文件,后缀名为(*.jsp)。 用JSP开发的Web应用是跨平台的,既能在Linux下运行,也能在其他操作系统上运行。

    其实说白了,就是html+java+js+css。sun公司想把java向网页推广的产品,不过确实很成功。

    讲一下jsp运行的原理,和设计jsp项目的流程。

    login.jsp--->LoginServlet--->LoginService--->jdbcUtil.java--->数据库

    不管是jsp还是servlet,当Tomcat服务器开启的时候,tomcat容器都会去加载jsp,说到底最后还是会被jvm编译成一个class文件,jvm认识的java代码会编译成class,不认识的html代码则会被out打印成字符串,留给浏览器解析。其实说到底还是java。

    列举到登录验证过程,当用户输入账号和密码,点击提交的时候,form表单则将请求以method(post,get),账号密码比较重要的数据,一般用post提交,则不会在地址栏显示。此时地址则会改变,比如login.jsp会变成LoginServlet,Servlet做相应逻辑处理,但是做事的还是service,与dao数据库打交道是service,而servlet只是向service要数据。然后servlet通过数据库里的账号和密码验证后,则通过转发或者重定向,跳转到另一个jsp。

   因此jsp项目的设计流程是:

   表设计--->jdbcUtil-->bean-->service-->jsp-->servlet

一般是先设计数据库,最后再设计servlet,中间大同小异。

废话不多说,直接贴代码。

实现通讯录添加、显示。要求如下:

1) 用户只有登录后才能对通讯录进行添加和查询显示

2) 如果用户没有登录直接访问通讯录维护页面,则提示用户先进行登录,然后点击链接让其跳转至登录页面进行登录。

流程如下:

1) 用户访问登录页面,输入用户名、密码,点击提交,进入servlet验证用户名密码的正确性。

2) 如果验证成功,则跳转至新的jsp页面,显示所有的通讯录信息,并在右上角显示当前登录用户名;如果验证不成功,则跳转至登录页面。

3) 在通讯录显示页面,有一个”添加通讯录”的按钮,点击后进行添加通讯录页面,并进行添加。

4) 退出系统

5) 统计访问人数


环境:myeclipse2014 jdk1.7 mysql tomcat7

mysql数据库表结构

一个用户表(users) 一个用来存储用户好友的表(persons)

users表:

create table users

(

    username varchar(10) primary key,

    password varchar() not null

)

persons表:

create table persons

    username varchar(10) references users(username),

    id int(20) primary key auto_increment,

    name varchar(10) not null,

    tel varchar(30),

    address varchar(20)

)

login.jsp(登录界面)

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%
    String num=(String)application.getAttribute("num");
    if(num==null){
    	//第一次访问
    	application.setAttribute("num", "1");
    }else{
    	int num_ = Integer.parseInt(num);
    	num_ +=1;
    	application.setAttribute("num", String.valueOf(num_));
    }
 %>


  
    
    
    Login
  
  
  
  

网站访问次数,<%=application.getAttribute("num") %>

用户名: 密码:

list.jsp(显示信息界面)

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ page import="com.work.bean.Person" %>



  
    
    list
  
  
  
  

当前在线人数:${userCounts }

正在登录的用户是:<%=request.getAttribute("user") %>

添加通讯录
<% Object getlists=request.getAttribute("personlists"); ArrayList personlists=(ArrayList)getlists; if(personlists!=null) { for(Person p:personlists) { %> <% } } else {%> <% } %>
用户编号 姓名 手机 地址
<%= p.getId() %> <%= p.getName() %> <%= p.getTel() %> <%= p.getAddress() %>
没有数据

add.jsp(通讯录添加好友)

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>



  
    
    
    add
    

  
  
  
  
姓名 手机 地址

AddressServlet(web层)

package com.work.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.work.bean.Person;
import com.work.bean.User;
import com.work.dao.PUtil;
import com.work.service.AddressService;

public class AddressServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		String name=request.getParameter("name");
		String tel=request.getParameter("tel");
		String address=request.getParameter("address");
		String type=request.getParameter("type");
		User user;
		Person p;
		if(!"".equals(username))
		{
			user=new User(username,password);
			request.setAttribute("user", username);
		}
		if(!"".equals(type)&&type!=null&&!"".equals(username)&&"login".equals(type))
		{
			if(AddressService.islogin(username, password))
			{
				user = new User(username, password);
				request.setAttribute("personlists", AddressService.list(username));
				//request.setAttribute("adminname", adminname);
				request.getSession().setAttribute("user", user);
				PUtil.uname=username;
				request.getRequestDispatcher("/list.jsp").forward(request, response);
			}
			else
			{
				request.getRequestDispatcher("/login.jsp").forward(request, response);
			}
			
		}
		if(!"".equals(type)&&type!=null&&!"".equals(username)&&"add".equals(type))
		{
			p=new Person(name, tel, address);
			if(AddressService.add(p,PUtil.getUname()))
			{
				request.setAttribute("user", PUtil.uname);
				request.setAttribute("personlists", AddressService.list(PUtil.uname));
				request.getRequestDispatcher("/list.jsp").forward(request, response);
			}
			else
			{
				request.getRequestDispatcher("/add.jsp").forward(request, response);
			}
		}
		
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}

}

AddressService.java(service层)

package com.work.service;

import java.util.ArrayList;

import com.work.bean.Person;
import com.work.dao.PUtil;

public class AddressService {
	//登录验证
	public static boolean islogin(String username,String pwd)
	{
		return PUtil.islogin(username, pwd);
	}
	//查看通讯录里的好友
	public static ArrayList list(String username)
	{
		return PUtil.list(username);
	}
	//添加通讯录好友
	public static boolean add(Person p,String username)
	{
		return PUtil.add(p, username);
	}
	//添加新用户
	public static boolean addUser(String username,String pwd)
	{
		return PUtil.addUser(username, pwd);
	}
}

SessionListener.java(监听器)

package com.work.listener;

import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class SessionListener implements HttpSessionListener,HttpSessionAttributeListener{
    private int userCounts = 0;//在线人数
	@Override
	public void attributeAdded(HttpSessionBindingEvent be) {
		System.out.println("session添加属性"+be.getName()+"--"+be.getValue());
		
	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent be) {
		System.out.println("session移除属性"+be.getName()+"--"+be.getValue());
		
	}

	@Override
	public void attributeReplaced(HttpSessionBindingEvent be) {
		System.out.println("session替换属性"+be.getName()+"--"+be.getValue());
		
	}

	@Override
	public void sessionCreated(HttpSessionEvent se) {
		userCounts++;
		se.getSession().setAttribute("userCounts", userCounts);
		System.out.println("新的会话创建===="+se.getSession().getId());
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
	    userCounts--;
	    se.getSession().setAttribute("userCounts", userCounts);
	    System.out.println("会话销毁===="+se.getSession().getId());
		
	}

}

Afilter.java(过滤器)

package com.work.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Afilter implements Filter {

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest request=(HttpServletRequest)arg0;
		HttpServletResponse response=(HttpServletResponse)arg1;
		String currentURL = request.getRequestURI();   
        String targetURL = currentURL.substring(currentURL.indexOf("/", 1),  
                currentURL.length());  
        HttpSession session = request.getSession(false);  
        if (!"/login.jsp".equals(targetURL)) {// 判断当前页是否是重定向以后的登录页面页面,如果是就不做session的判断,防止出现死循环  
            if (session == null || session.getAttribute("user") == null) {  
                // *用户登录以后需手动添加session  
                System.out.println("request.getContextPath()="  
                        + request.getContextPath());  
                response.sendRedirect(request.getContextPath() + "/login.jsp");  
                // 如果session为空表示用户没有登录就重定向到login.jsp页面  
                return;  
            }  
        }  
        // 加入filter链继续向下执行  
        arg2.doFilter(request, response);  
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		System.out.println("过滤器已经回收...");
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		System.out.println("过滤器正在过滤...");
	}

}

PUtil.java(dao层)

package com.work.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.work.bean.Person;



public class PUtil {
	static Connection conn;
	static PreparedStatement ps;
	static ResultSet rs;
	static ArrayList plists;
	public static String uname;
	private static final String DBDRIVER="com.mysql.jdbc.Driver";
	private static String USERNAME="root";
	private static String PASSWORD="123456";
	private static String URL="jdbc:mysql://localhost:3306/qq";
	//添加用户
	public static boolean addUser(String username,String pwd)
	{
		try {
			Class.forName(DBDRIVER);
			conn=DriverManager.getConnection(URL, USERNAME, PASSWORD);
			String sql="insert into users values(?,?)";
			ps=conn.prepareStatement(sql);
			ps.setString(1, username);
			ps.setString(2, pwd);
			ps.execute();
			return true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				ps.close();
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return false;
	}
	//验证用户登录
	public static boolean islogin(String username,String pwd)
	{
		try {
			Class.forName(DBDRIVER);
			conn=DriverManager.getConnection(URL, USERNAME, PASSWORD);
			String sql="select * from users where username=? and password=?";
			ps=conn.prepareStatement(sql);
			ps.setString(1, username);
			ps.setString(2, pwd);
			rs=ps.executeQuery();
			while(rs.next())
			{
				if(rs.getString("username").equals(username)&&rs.getString("password").equals(pwd))
				{
					return true;
				}
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				rs.close();
				ps.close();
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return false;
	}
	//查看全部
	public static ArrayList list(String username)
	{
		Person person;
		try {
			Class.forName(DBDRIVER);
			conn=DriverManager.getConnection(URL, USERNAME, PASSWORD);
			String sql="select * from persons where username=?";
			ps=conn.prepareStatement(sql);
			ps.setString(1, username);
			rs=ps.executeQuery();
			plists=new ArrayList<>();
			while(rs.next())
			{
				person=new Person(rs.getInt("id"),rs.getString("name"),rs.getString("tel"), rs.getString("address"));
				plists.add(person);
			}
			return plists;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				rs.close();
				ps.close();
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}
	//添加通讯录的好友
	public static boolean add(Person p,String username)
	{
		try {
			Class.forName(DBDRIVER);
			conn=DriverManager.getConnection(URL, USERNAME, PASSWORD);
			String sql="insert into persons(username,name,tel,address) values(?,?,?,?)";
			ps=conn.prepareStatement(sql);
			ps.setString(1,username);
			ps.setString(2, p.getName());
			ps.setString(3, p.getTel());
			ps.setString(4, p.getAddress());
			ps.execute();
			return true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				ps.close();
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return false;
	}
	public static String getUname() {
		return uname;
	}
	public static void setUname(String uname) {
		PUtil.uname = uname;
	}
	
}

Person.java(bean)

package com.work.bean;

public class Person {
	int id; 
	String name;
	String tel;
	String address;
	public Person() {
	}
	
	public Person(int id,String name, String tel, String address) {
		this.id=id;
		this.name = name;
		this.tel = tel;
		this.address = address;
	}
	public Person(String name, String tel, String address) {
		this.name = name;
		this.tel = tel;
		this.address = address;
	}
	
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getTel() {
		return tel;
	}
	public void setTel(String tel) {
		this.tel = tel;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	
}

User.java(bean)

package com.work.bean;

public class User {
	String username;
	String password;
	public User()
	{
		
	}
	
	public User(String username, String password) {
		super();
		this.username = username;
		this.password = password;
	}

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

web.xml(配置文件有很严格的顺序要求 filter-->servlet-->listener-->session)




    
    
        Afilter
        com.work.filter.Afilter
         
            encoding
            utf-8
        
    
    
        Afilter
        *.jsp
        
    
    
  
   com.work.listener.SessionListener
  
  
    AddressServlet
    com.work.web.AddressServlet
  
  
    AddressServlet
    /AddressServlet
  
  
  
    1
  


还有mysql jdbc jar 可以去mysql官网下载

https://dev.mysql.com/downloads/connector/j/

你可能感兴趣的:(java,web,开发)