1:用戶登陸界面 login.jspcss
<%@ 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> <center> <form name="myform" method="post" action="/webDemo2/LoginServlet"> 用戶名字: <input type="text" name="username"/><br/><br/> 用戶密碼:<input type="text" name="userpwd"/><br/><br/> <input type="submit" value="登陸"/> <a href="/webDemo2/registerStudent.html">點擊註冊用戶</a> </form> </center> </body> </html>
1.1:點擊登陸,表單信息提交到LoginServlethtml
package com.neusoft.servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.neusoft.dao.StudentDAO; import com.neusoft.dao.StudentPO; public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String username=request.getParameter("username"); String userpwd=request.getParameter("userpwd"); StudentDAO sd = new StudentDAO(); try { StudentPO sp=sd.doLogin(username, userpwd); if(sp==null){ response.sendRedirect("/webDemo2/login.jsp"); }else{ request.setAttribute("student", sp); if(sp.getUserPower()==1) request.getRequestDispatcher("/main.jsp").forward(request, response); else if(sp.getUserPower()==0) request.getRequestDispatcher("/user.jsp").forward(request, response); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
Power爲1表明管理員,Power爲2表明用戶java
分別跳轉到main.jsp,user.jspmysql
1.1.1:管理員登陸web
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@page import="com.neusoft.dao.StudentPO"%> <% //java腳本 //寫java的代碼 String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <% StudentPO stu=(StudentPO)request.getAttribute("student"); %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'main.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> <!-- java表達式 --> 當前網站的根目錄:<%=path %><BR/> 當前網站的全目錄:<%=basePath %><br/> 歡迎<%=stu.getUserName() %>登陸!!!<BR/> <a href="/webDemo2/QueryAllStudent">查看全部人員</a> </body> </html>
跳轉到QueryAllAtudent方法中:sql
package com.neusoft.servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; 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.neusoft.dao.StudentDAO; import com.neusoft.dao.StudentPO; public class QueryAllStudent extends HttpServlet { /** * 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 { StudentDAO sd = new StudentDAO(); try { List<StudentPO> list=sd.queryAllStudent(); request.setAttribute("students", list); request.getRequestDispatcher("/showStudents.jsp").forward(request, response); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
建立數據庫對象,將數據庫中信息放到集合中,封裝對象,提交到showStudents.jsp中數據庫
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@page import="com.neusoft.dao.StudentPO"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <% List<StudentPO> list=(List<StudentPO>)request.getAttribute("students"); %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'showStudents.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> <table border="1" bordercolor="red" align="center"> <tr> <th>用戶ID</th> <th>真實姓名</th> <th>用戶姓名</th> <th>用戶年齡</th> <th>用戶權限</th> </tr> <% for(StudentPO s :list){ %> <tr> <td><%=s.getUserId() %></td> <td><%=s.getRealName() %>></td> <td><%=s.getUserName() %></td> <td><%=s.getUserAge() %></td> <td><%=s.getUserPower() %></td> </tr> <% } %> </table> </body> </html>
1.1.2:企業員工登陸瀏覽器
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@page import="com.neusoft.dao.StudentPO"%> <% //java腳本 //寫java的代碼 String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <% StudentPO stu=(StudentPO)request.getAttribute("student"); %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'main.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> <!-- java表達式 --> 當前網站的根目錄:<%=path %><BR/> 當前網站的全目錄:<%=basePath %><br/> 歡迎<%=stu.getUserName() %>登陸!!!<BR/> <a href="/webDemo2/QueryOnlyOne?userid=<%=stu.getUserId() %>">查看本身信息</a> </body> </html>
向QueryOnlyOne 提交userid 的信息,爲了調用StudentDAO下面的public List<StudentPO> queryStudentById(int id)方法,查詢出當前登陸用戶app
package com.neusoft.servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; 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.neusoft.dao.StudentDAO; import com.neusoft.dao.StudentPO; public class QueryOnlyOne extends HttpServlet { /** * 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 { StudentDAO sd = new StudentDAO(); StudentPO sp = new StudentPO(); String id=request.getParameter("userid"); int userid = Integer.parseInt(id); try { //將對象保存在請求對象中 List<StudentPO> list=sd.queryStudentById(userid); request.setAttribute("students", list); request.getRequestDispatcher("/showStudents.jsp").forward(request, response); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
跳轉到showStudents.jsp中jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@page import="com.neusoft.dao.StudentPO"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <% List<StudentPO> list=(List<StudentPO>)request.getAttribute("students"); %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'showStudents.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> <table border="1" bordercolor="red" align="center"> <tr> <th>用戶ID</th> <th>真實姓名</th> <th>用戶姓名</th> <th>用戶年齡</th> <th>用戶權限</th> </tr> <% for(StudentPO s :list){ %> <tr> <td><%=s.getUserId() %></td> <td><%=s.getRealName() %>></td> <td><%=s.getUserName() %></td> <td><%=s.getUserAge() %></td> <td><%=s.getUserPower() %></td> </tr> <% } %> </table> </body> </html>
1.2:註冊用戶
1.2.1registerStudent.html界面
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>registerStudent.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> </head> <body> <center> <form name="myform" method="post" action="/webDemo2/RegisterServlet"> 用戶ID : <input type="text" name="userid"><br/> 用戶姓名:<input type="text" name="username"/><br/> 真實姓名:<input type="text" name="realname"><br/> 用戶密碼:<input type="text" name="userpwd"><br/> 用戶年齡:<input type="text" name="userage"><br/> <input type="radio" name="power" value="0" checked>員工 <input type="radio" name="power" value="1" checked="true">管理員<br/> <input type="submit" value="註冊"/> </form> </center> </body> </html>
1.2.2跳轉到RegisterServlet.java中
package com.neusoft.servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.neusoft.dao.StudentDAO; public class RegisterServlet extends HttpServlet{ /* * HttpServlet中有兩個方法須要咱們本身重寫 * 須要在web.xml文件中進行註冊 */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8"); //1.接受客戶端數據 //按照客戶端調教數據的name-value的形式來提取數據 String userid=req.getParameter("userid"); String username = req.getParameter("username"); String realname=req.getParameter("realname"); String userpwd=req.getParameter("userpwd"); String userage=req.getParameter("userage"); String userpower=req.getParameter("power"); int id = Integer.parseInt(userid); int age = Integer.parseInt(userage); int power=Integer.parseInt(userpower); //2.使用JDBC,將數據添加到數據庫中 StudentDAO sd = new StudentDAO(); //3.HttpServletResponse對象 //將HTML代碼以數據流的形式響應給客戶端 //客戶端使用IE瀏覽器來解析響應的HTML數據流 //得到一個輸出流對象 // PrintWriter out = resp.getWriter(); // // out.println("<html>"); // out.println("<head>"); // out.println("<meta http-equiv='content-type' content='text/html; charset=UTF-8'>"); // out.println("</head>"); // out.println("<body>"); try { int result=sd.add(id,username,userpwd,age,realname,power); if(result>0){ //1.站內跳轉,請求轉發 //只能轉發網站內部的資源 //轉發的是同一個請求和響應對象 req.getRequestDispatcher("/login.jsp").forward(req, resp); //2.重定向跳轉 //能夠請求外部資源 //因爲是客戶端從新發起的請求,因此請求和響應對象不是同一個 //resp.sendRedirect("/webDemo/success.jsp"); //out.println("添加成功"); }else{ //out.println("添加失敗"); } } catch (SQLException e) { //out.println("添加失敗"); } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } }
註冊成功,從新跳回login.jsp
2.1數據庫代碼
package com.neusoft.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 java.util.List; public class StudentDAO { //連接數據庫 public Connection getConnection(){ Connection conn = null; String driverName="com.mysql.jdbc.Driver"; String connectionString="jdbc:mysql://localhost:3306/test?"+"user=root&password=123456&useUnicode=true&characterEncoding=utf-8"; try{ Class.forName(driverName); conn=DriverManager.getConnection(connectionString); //conn.close(); }catch(ClassNotFoundException e){ e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return conn; } //用戶登陸 public StudentPO doLogin(String username,String userpwd) throws SQLException{ String sql="select * from test where loginname=? and loginpwd=?"; Connection conn = getConnection(); PreparedStatement ps = null; //向數據庫中發送數據集 ResultSet rs = null; //接受返回的數據集對象 StudentPO sp = null; //將傳回的行封裝爲列對象 try { ps=conn.prepareStatement(sql); ps.setString(1, username); ps.setString(2, userpwd); rs = ps.executeQuery(); //遍歷結果集,將數據封裝到集合中 while(rs.next()){ sp = new StudentPO(); sp.setUserName(rs.getString("loginname"));/*********/ sp.setUserPwd(rs.getString("loginpwd")); sp.setuserPower(rs.getInt("power")); sp.setUserId(rs.getInt("id")); sp.setRealName(rs.getString("name")); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ rs.close(); ps.close(); conn.close(); } return sp; } public int executeNonQuery(String sql,Object[]args) throws SQLException{ Connection conn = getConnection(); PreparedStatement ps=null; int result=0; try { ps = conn.prepareStatement(sql); if(args!=null){ for(int i=0;i<args.length;i++){ ps.setObject(i+1, args[i]); } } result=ps.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ ps.close(); conn.close(); } return result; } //用戶註冊 public int add(int id,String name,String loginpwd,int userage,String realname,int userpower) throws SQLException{ String sql="insert into test(id,loginname,loginpwd,age,name,power)" +"values(?,?,?,?,?,?)"; Object[] args={id,name,loginpwd,userage,realname,userpower}; int result=executeNonQuery(sql, args); return result; } //刷新用戶(在哪調用) public int update(int id,String name,String loginpwd,int age) throws SQLException{ String sql="update test set loginname=? ,loginpwd=? ,age=?" +" where id=?"; Object[] args={name,loginpwd,id,age}; int result = executeNonQuery(sql, args); return result; } //刪除用戶信息 public int delete(int id) throws SQLException{ String sql="delete from test where id="+id; int result=executeNonQuery(sql, null); return result; } //封裝數據集 public List<StudentPO> queryAllStudent() throws SQLException{ String sql="select * from test"; Connection conn = getConnection(); PreparedStatement ps = null; ResultSet rs = null; List<StudentPO> list = new ArrayList<StudentPO>(); try { ps=conn.prepareStatement(sql); rs = ps.executeQuery(); //遍歷結果集,將數據封裝到集合中 while(rs.next()){ int userid=rs.getInt("id");//*********** int userage=rs.getInt("age"); int userpower=rs.getInt("power"); String username = rs.getString("loginname"); String userpwd = rs.getString("loginpwd"); String realname=rs.getString("name"); StudentPO sp = new StudentPO(); sp.setUserId(userid); sp.setUserName(username); sp.setRealName(realname); sp.setUserPwd(userpwd); sp.setUserAge(userage); sp.setuserPower(userpower); list.add(sp); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ rs.close(); ps.close(); conn.close(); } return list; } //註冊檢索 public List<StudentPO> queryStudentById(int id) throws SQLException{ String sql="select * from test where id="+id; Connection conn = getConnection(); PreparedStatement ps = null; ResultSet rs = null; List<StudentPO> list = new ArrayList<StudentPO>(); try { ps=conn.prepareStatement(sql); rs = ps.executeQuery(); //遍歷結果集,將數據封裝到集合中 while(rs.next()){ int userid=rs.getInt("id");//**************/ int userage=rs.getInt("age"); int userpower=rs.getInt("power"); String username = rs.getString("loginname"); String userpwd = rs.getString("loginpwd"); String realname=rs.getString("name"); StudentPO sp = new StudentPO(); sp.setUserId(userid); sp.setUserName(username); sp.setUserPwd(userpwd); sp.setUserAge(userage); sp.setRealName(realname); sp.setuserPower(userpower); list.add(sp); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ rs.close(); ps.close(); conn.close(); } return list; } }
package com.neusoft.dao; import java.util.List; public class StudentPO { private int userId; private String userName; private int userAge; private String userPwd; private String realName; private int userPower; public int getUserPower(){ return userPower; } public void setuserPower(int userpower) { this.userPower = userpower; } public String getRealName(){ return realName; } public void setRealName(String realname) { this.realName = realname; } public String getUserPwd() { return userPwd; } public void setUserPwd(String userpwd) { this.userPwd = userpwd; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public int getUserAge() { return userAge; } public void setUserAge(int userAge) { this.userAge = userAge; } }
3.1配置文件
<?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>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>RegisterServlet</servlet-name> <servlet-class>com.neusoft.servlet.RegisterServlet</servlet-class> </servlet> <servlet> <servlet-name>QueryOnlyOne</servlet-name> <servlet-class>com.neusoft.servlet.QueryOnlyOne</servlet-class> </servlet> <servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.neusoft.servlet.LoginServlet</servlet-class> </servlet> <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>QueryAllStudent</servlet-name> <servlet-class>com.neusoft.servlet.QueryAllStudent</servlet-class> </servlet> <servlet-mapping> <servlet-name>QueryOnlyOne</servlet-name> <url-pattern>/QueryOnlyOne</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>RegisterServlet</servlet-name> <url-pattern>/RegisterServlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/LoginServlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>QueryAllStudent</servlet-name> <url-pattern>/QueryAllStudent</url-pattern> </servlet-mapping> </web-app>