主要功能有: 涉及到的知识点有:
1.用户注册 1.JDBC
2.用户登录 2.Servlet
3.用户列表展示 3.过滤器
4.用户信息修改 4..EL与JSTL表达式
5.用户信息删除
//新建数据库,这一步没什么好说的
CREATE TABLE `user` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(255) NOT NULL,
`pwd` varchar(255) NOT NULL,
`sex` varchar(255) NOT NULL,
`home` varchar(255) NOT NULL,
`info` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES ('3', '123', '123', '123', '123', '123');
INSERT INTO `user` VALUES ('4', '123123', '123123', '男', '北京', '123123');
建立对应的包
新建一个过滤器类 Filter
package com.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;
/**
1.两者都是为了初始化用,但是不推荐在构造函数中对servlet做初始化工作。
2.servlet实例的生命周期是由容器控制的。构造函数中的初始化工作只会在容器构造这个servlet时做一次。
3.servlet的实例是会被多个请求复用,但是构造函数却只能提供一次初始化,所以必须将初始化工作放入init中,由容器来控制。
*/
public class EncodingFilter implements Filter{
public EncodingFilter(){
System.out.println("过滤器构造");
}
public void destroy() {
System.out.println("过滤器销毁");
}
/**
过滤器拦截到响应url的请求后会先执行doFilter()方法中chain.doFilter()之前的代码,
然后执行下一个过滤器或者servelt。紧接着执行chain.doFilter()之后的代码
*/
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("utf-8"); //将编码改为utf-8
response.setContentType("text/html;charset=utf-8");
chain.doFilter(request, response);
}
public void init(FilterConfig arg0) throws ServletException {
System.out.println("过滤器初始化");
}
}
在web.xml进行过滤器的相应配置
<?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">
<display-name></display-name>
<!-- 配置Filter的过滤器名和路径名 -->
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>com.filter.EncodingFilter</filter-class><!--全路径 从根包开始一直到类名-->
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern> <!--*即为过滤所有-->
</filter-mapping>
<welcome-file-list>
<welcome-file>denglu.jsp</welcome-file>
</welcome-file-list>
</web-app>
新建一个DBconn类用来处理对数据库的连接操作(用户名或密码按照自己的数据库更改)
package com.util;
import java.sql.*;
public class DBconn {
static String url = "jdbc:mysql://localhost:3306/test?useunicuee=true& characterEncoding=utf8";
static String username = "root";
static String password = "root";
static Connection conn = null;
static ResultSet rs = null;
static PreparedStatement ps =null;
public static void init(){
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url,username,password);
} catch (Exception e) {
System.out.println("init [SQL驱动程序初始化失败!]");
e.printStackTrace();
}
}
public static int addUpdDel(String sql){
int i = 0;
try {
PreparedStatement ps = conn.prepareStatement(sql);
i = ps.executeUpdate();
} catch (SQLException e) {
System.out.println("sql数据库增删改异常");
e.printStackTrace();
}
return i;
}
public static ResultSet selectSql(String sql){
try {
ps = conn.prepareStatement(sql);
rs = ps.executeQuery(sql);
} catch (SQLException e) {
System.out.println("sql数据库查询异常");
e.printStackTrace();
}
return rs;
}
public static void closeConn(){
try {
conn.close();
} catch (SQLException e) {
System.out.println("sql数据库关闭异常");
e.printStackTrace();
}
}
}
在entity下新建一个User实体类(实体即抽象出来的用户对象,对应数据库中的user表,表中每个字段在实体中为一个属性,也可以理解为一个User对象对应数据库中的user表一条记录)
package com.entity;
public class User {
private int id;
private String name;
private String pwd;
private String sex;
private String home;
private String info;
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 getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getHome() {
return home;
}
public void setHome(String home) {
this.home = home;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
}
package com.dao;
import java.util.List;
import com.entity.User;
public interface UserDao {
public boolean login(String name,String pwd);//登录
public boolean register(User user);//注册
public List<User> getUserAll();//返回用户信息集合
public boolean delete(int id) ;//根据id删除用户
public boolean update(int id,String name, String pwd,String sex, String home,String info) ;//更新用户信息
}
新建UserDaoImpl.java 实现UserDao接口,及未实现的方法 (SQL语句建议在mysql中测试以下,没有问题然后在拿到实现类中使用,可以避免无必要的麻烦)
本例子SQL使用字符串拼接的方式,其实还有一种预加载的方式,有兴趣的童鞋可以参考我的博客,了解预加载的方式处理SQL语句与字符串拼接方式的区别。
package com.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.entity.User;
import com.util.DBconn;
public class UserDaoImpl implements UserDao{
public boolean register(User user) {
boolean flag = false;
DBconn.init();
int i =DBconn.addUpdDel("insert into user(name,pwd,sex,home,info) " +
"values('"+user.getName()+"','"+user.getPwd()+"','"+user.getSex()+"','"+user.getHome()+"','"+user.getInfo()+"')");
if(i>0){
flag = true;
}
DBconn.closeConn();
return flag;
}
public boolean login(String name, String pwd) {
boolean flag = false;
try {
DBconn.init();
ResultSet rs = DBconn.selectSql("select * from user where name='"+name+"' and pwd='"+pwd+"'");
while(rs.next()){
if(rs.getString("name").equals(name) && rs.getString("pwd").equals(pwd)){
flag = true;
}
}
DBconn.closeConn();
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
public List<User> getUserAll() {
List<User> list = new ArrayList<User>();
try {
DBconn.init();
ResultSet rs = DBconn.selectSql("select * from user");
while(rs.next()){
User user = new User();
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setPwd(rs.getString("pwd"));
user.setSex(rs.getString("sex"));
user.setHome(rs.getString("home"));
user.setInfo(rs.getString("info"));
list.add(user);
}
DBconn.closeConn();
return list;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public boolean update(int id,String name, String pwd,String sex, String home,String info) {
boolean flag = false;
DBconn.init();
String sql ="update user set name ='"+name
+"' , pwd ='"+pwd
+"' , sex ='"+sex
+"' , home ='"+home
+"' , info ='"+info+"' where id = "+id;
int i =DBconn.addUpdDel(sql);
if(i>0){
flag = true;
}
DBconn.closeConn();
return flag;
}
public boolean delete(int id) {
boolean flag = false;
DBconn.init();
String sql = "delete from user where id="+id;
int i =DBconn.addUpdDel(sql);
if(i>0){
flag = true;
}
DBconn.closeConn();
return flag;
}
}
在servlet下创建DengluServlet用来实现对用户登录的操作(Servlet有两种方式创建,一种手工创建。另一种程序自动生成。前者自己创建java类,实现Servlet具体内容,然后需要去WEB_INF下的web.xml去配置servlet . 而后者则直接由程序替我们配置好了Servlet)本例子使用第二种方式生成Servlet
package com.servlet;
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.dao.UserDao;
import com.dao.UserDaoImpl;
public class DengluServlet extends HttpServlet { //需要继承HttpServlet 并重写doGet doPost方法
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response); //将信息使用doPost方法执行 对应jsp页面中的form表单中的method
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name"); //得到jsp页面传过来的参数
String pwd = request.getParameter("pwd"); //得到jsp中action传来的参数
UserDao ud = new UserDaoImpl();
//存在用户名密码
/**
request.getAttribute表示从request范围取得设置的属性,
必须要先setAttribute设置属性,才能通过getAttribute来取得,
设置与取得的为Object对象类型 。
*/
if(ud.login(name, pwd)){
request.setAttribute("xiaoxi", "欢迎用户"+name); //向request域中放置信息
request.getRequestDispatcher("/success.jsp").forward(request, response);//转发到成功页面
}else{
response.sendRedirect("index.jsp"); //重定向到首页
}
}
}
request.getRequestDispatcher()有两种跳转:
(1)跳转到一个servlet
request.getRequestDispatcher("想跳转的servlet名").forward(request, response);
(2)跳转到一个页面
request.getRequestDispatcher("文件路径").forward(request, response);
response.sendRedirect("cart.jsp");
response.sendRedirect(url) -- 重定向到指定URL
request.getRequestDispatcher(url).forward(request,response) -- 请求转发到指定URL
1:二者区别:
response.sendRedirect(url)跳转到指定的URL地址,产生一个新的request,所以要传递参数只有在url后加参数,如:
url?id=1.
request.getRequestDispatcher(url).forward(request,response) 是直接将请求转发到指定URL,所以该请求能够直接获得上一个请求的数据,也就是说采用请求转发,request对象始终存在,不会重新创建。而 sendRedirect()会新建request对象,所以上一个request中的数据会丢失。
更具体来说就是这样的:
redirect 会首先发一个response给浏览器, 然后浏览器收到这个response后再发一个request给服务器, 然后服务器发新的response给浏览器. 这时页面收到的request是一个新从浏览器发来的.
forward 发生在服务器内部, 在浏览器完全不知情的情况下发给了浏览器另外一个页面的response. 这时页面收到的request不是从浏览器直接发来了,可能己经用request.setAttribute在request里放了数据.在转到的页面可直接用request.getAttribute获得数据。
//ZhuceServlet.java
package com.servlet;
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.dao.UserDao;
import com.dao.UserDaoImpl;
import com.entity.User;
public class ZhuceServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name"); //获取jsp页面传过来的参数
String pwd = request.getParameter("pwd");
String sex = request.getParameter("sex");
String home = request.getParameter("home");
String info = request.getParameter("info");
User user = new User(); //实例化一个对象,组装属性
user.setName(name);
user.setPwd(pwd);
user.setSex(sex);
user.setHome(home);
user.setInfo(info);
UserDao ud = new UserDaoImpl();
if(ud.register(user)){
request.setAttribute("username", name); //向request域中放置参数
//request.setAttribute("xiaoxi", "注册成功");
request.getRequestDispatcher("/denglu.jsp").forward(request, response); //转发到登录页面
}else{
response.sendRedirect("index.jsp");//重定向到首页
}
}
}
//Searchall.java
package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dao.UserDao;
import com.dao.UserDaoImpl;
import com.entity.User;
public class Searchall extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
UserDao ud = new UserDaoImpl();
List<User> userAll = ud.getUserAll();
request.setAttribute("userAll", userAll);
request.getRequestDispatcher("/showall.jsp").forward(request, response);
}
}
//DeleteServlet.java
package com.servlet;
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.dao.UserDao;
import com.dao.UserDaoImpl;
public class DeleteServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("id");
int userId = Integer.parseInt(id);
UserDao ud = new UserDaoImpl();
if(ud.delete(userId)){
request.setAttribute("xiaoxi", "删除成功");
request.getRequestDispatcher("/Searchall").forward(request, response);
}else{
response.sendRedirect("index.jsp");
}
}
}
//UpdateServlet.java
package com.servlet;
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.dao.UserDao;
import com.dao.UserDaoImpl;
import com.entity.User;
public class UpdateServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("id");
int userId = Integer.parseInt(id);
String name = request.getParameter("name");
String pwd = request.getParameter("pwd");
String sex = request.getParameter("sex");
String home = request.getParameter("home");
String info = request.getParameter("info");
System.out.println("------------------------------------"+userId);
UserDao ud = new UserDaoImpl();
if(ud.update(userId, name, pwd, sex, home, info)){
request.setAttribute("xiaoxi", "更新成功");
request.getRequestDispatcher("/Searchall").forward(request, response);
}else{
response.sendRedirect("index.jsp");
}
}
}
success.jsp 成功页面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'success.jsp' starting page</title>
</head>
<body>
${xiaoxi} <br>
<a href="Searchall">查看所有用户</a>
</body>
</html>
<%! %>里声明的变量和方法都是作为类的属性和方法存在的,<% %>里不能声明方法
而<% %>里声明的变量则是作为_jspService这个方法的内部属性
在ASP.NET中的<%=%>代码块指明了开发人员想要呈现的值(例如<%=”hello”%>就是呈现hello)。<%%>代码块则指出开发人员想要执行的代码,任何在其中呈现的输出都必须是显式地完成(例如<%Response.Write(“hello”);%>)。
所以说二者的区别就是<%=%>只是呈现某个值(比如说字符串呀),或者说用来和某个变量绑定;而<%%>则是执行一段代码(记住代码后要加“;”号),因为是被执行的代码嘛,“;”号是肯定要的。
<a> 标签的 href 属性用于指定超链接目标的 URL。
href 属性的值可以是任何有效文档的相对或绝对 URL,包括片段标识符和 JavaScript 代码段。如果用户选择了 <a> 标签中的内容,那么浏览器会尝试检索并显示 href 属性指定的 URL 所表示的文档,或者执行 JavaScript 表达式、方法和函数的列表。
//index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
//web项目的根路径,就是webContent
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>//) 返回当前链接使用的协议;比如,一般应用返回http;SSL返回https;
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
</head>
<body>
<h1>失敗</h1>
</body>
</html>
这个语句是用来拼装当前网页的相对路径的。
<base href="...">是用来表明当前页面的相对路径所使用的根路径的。
比如,页面内部有一个连接,完整的路径应该是 http://localhost:80/myblog/authen/login.do
其中http://server/是服务器的基本路径,myblog是当前应用程序的名字,那么,我的根路径应该是那么http://localhost:80/myblog/。
有了这个 <base ... >以后,我的页面内容的连接,我不想写全路径,我只要写 authen/login.do就可以了。服务器会自动把 <base ...>指定的路径和页面内的相对路径拼装起来,组成完整路径。
如果没有这个 <base...>,那么我页面的连链接就必须写全路径,否则服务器会找不到。
在使用表单提交数据到服务器的时候有两张方式可共选择,一个是post一个是get。可在<form>中的method属性中指定提交的方式。如:<form action="inputForm"method="get">,如果不指定method属性,则会默认该属性为”get”方式。
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>登录注册页面</title>
</head>
<body >
<form action="DengluServlet" method="post" style="padding-top:-700px;">
用户名:<input type="text" name="name"value=""><br><br>
密码: <input type="password" name="pwd"value=""><br><br>
<input type="submit"value="登录"name="denglu"><input type="reset"value="重置"><br>
</form>
<form action="zhuce.jsp">
<input type="submit"value="新用户注册">
</form>
</body>
</html>
showall.jsp 展现所有用户页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>所有用户页面</title>
</head>
<body>
<h1>${xiaoxi}</h1>
<table width="600" border="1" cellpadding="0" >
<tr>
<th>ID</th>
<th>姓名</th>
<th>性别</th>
<th>密码</th>
<th>家乡</th>
<th>备注</th>
<th>操作</th>
</tr>
<c:forEach var="U" items="${userAll}" >
<form action="UpdateServlet" method="post">
<tr>
<td><input type="text" value="${U.id}" name="id" ></td>
<td><input type="text" value="${U.name}" name="name"></td>
<td><input type="text" value="${U.sex}" name="sex"></td>
<td><input type="text" value="${U.pwd}" name="pwd"></td>
<td><input type="text" value="${U.home}" name="home"></td>
<td><input type="text" value="${U.info}" name="info"></td>
<td><a href="DeleteServlet?id=${U.id}">删除</a> <input type="submit" value="更新"/></td>
</tr>
</form>
</c:forEach>
</table>
</body>
</html>
zhuce.jsp 用户注册页面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'BB.jsp' starting page</title>
</head>
<body >
<form action="ZhuceServlet"method="post" style="padding-top:-700px;">
输入用户名:<input name="name" type="text"><br><br>
输入密码:<input name="pwd" type="password"><br><br>
选择性别:<input type="radio"name="sex"value="男"checked>男
<input type="radio"name="sex"value="女">女<br><br>
选择家乡:
<select name="home">
<option value="上海">上海</option>
<option value="北京" selected>北京</option>
<option value="纽约">纽约</option>
</select><br>
填写个人信息:<br>
<textarea name="info" row="5"cols="30"></textarea><br>
<input type="reset"value="重置"><input type="submit"value="注册">
</form>
</body>
</html>
<?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">
<display-name></display-name>
<filter><!--过滤器配置-->
<filter-name>EncodingFilter</filter-name>
<filter-class>com.filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet><!--servlet类路径配置-->
<servlet-name>DengluServlet</servlet-name>
<servlet-class>com.servlet.DengluServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>ZhuceServlet</servlet-name>
<servlet-class>com.servlet.ZhuceServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>Searchall</servlet-name>
<servlet-class>com.servlet.Searchall</servlet-class>
</servlet>
<servlet>
<servlet-name>DeleteServlet</servlet-name>
<servlet-class>com.servlet.DeleteServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>UpdateServlet</servlet-name>
<servlet-class>com.servlet.UpdateServlet</servlet-class>
</servlet>
<servlet-mapping><!--servlet类映射配置-->
<servlet-name>DengluServlet</servlet-name>
<url-pattern>/DengluServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ZhuceServlet</servlet-name>
<url-pattern>/ZhuceServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Searchall</servlet-name>
<url-pattern>/Searchall</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>DeleteServlet</servlet-name>
<url-pattern>/DeleteServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>UpdateServlet</servlet-name>
<url-pattern>/UpdateServlet</url-pattern>
</servlet-mapping>
<welcome-file-list><!--默认首页地址-->
<welcome-file>denglu.jsp</welcome-file>
</welcome-file-list>
</web-app>
版权声明:未标注转载均为本站原创,转载时请以链接形式注明文章出处。如有侵权、不妥之处,请联系站长删除。敬请谅解!