JAVAWEB 一一 userweb2(升级,servlet版,jstl和el)
Posted PoeticalJustice
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAVAWEB 一一 userweb2(升级,servlet版,jstl和el)相关的知识,希望对你有一定的参考价值。
创建数据库和表
首先,创建一个web项目
然后引入jar包(jstl.jar和standard.jar是jstl和el包,在jsp页面中需要手动加 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 才有效)
创建jsp页面(doXX.jsp的代码全部转移到servlet里面)
创建包
创建接口
实现类
创建servlet
创建fiter过滤器
创建工具类(分页)
详细内容
首先创建一个登陆页面
login.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> <base href="<%=basePath%>"> <title>My JSP \'login.jsp\' starting page</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> <form action="UserServlet" method="post"> 用户名:<input type="text" name="username"/><br/> 密码:<input type="password" name="password3"/><br/> <input type="submit" value="登陆"/> <input type="reset" value="重置"/> </form> </body> </html>
创建要跳转的页面 (充当半个控制器servlet)
dologin.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
<%@page import="com.user.service.impl.UserServiceImpl"%> <%@page import="com.user.service.UserService"%> <%@ 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 > < base href="<%=basePath%>"> < title >My JSP \'dologin.jsp\' starting page</ 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 > <% //dologin相当于一个servlet //设置前台页面参数 编码格式 request.setCharacterEncoding("UTF-8"); //获取前台页面参数 String username = request.getParameter("username"); String password = request.getParameter("password"); // 调用Service 层方法 判断是否成功 UserService service = new UserServiceImpl(); boolean islogin = service.isLogin(username, password); if(islogin){//登录成功 跳转到sucess.jsp页面 否则 跳转到login.jsp //转发 request.getRequestDispatcher("success.jsp").forward(request,response); }else{//登录失败 //重定向 response.sendRedirect("Login.jsp"); } %> </ body > </ html > |
将dologin.jsp的代码复制粘贴到
UserServlet.java
package com.user.servlet.user; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.user.service.UserService; import com.user.service.impl.UserServiceImpl; public class UserServlet extends HttpServlet { /** * Constructor of the object. */ public UserServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置前台页面参数编码格式 request.setCharacterEncoding("UTF-8"); //获取前台页面参数 String username = request.getParameter("username"); String password = request.getParameter("password3"); //调用Sevice层方法 判断是否登陆成功 UserService service = new UserServiceImpl(); boolean isLogin = service.isLogin(username, password); //如果登陆成功则跳转至success.jsp,否则跳转至login.jsp重新登陆 if(isLogin){ //转发 request.getRequestDispatcher("EmpServlet").forward(request, response); }else{ //重定向 response.sendRedirect("jsp/login.jsp"); } } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }
成功跳转
success.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
<%@ 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 > < base href="<%=basePath%>"> < title >My JSP \'success.jsp\' starting page</ 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 > < h1 >登录成功</ h1 >< br > </ body > </ html > |
否则
Login.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
<%@ 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 > < base href="<%=basePath%>"> < title >My JSP \'Login.jsp\' starting page</ 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 > < form action="jsp/dologin.jsp" method="post"> 用户名:< input type="text" name="username"/>< br /> 密码 :< input type="password" name="password"/> < br /> < input type="submit" value="登录"/> < input type="reset" value="重置"/> </ form > </ body > </ html > |
User
entity层
实体类
User.java
package com.user.entity; /** * * @author Administrator * */ public class User { private String username; private String password; private String job; private String email; private int age; 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 String getJob() { return job; } public void setJob(String job) { this.job = job; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public User(String username, String password, String job, String email, int age) { super(); this.username = username; this.password = password; this.job = job; this.email = email; this.age = age; } public User() { super(); } }
service层
接口 UserService.java
package com.user.service; public interface UserService { public boolean isLogin(String username,String password); }
实现类 UserServiceImpl.java
package com.user.service.impl; import com.user.dao.UserDao; import com.user.dao.impl.UserDaoImpl; import com.user.entity.User; import com.user.service.UserService; public class UserServiceImpl implements UserService { public boolean isLogin(String username, String password) { UserDao userDao = new UserDaoImpl(); User user = userDao.getUserByName(username); if(user!=null){ String pwd= user.getPassword(); if(pwd.equals(password)){ return true; } return false; }else{ return false; } } }
dao层
接口 UserDao.java
package com.user.dao; import com.user.entity.User; public interface UserDao { public User getUserByName(String username); }
实现类 UserDaoImpl.java
package com.user.dao.impl; import java.sql.ResultSet; import java.sql.SQLException; import com.user.dao.BaseDao; import com.user.dao.UserDao; import com.user.entity.User; public class UserDaoImpl implements UserDao { BaseDao dao = new BaseDao(); public User getUserByName(String username) { // String sql ="select * from users where username = ?"; Object [] obj = new Object[]{ username}; ResultSet rs = dao.executeQuery(sql, obj); User user =null; try { while(rs.next()){ String password = rs.getString("password"); String job = rs.getString("job"); String email = rs.getString("email"); int age = rs.getInt("age"); user = new User(username, password, job, email, age); } return user; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ dao.closeConnection(); } return null; } }
basedao,java
package com.user.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; /** * 数据库操作的基类 * @author YangKe * */ public class BaseDao { protected Connection conn; protected PreparedStatement ps; protected ResultSet rs; protected String sql; //获取连接 public Connection getConnection(){ try { //获取上下文对象 Context ctx = new InitialContext(); //从上下文中查找数据源 DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/emp"); //从数据源中获取连接 conn = ds.getConnection(); } catch (NamingException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return conn; } //关闭连接释放资源 public void closeConnection(){ if(rs!=null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if(ps!=null){ try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } //通过JDBC来对数据库进行查询操作 public ResultSet executeQuery(String sql, Object[] obj ){ //获取连接 conn = getConnection(); try { //预编译SQL ps= conn.prepareStatement(sql); for (int i = 0; i < obj.length; i++) { //给占位符赋值 ps.setObject(i+1, obj[i]); } //执行SQL语句,获取结果集 rs = ps.executeQuery(); } catch (SQLException e) { e.printStackTrace(); } return rs; } //通过JDBC来对数据库进行更新操作 public boolean executeUpdate(String sql, Object[] obj ){ //获取连接 conn = getConnection(); try { //预编译SQL ps= conn.prepareStatement(sql); for (int i = 0; i < obj.length; i++) { //给占位符赋值 ps.setObject(i+1, obj[i]); } //执行SQL语句,获取该更新语句实际影响的行数 int count = ps.executeUpdate(); //如果行数大于0,表示更新操作成功 if(count>0){ return true; //否则表示更新操作失败 }else{ return false; } } catch (SQLException e) { e.printStackTrace(); } return false; } }
Login.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> <base href="<%=basePath%>"> <title>My JSP \'Login.jsp\' starting page</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> <form action="jsp/dologin.jsp" method="post"> 用户名:<input type="text" name="username"/><br/> 密码 :<input type="password" name="password"/> <br/> <input type="submit" value="登录"/> <input type="reset" value="重置"/> </form> </body> </html>
dologin.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
<%@page import="com.user.service.impl.UserServiceImpl"%> <%@page import="com.user.service.UserService"%> <%@ 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 > < base href="<%=basePath%>"> < title >My JSP \'dologin.jsp\' starting page</ 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 > <% //dologin相当于一个servlet //设置前台页面参数 编码格式 request.setCharacterEncoding("UTF-8"); //获取前台页面参数 String username = request.getParameter("username"); String password = request.getParameter("password"); // 调用Service 层方法 判断是否成功 UserService service = new UserServiceImpl(); boolean islogin = service.isLogin(username, password); if(islogin){//登录成功 跳转到sucess.jsp页面 否则 跳转到login.jsp //转发 request.getRequestDispatcher("success.jsp").forward(request,response); }else{//登录失败 //重定向 response.sendRedirect("Login.jsp"); } %> </ body > </ html > |
将dologin.jsp的代码复制粘贴到
UserServlet.java
package com.user.servlet.user; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.user.service.UserService; import com.user.service.impl.UserServiceImpl; public class UserServlet extends HttpServlet { /** * Constructor of the object. */ public UserServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置前台页面参数编码格式 request.setCharacterEncoding("UTF-8"); //获取前台页面参数 String username = request.getParameter("username"); String password = request.getParameter("password3"); //调用Sevice层方法 判断是否登陆成功 UserService service = new UserServiceImpl(); boolean isLogin = service.isLogin(username, password); //如果登陆成功则跳转至success.jsp,否则跳转至login.jsp重新登陆 if(isLogin){ //转发 request.getRequestDispatcher("EmpServlet").forward(request, response); }else{ //重定向 response.sendRedirect("jsp/login.jsp"); } } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }
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> <base href="<%=basePath%>"> <title>My JSP \'success.jsp\' starting page</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> <h1>登录成功</h1><br> </body> </html>
也可以直接跳转到别的页面比如list.jsp 一个雇员信息列表的页面 但是 这个页面的数据是从数据库查出来的(这样才是动态页面啊)
那么就需要再做一遍上面的步骤 (创建Emp接口和实现类 还有dolist页面 list页面)
Emp
entity层
Emp.java
package com.user.entity; import java.util.Date; public class Emp { private int empno; private String ename; private String job; private int mgr; private Date hiredate; private double sal; private double comm; private int deptno; public Emp() { super(); } public Emp(int empno, String ename, String job, int mgr, Date hiredate, double sal, double comm, int deptno) { super(); this.empno = empno; this.ename = ename; this.job = job; this.mgr = mgr; this.hiredate = hiredate; this.sal = sal; this.comm = comm; this.deptno = deptno; } public int getEmpno() { return empno; } public void setEmpno(int empno) { this.empno = empno; } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } public int getMgr() { return mgr; } public void setMgr(int mgr) { this.mgr = mgr; } public Date getHiredate() { return hiredate; } public void setHiredate(Date hiredate) { this.hiredate = hiredate; } public double getSal() { return sal; } public void setSal(double sal) { this.sal = sal; } public double getComm() { return comm; } public void setComm(double comm) { this.comm = comm; } public int getDeptno() { return deptno; } public void setDeptno(int deptno) { this.deptno = deptno; } }
service层
接口 EmpService.java
/** * */ package com.user.service; import java.util.List; import com.user.entity.Emp; /** * @author YangKe * */ public interface EmpService { public List<Emp> getEmpList(); public Emp getEmpById(int empno); public List<Emp> getEmpByName(String ename); public boolean addEmp(Emp emp); public boolean updateEmp(Emp emp); public boolean delEmpById(int empno); public List<Emp> getEmpList(int pageIndex,int pageSize); public int getTotalCount(); }
实现类 EmpServiceImpl
package com.user.service.impl; import java.util.List; import com.user.dao.EmpDao; import com.user.dao.impl.EmpDaoImpl; import com.user.entity.Emp; import com.user.service.EmpService; public class EmpServiceImpl implements EmpService { EmpDao empdao = new EmpDaoImpl(); public List<Emp> getEmpList() { // TODO Auto-generated method stub return empdao.getEmpList(); } public Emp getEmpById(int empno) { return empdao.getEmpByNo(empno); } public List<Emp> getEmpByName(String ename) { // TODO Auto-generated method stub return null; } public boolean addEmp(Emp emp) { return empdao.addEmp(emp); } public boolean updateEmp(Emp emp) { return empdao.updateEmp(emp); } public boolean delEmpById(int empno) { // TODO Auto-generated method stub return empdao.delEmpById(empno); } public List<Emp> getEmpList(int pageIndex,int pageSize){ return empdao.getEmpList(); } public int getTotalCount(){ return empdao.getTotalCount(); } }
dao层
接口
EmpDao.java
package com.user.dao; import java.util.List; import com.user.entity.Emp; public interface EmpDao { // public List<Emp> getEmpList(); // public Emp getEmpByNo(int empno); // public List<Emp> getEmpByName(String name); // public boolean addEmp(Emp emp); // public boolean updateEmp(Emp emp); // public boolean delEmpById(int empno); //分页 public List<Emp> getEmpList(int pageIndex,int pageSize); public int getTotalCount(); }
实现类
EmpDaoImpl.java
package com.user.dao.impl; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.user.dao.BaseDao; import com.user.dao.EmpDao; import com.user.entity.Emp; import com.user.util.Page; public class EmpDaoImpl implements EmpDao { Page page = new Page(); //创建一个操作数据库的对象 BaseDao basedao = new BaseDao(); public List<Emp> getEmpList() { String sql = "select * from emp "; Object [] obj = new Object[]{}; ResultSet rs = basedao.executeQuery(sql, obj); List<Emp> list = new ArrayList<Emp>(); try { while(rs.next()){ String ename = rs.getString("ename"); int empno =rs.getInt("empno"); String job = rs.getString("job"); int mgr = rs.getInt("mgr"); Date hiredate = rs.getDate("hiredate"); double sal = rs.getDouble("sal"); double comm = rs.getDouble("comm"); int deptno = rs.getInt("deptno"); Emp emp = new Emp(empno, ename, job, mgr, hiredate, sal, comm, deptno); list.add(emp); } return list; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public Emp getEmpByNo(int empno) { String sql = "select * from emp where empno=?"; Object[]obj = new Object[]{empno}; ResultSet rs = basedao.executeQuery(sql, obj); Emp emp =null; try { while(rs.next()){ String ename = rs.getString("ename"); empno =rs.getInt("empno"); String job = rs.getString("job"); int mgr = rs.getInt("mgr"); Date hiredate = rs.getDate("hiredate"); double sal = rs.getDouble("sal"); double comm = rs.getDouble("comm"); int deptno = rs.getInt("deptno"); emp = new Emp(empno, ename, job, mgr, hiredate, sal, comm, deptno); } return emp; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public List<Emp> getEmpByName(String name) { // TODO Auto-generated method stub return null; } public boolean addEmp(Emp emp) { String sql = "insert into emp(empno,ename,job,mgr,sal,comm,deptno) values(?,?,?,?,?,?,?)"; Object[] obj = new Object[] { emp.getEmpno(), emp.getEname(), emp.getJob(), emp.getMgr(), emp.getSal(), emp.getComm(), emp.getDeptno() }; return basedao.executeUpdate(sql, obj); } public boolean updateEmp(Emp emp) { String sql = "update emp set ename=?,job=?,mgr=?,sal=?,comm=?,deptno=? where empno=?"; Object [] obj = new Object[]{ emp.getEname(), emp.getJob(), emp.getMgr(), emp.getSal(), emp.getComm(), emp.getDeptno(),emp.getEmpno()}; return basedao.executeUpdate(sql, obj); } public boolean delEmpById(int empno) { // TODO Auto-generated method stub String sql ="delete from emp where empno =?"; Object[] obj = new Object[]{empno}; return basedao.executeUpdate(sql, obj); } public List<Emp> getEmpList(int pageIndex, int pageSize) { String sql = "select*from(select e.*,rownum rn from (select * from emp)e)where rn>=? and rn<=?"; int startRow = page.getStartRow(pageIndex, pageSize); int endRow = page.getEndRow(pageIndex, pageSize); Object[]obj= new Object[]{startRow,endRow}; ResultSet rs = basedao.executeQuery(sql, obj); Li以上是关于JAVAWEB 一一 userweb2(升级,servlet版,jstl和el)的主要内容,如果未能解决你的问题,请参考以下文章
24. Java SE Java EE JavaME JavaWeb 直接的区别和联系