手把手搭建一个完整的javaweb项目

手把手搭建一个完整的javaweb项目

本案例使用Servlet+jsp制作,用MyEclipse和Mysql数据库进行搭建,详细介绍了搭建过程及知识点。

下载地址:http://download.csdn.net/detail/qq_23994787/9904842  点击下载

主要功能有:

1.用户注册

2.用户登录

3.用户列表展示

4.用户信息修改

5.用户信息删除

涉及到的知识点有:   

1.JDBC

2.Servlet

3.过滤器

4..EL与JSTL表达式

1.首先打开mysql数据库 新建一个数据库test,然后生成对应的表结构

[sql] view plain copy
 
  1. CREATE TABLE `user` (  
  2.   `id` int(11) NOT NULL auto_increment,  
  3.   `name` varchar(255) NOT NULL,  
  4.   `pwd` varchar(255) NOT NULL,  
  5.   `sex` varchar(255) NOT NULL,  
  6.   `home` varchar(255) NOT NULL,  
  7.   `info` varchar(255) NOT NULL,  
  8.   PRIMARY KEY  (`id`)  
  9. ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;  
  10.   
  11.   
  12. INSERT INTO `user` VALUES ('3', '123', '123', '123', '123', '123');  
  13. INSERT INTO `user` VALUES ('4', '123123', '123123', '男', '北京', '123123');  

这里使用到了navicat for mysql    这是一种mysql的图形界面化工具,后期可以非常方便的操作数据库。

需要的童鞋 给你们个连接     http://download.csdn.net/download/qq_23994787/10168988

2.然后打开MyEclipse新建一个web项目

3.在webroot下的WEB-INF下的lib中导入mysql的驱动jar包

4.建立对应的包结构 
com.filter   //过滤器 解决中文字符集乱码
com.util     //数据库连接工具类
com.entity   //实体类
com.dao      //数据操作类
com.servlet   //servlet类

5.在filter下新建一个EncodingFilter用来解决中文字符集乱码,它需要实现Filter接口,并重写doFilter函数

[java] view plain copy
 
  1. package com.filter;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import javax.servlet.Filter;  
  6. import javax.servlet.FilterChain;  
  7. import javax.servlet.FilterConfig;  
  8. import javax.servlet.ServletException;  
  9. import javax.servlet.ServletRequest;  
  10. import javax.servlet.ServletResponse;  
  11.   
  12. public class EncodingFilter implements Filter{  
  13.     public EncodingFilter(){  
  14.         System.out.println("过滤器构造");  
  15.     }  
  16.     public void destroy() {  
  17.         System.out.println("过滤器销毁");  
  18.     }  
  19.     public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {  
  20.         request.setCharacterEncoding("utf-8"); //将编码改为utf-8  
  21.         response.setContentType("text/html;charset=utf-8");  
  22.         chain.doFilter(request, response);  
  23.     }  
  24.   
  25.     public void init(FilterConfig arg0) throws ServletException {  
  26.         System.out.println("过滤器初始化");  
  27.     }  
  28.   
  29. }  



6.到web.xml下进行对EncodingFilter相应的配置

[html] view plain copy
 
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5"   
  3.     xmlns="http://java.sun.com/xml/ns/javaee"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  6.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  7.   <display-name></display-name>   
  8.     
  9.   <filter>  
  10.     <filter-name>EncodingFilter</filter-name>  
  11.     <filter-class>com.filter.EncodingFilter</filter-class><!--全路径 从根包开始一直到类名-->  
  12.   </filter>  
  13.   <filter-mapping>  
  14.     <filter-name>EncodingFilter</filter-name>  
  15.     <url-pattern>/*</url-pattern<!--*即为过滤所有-->  
  16.   </filter-mapping>  
  17.     
  18.     
  19.   <welcome-file-list>  
  20.     <welcome-file>denglu.jsp</welcome-file>  
  21.   </welcome-file-list>  
  22. </web-app>  



7.在util下新建一个DBconn类用来处理对数据库的连接操作(用户名或密码按照自己的数据库更改)

[java] view plain copy
 
  1. package com.util;  
  2.   
  3. import java.sql.*;  
  4.   
  5. public class DBconn {  
  6.     static String url = "jdbc:mysql://localhost:3306/test?useunicuee=true& characterEncoding=utf8";   
  7.     static String username = "root";   
  8.     static String password = "root";   
  9.     static Connection  conn = null;  
  10.     static ResultSet rs = null;  
  11.     static PreparedStatement ps =null;  
  12.     public static void init(){  
  13.         try {  
  14.             Class.forName("com.mysql.jdbc.Driver");  
  15.             conn = DriverManager.getConnection(url,username,password);  
  16.         } catch (Exception e) {  
  17.             System.out.println("init [SQL驱动程序初始化失败!]");  
  18.             e.printStackTrace();  
  19.         }  
  20.     }  
  21.     public static int addUpdDel(String sql){  
  22.         int i = 0;  
  23.         try {  
  24.             PreparedStatement ps =  conn.prepareStatement(sql);  
  25.             i =  ps.executeUpdate();  
  26.         } catch (SQLException e) {  
  27.             System.out.println("sql数据库增删改异常");  
  28.             e.printStackTrace();  
  29.         }  
  30.           
  31.         return i;  
  32.     }  
  33.     public static ResultSet selectSql(String sql){  
  34.         try {  
  35.             ps =  conn.prepareStatement(sql);  
  36.             rs =  ps.executeQuery(sql);  
  37.         } catch (SQLException e) {  
  38.             System.out.println("sql数据库查询异常");  
  39.             e.printStackTrace();  
  40.         }  
  41.         return rs;  
  42.     }  
  43.     public static void closeConn(){  
  44.         try {  
  45.             conn.close();  
  46.         } catch (SQLException e) {  
  47.             System.out.println("sql数据库关闭异常");  
  48.             e.printStackTrace();  
  49.         }  
  50.     }  
  51. }  



8.在entity下新建一个User实体类(实体即抽象出来的用户对象,对应数据库中的user表,表中每个字段在实体中为一个属性,也可以理解为一个User对象对应数据库中的user表一条记录)

[java] view plain copy
 
  1. package com.entity;  
  2.   
  3. public class User {  
  4.     private int id;  
  5.     private String name;  
  6.     private String pwd;  
  7.     private String sex;  
  8.     private String home;  
  9.     private String info;  
  10.     public int getId() {  
  11.         return id;  
  12.     }  
  13.     public void setId(int id) {  
  14.         this.id = id;  
  15.     }  
  16.     public String getName() {  
  17.         return name;  
  18.     }  
  19.     public void setName(String name) {  
  20.         this.name = name;  
  21.     }  
  22.     public String getPwd() {  
  23.         return pwd;  
  24.     }  
  25.     public void setPwd(String pwd) {  
  26.         this.pwd = pwd;  
  27.     }  
  28.     public String getSex() {  
  29.         return sex;  
  30.     }  
  31.     public void setSex(String sex) {  
  32.         this.sex = sex;  
  33.     }  
  34.     public String getHome() {  
  35.         return home;  
  36.     }  
  37.     public void setHome(String home) {  
  38.         this.home = home;  
  39.     }  
  40.     public String getInfo() {  
  41.         return info;  
  42.     }  
  43.     public void setInfo(String info) {  
  44.         this.info = info;  
  45.     }  
  46.       
  47. }  



9.在dao下新建一个UserDao接口  以及对应的方法实现类(使用接口类是为了规范开发)

UserDao.java

[java] view plain copy
 
  1. package com.dao;  
  2.   
  3. import java.util.List;  
  4.   
  5. import com.entity.User;  
  6.   
  7. public interface UserDao {  
  8.     public boolean login(String name,String pwd);//登录  
  9.     public boolean register(User user);//注册  
  10.     public List<User> getUserAll();//返回用户信息集合  
  11.     public boolean delete(int id) ;//根据id删除用户  
  12.     public boolean update(int id,String name, String pwd,String sex, String home,String info) ;//更新用户信息  
  13. }  

新建UserDaoImpl.java     实现UserDao接口,及未实现的方法     (SQL语句建议在mysql中测试以下,没有问题然后在拿到实现类中使用,可以避免无必要的麻烦)

本例子SQL使用字符串拼接的方式,其实还有一种预加载的方式,有兴趣的童鞋可以参考我的博客,了解预加载的方式处理SQL语句与字符串拼接方式的区别。

[java] view plain copy
 
  1. package com.dao;  
  2.   
  3. import java.sql.ResultSet;  
  4. import java.sql.SQLException;  
  5. import java.util.ArrayList;  
  6. import java.util.List;  
  7.   
  8. import com.entity.User;  
  9. import com.util.DBconn;  
  10.   
  11. public class UserDaoImpl implements UserDao{  
  12.       
  13.     public boolean register(User user) {  
  14.         boolean flag = false;  
  15.         DBconn.init();  
  16.         int i =DBconn.addUpdDel("insert into user(name,pwd,sex,home,info) " +  
  17.                 "values('"+user.getName()+"','"+user.getPwd()+"','"+user.getSex()+"','"+user.getHome()+"','"+user.getInfo()+"')");  
  18.         if(i>0){  
  19.             flag = true;  
  20.         }  
  21.         DBconn.closeConn();  
  22.         return flag;  
  23.     }  
  24.     public boolean login(String name, String pwd) {  
  25.         boolean flag = false;  
  26.         try {  
  27.                 DBconn.init();  
  28.                 ResultSet rs = DBconn.selectSql("select * from user where name='"+name+"' and pwd='"+pwd+"'");  
  29.                 while(rs.next()){  
  30.                     if(rs.getString("name").equals(name) && rs.getString("pwd").equals(pwd)){  
  31.                         flag = true;  
  32.                     }  
  33.                 }  
  34.                 DBconn.closeConn();  
  35.         } catch (SQLException e) {  
  36.             e.printStackTrace();  
  37.         }  
  38.         return flag;  
  39.     }  
  40.     public List<User> getUserAll() {  
  41.         List<User> list = new ArrayList<User>();  
  42.         try {  
  43.             DBconn.init();  
  44.             ResultSet rs = DBconn.selectSql("select * from user");  
  45.             while(rs.next()){  
  46.                 User user = new User();  
  47.                 user.setId(rs.getInt("id"));  
  48.                 user.setName(rs.getString("name"));  
  49.                 user.setPwd(rs.getString("pwd"));  
  50.                 user.setSex(rs.getString("sex"));  
  51.                 user.setHome(rs.getString("home"));  
  52.                 user.setInfo(rs.getString("info"));  
  53.                 list.add(user);  
  54.             }  
  55.             DBconn.closeConn();  
  56.             return list;  
  57.         } catch (SQLException e) {  
  58.             e.printStackTrace();  
  59.         }  
  60.         return null;  
  61.     }  
  62.     public boolean update(int id,String name, String pwd,String sex, String home,String info) {  
  63.         boolean flag = false;  
  64.         DBconn.init();  
  65.         String sql ="update user set name ='"+name  
  66.                 +"' , pwd ='"+pwd  
  67.                 +"' , sex ='"+sex  
  68.                 +"' , home ='"+home  
  69.                 +"' , info ='"+info+"' where id = "+id;  
  70.         int i =DBconn.addUpdDel(sql);  
  71.         if(i>0){  
  72.             flag = true;  
  73.         }  
  74.         DBconn.closeConn();  
  75.         return flag;  
  76.     }  
  77.     public boolean delete(int id) {  
  78.         boolean flag = false;  
  79.         DBconn.init();  
  80.         String sql = "delete  from user where id="+id;  
  81.         int i =DBconn.addUpdDel(sql);  
  82.         if(i>0){  
  83.             flag = true;  
  84.         }  
  85.         DBconn.closeConn();  
  86.         return flag;  
  87.     }  
  88.       
  89. }  




10.在servlet下创建DengluServlet用来实现对用户登录的操作(Servlet有两种方式创建,一种手工创建。另一种程序自动生成。前者自己创建java类,实现Servlet具体内容,然后需要去WEB_INF下的web.xml去配置servlet  . 而后者则直接由程序替我们配置好了Servlet)本例子使用第二种方式生成Servlet

DengluServlet.java

[java] view plain copy
 
  1. package com.servlet;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5.   
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.http.HttpServlet;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. import com.dao.UserDao;  
  12. import com.dao.UserDaoImpl;  
  13.   
  14. public class DengluServlet extends HttpServlet {  //需要继承HttpServlet  并重写doGet  doPost方法  
  15.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  16.             throws ServletException, IOException {  
  17.         doPost(request, response);  //将信息使用doPost方法执行   对应jsp页面中的form表单中的method  
  18.     }  
  19.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  20.             throws ServletException, IOException {  
  21.           
  22.         String name = request.getParameter("name"); //得到jsp页面传过来的参数  
  23.         String pwd = request.getParameter("pwd");  
  24.           
  25.         UserDao ud = new UserDaoImpl();  
  26.           
  27.         if(ud.login(name, pwd)){  
  28.             request.setAttribute("xiaoxi", "欢迎用户"+name); //向request域中放置信息  
  29.             request.getRequestDispatcher("/success.jsp").forward(request, response);//转发到成功页面  
  30.         }else{  
  31.             response.sendRedirect("index.jsp"); //重定向到首页  
  32.         }  
  33.     }  
  34.   
  35. }  

有两点要注意的地方:

一:getParameter与getAttribute两者的区别

request.setAttribute("xiaoxi", "欢迎用户"+name);//向request域中放置信息 ( 键值对的形式)  名字为xiaoxi  内容为"欢迎用户"+name

request.getAttribute("xiaoxi");//得到request域中放置名字为xiaoxi的信息

request.getParameter("name");//得到request域的参数信息(得到jsp页面传过来的参数)

getAttribute表示从request范围取得设置的属性,必须要先setAttribute设置属性,才能通过getAttribute来取得,设置与取得的为Object对象类型 。

getParameter表示接收参数,参数为页面提交的参数,包括:表单提交的参数、URL重写(就是xxx?id=1中的id)传的参数等,因此这个并没有设置参数的方法(没有setParameter),而且接收参数返回的不是Object,而是String类型

二:转发与重定向的区别

(1).重定向的执行过程:Web服务器向浏览器发送一个http响应--》浏览器接受此响应后再发送一个新的http请求到服务器--》服务器根据此请求寻找资源并发送给浏览器。它可以重定向到任意URL,不能共享request范围内的数据。
(2).重定向是在客户端发挥作用,通过新的地址实现页面转向。
(3).重定向是通过浏览器重新请求地址,在地址栏中可以显示转向后的地址。
(4).转发过程:Web服务器调用内部方法在容器内部完成请求和转发动作--》将目标资源发送给浏览器,它只能在同一个Web应用中使用,可以共享request范围内的数据。
(5).转发是在服务器端发挥作用,通过forward()方法将提交信息在多个页面间进行传递。
(6).转发是在服务器内部控制权的转移,客户端浏览器的地址栏不会显示出转向后的地址。

11.在servlet下创建一个ZhuceServlet用来实现用户注册的操作

ZhuceServlet.java

[java] view plain copy
 
  1. package com.servlet;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5.   
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.http.HttpServlet;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10. import com.dao.UserDao;  
  11. import com.dao.UserDaoImpl;  
  12. import com.entity.User;  
  13.   
  14. public class ZhuceServlet extends HttpServlet {  
  15.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  16.             throws ServletException, IOException {  
  17.         doPost(request, response);  
  18.     }  
  19.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  20.             throws ServletException, IOException {  
  21.           
  22.         String name = request.getParameter("name"); //获取jsp页面传过来的参数  
  23.         String pwd = request.getParameter("pwd");  
  24.         String sex = request.getParameter("sex");  
  25.         String home = request.getParameter("home");  
  26.         String info = request.getParameter("info");  
  27.           
  28.         User user = new User(); //实例化一个对象,组装属性  
  29.         user.setName(name);  
  30.         user.setPwd(pwd);  
  31.         user.setSex(sex);  
  32.         user.setHome(home);  
  33.         user.setInfo(info);  
  34.           
  35.         UserDao ud = new UserDaoImpl();  
  36.           
  37.         if(ud.register(user)){  
  38.             request.setAttribute("username", name);  //向request域中放置参数  
  39.             //request.setAttribute("xiaoxi", "注册成功");  
  40.             request.getRequestDispatcher("/denglu.jsp").forward(request, response);  //转发到登录页面  
  41.         }else{  
  42.               
  43.             response.sendRedirect("index.jsp");//重定向到首页  
  44.         }  
  45.     }  
  46. }  



12.在servlet下创建SearchallServlet用来返回数据库中所有用户信息

Searchall.java

[java] view plain copy
 
  1. package com.servlet;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5. import java.util.List;  
  6.   
  7. import javax.servlet.ServletException;  
  8. import javax.servlet.http.HttpServlet;  
  9. import javax.servlet.http.HttpServletRequest;  
  10. import javax.servlet.http.HttpServletResponse;  
  11.   
  12. import com.dao.UserDao;  
  13. import com.dao.UserDaoImpl;  
  14. import com.entity.User;  
  15.   
  16. public class Searchall extends HttpServlet {  
  17.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  18.             throws ServletException, IOException {  
  19.         doPost(request, response);  
  20.     }  
  21.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  22.             throws ServletException, IOException {  
  23.           
  24.         UserDao ud = new UserDaoImpl();  
  25.         List<User> userAll = ud.getUserAll();  
  26.         request.setAttribute("userAll", userAll);  
  27.         request.getRequestDispatcher("/showall.jsp").forward(request, response);  
  28.     }  
  29. }  



13.在servlet下创建DeleteServlet用来删除用户操作

DeleteServlet.java

[java] view plain copy
 
  1. package com.servlet;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5.   
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.http.HttpServlet;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. import com.dao.UserDao;  
  12. import com.dao.UserDaoImpl;  
  13.   
  14. public class DeleteServlet extends HttpServlet {  
  15.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  16.             throws ServletException, IOException {  
  17.         doPost(request, response);  
  18.     }  
  19.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  20.             throws ServletException, IOException {  
  21.           
  22.         String id = request.getParameter("id");  
  23.         int userId = Integer.parseInt(id);  
  24.           
  25.         UserDao ud = new UserDaoImpl();  
  26.           
  27.         if(ud.delete(userId)){  
  28.             request.setAttribute("xiaoxi", "删除成功");  
  29.             request.getRequestDispatcher("/Searchall").forward(request, response);  
  30.         }else{  
  31.             response.sendRedirect("index.jsp");  
  32.         }  
  33.     }  
  34.   
  35. }  



14.在servlet下创建UpdateServlet操作用来更新用户信息

UpdateServlet.java

[java] view plain copy
 
  1. package com.servlet;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5.   
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.http.HttpServlet;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. import com.dao.UserDao;  
  12. import com.dao.UserDaoImpl;  
  13. import com.entity.User;  
  14.   
  15. public class UpdateServlet extends HttpServlet {  
  16.   
  17.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  18.             throws ServletException, IOException {  
  19.         doPost(request, response);  
  20.     }  
  21.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  22.             throws ServletException, IOException {  
  23.           
  24.         String id = request.getParameter("id");  
  25.         int userId = Integer.parseInt(id);  
  26.           
  27.         String name = request.getParameter("name");  
  28.         String pwd = request.getParameter("pwd");  
  29.         String sex = request.getParameter("sex");  
  30.         String home = request.getParameter("home");  
  31.         String info = request.getParameter("info");  
  32.           
  33.         System.out.println("------------------------------------"+userId);  
  34.           
  35.         UserDao ud = new UserDaoImpl();  
  36.           
  37.         if(ud.update(userId, name, pwd, sex, home, info)){  
  38.             request.setAttribute("xiaoxi", "更新成功");  
  39.             request.getRequestDispatcher("/Searchall").forward(request, response);  
  40.         }else{  
  41.             response.sendRedirect("index.jsp");  
  42.         }  
  43.     }  
  44. }  


15.配置servlet       如果非手打而用MyEclipse生成则不用配置  附完整web.xml

[html] view plain copy
 
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5"   
  3.     xmlns="http://java.sun.com/xml/ns/javaee"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  6.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  7.   <display-name></display-name>   
  8.     
  9.   <filter><!--过滤器配置-->  
  10.     <filter-name>EncodingFilter</filter-name>  
  11.     <filter-class>com.filter.EncodingFilter</filter-class>  
  12.   </filter>  
  13.   <filter-mapping>  
  14.     <filter-name>EncodingFilter</filter-name>  
  15.     <url-pattern>/*</url-pattern>  
  16.   </filter-mapping>  
  17.     
  18.     
  19.     
  20.   <servlet><!--servlet类路径配置-->  
  21.     <servlet-name>DengluServlet</servlet-name>  
  22.     <servlet-class>com.servlet.DengluServlet</servlet-class>  
  23.   </servlet>  
  24.   <servlet>  
  25.     <servlet-name>ZhuceServlet</servlet-name>  
  26.     <servlet-class>com.servlet.ZhuceServlet</servlet-class>  
  27.   </servlet>  
  28.   <servlet>  
  29.     <servlet-name>Searchall</servlet-name>  
  30.     <servlet-class>com.servlet.Searchall</servlet-class>  
  31.   </servlet>  
  32.   <servlet>  
  33.     <servlet-name>DeleteServlet</servlet-name>  
  34.     <servlet-class>com.servlet.DeleteServlet</servlet-class>  
  35.   </servlet>  
  36.   <servlet>  
  37.     <servlet-name>UpdateServlet</servlet-name>  
  38.     <servlet-class>com.servlet.UpdateServlet</servlet-class>  
  39.   </servlet>  
  40.   
  41.   
  42.   
  43.   <servlet-mapping><!--servlet类映射配置-->  
  44.     <servlet-name>DengluServlet</servlet-name>  
  45.     <url-pattern>/DengluServlet</url-pattern>  
  46.   </servlet-mapping>  
  47.   <servlet-mapping>  
  48.     <servlet-name>ZhuceServlet</servlet-name>  
  49.     <url-pattern>/ZhuceServlet</url-pattern>  
  50.   </servlet-mapping>  
  51.   <servlet-mapping>  
  52.     <servlet-name>Searchall</servlet-name>  
  53.     <url-pattern>/Searchall</url-pattern>  
  54.   </servlet-mapping>  
  55.   <servlet-mapping>  
  56.     <servlet-name>DeleteServlet</servlet-name>  
  57.     <url-pattern>/DeleteServlet</url-pattern>  
  58.   </servlet-mapping>  
  59.   <servlet-mapping>  
  60.     <servlet-name>UpdateServlet</servlet-name>  
  61.     <url-pattern>/UpdateServlet</url-pattern>  
  62.   </servlet-mapping>  
  63.     
  64.     
  65.     
  66.   <welcome-file-list><!--默认首页地址-->  
  67.     <welcome-file>denglu.jsp</welcome-file>  
  68.   </welcome-file-list>  
  69. </web-app>  


16.新建jsp页面

denglu.jsp 用户登录页面      默认页面进入项目后  先进入该页面(web.xml中配置)    

form表单中需要注意的是<form action="DengluServlet"  method="post">

其中action即为要跳转的servlet路径(即在web.xml中配置的servlet-mapping   :<url-pattern>/DengluServlet</url-pattern>   ,)写  /  后的内容。

method="post"为传递值得方法类型有两种,第一种get,第二种post。网上介绍这两种的区别有很多,阐述的又是百家争鸣。而我觉得那个方便就用那个,一般使用post传递,可避免乱码。

另一个需要注意的是   用户名:<input type="text" name="name" value="">  input标签  一定要起个名字  如name="name"  

起名的作用就是让后台通过request.getParterment("name");来取值

[plain] view plain copy
 
  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  3. <html>  
  4.   <head>  
  5.     <title>登录注册页面</title>  
  6.   </head>  
  7.   <body >  
  8.          <form action="DengluServlet"  method="post"  style="padding-top:-700px;">  
  9.         用户名:<input type="text" name="name"value=""><br><br>  
  10.         密码:  <input type="password" name="pwd"value=""><br><br>  
  11.                     <input type="submit"value="登录"name="denglu"><input type="reset"value="重置"><br>  
  12.      </form>  
  13.      <form action="zhuce.jsp">  
  14.         <input type="submit"value="新用户注册">  
  15.          </form>  
  16.       
  17.   </body>  
  18. </html>  


zhuce.jsp  用户注册页面

[plain] view plain copy
 
  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  7. <html>  
  8.   <head>  
  9.     <title>My JSP 'BB.jsp' starting page</title>  
  10.   </head>  
  11.   <body >  
  12.   <form action="ZhuceServlet"method="post" style="padding-top:-700px;">  
  13.        输入用户名:<input name="name" type="text"><br><br>  
  14.        输入密码:<input name="pwd" type="password"><br><br>  
  15.        选择性别:<input type="radio"name="sex"value="男"checked>男  
  16.             <input type="radio"name="sex"value="女">女<br><br>  
  17.        选择家乡:  
  18.        <select name="home">  
  19.            <option value="上海">上海</option>  
  20.            <option value="北京" selected>北京</option>  
  21.            <option value="纽约">纽约</option>  
  22.         </select><br>  
  23.                填写个人信息:<br>  
  24.        <textarea name="info" row="5"cols="30"></textarea><br>  
  25.        <input type="reset"value="重置"><input type="submit"value="注册">  
  26.    </form>  
  27.   </body>  
  28. </html>  

 
index.jsp  失败页面

[plain] view plain copy
 
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  7. <html>  
  8.   <head>  
  9.     <title>My JSP 'index.jsp' starting page</title>  
  10.   </head>  
  11.   <body>  
  12.             <h1>失敗</h1>  
  13.   </body>  
  14. </html>  

success.jsp  成功页面

${xiaoxi}为EL表达式  获取request域中的键名为xiaoxi的值

[plain] view plain copy
 
  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <title>My JSP 'success.jsp' starting page</title>  
  11.   </head>  
  12.   <body>  
  13.             ${xiaoxi} <br>    
  14.             <a href="Searchall">查看所有用户</a>  
  15.   </body>  
  16. </html>  

showall.jsp   展现所有用户页面

页面使用的到JSTL表达式 即c标签。使用c标签需要引入头文件<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 。

需要注意的的是El标签配合JSTl标签的使用,<c:forEach var="U" items="${userAll}"  >   例子foeEach标签的遍历内容即为EL表达式获取的${userAll}

而且当指定别名后var="U"  ,别名可以随便起,为了方便一般是小写类名命名。  

C标签内遍历的属性也是需要用${  }获取。此时别名U即为当前集合中的User对象,想得到属性只需要用 ${ U.属性名 }     即可

[plain] view plain copy
 
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>   
  3. <%  
  4. String path = request.getContextPath();  
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  6. %>  
  7.   
  8. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  9. <html>  
  10.   <head>  
  11.     <base href="<%=basePath%>">  
  12.     <title>所有用户页面</title>  
  13.   </head>  
  14.     
  15.   <body>  
  16.   <h1>${xiaoxi}</h1>  
  17.   <table  width="600" border="1" cellpadding="0" >  
  18.         <tr>  
  19.             <th>ID</th>  
  20.             <th>姓名</th>  
  21.             <th>性别</th>  
  22.             <th>密码</th>  
  23.             <th>家乡</th>  
  24.             <th>备注</th>  
  25.             <th>操作</th>  
  26.         </tr>  
  27.      <c:forEach var="U" items="${userAll}"  >   
  28.       <form action="UpdateServlet" method="post">   
  29.        <tr>  
  30.            <td><input type="text" value="${U.id}" name="id" ></td>  
  31.            <td><input type="text" value="${U.name}" name="name"></td>  
  32.            <td><input type="text" value="${U.sex}" name="sex"></td>  
  33.            <td><input type="text" value="${U.pwd}" name="pwd"></td>  
  34.            <td><input type="text" value="${U.home}" name="home"></td>  
  35.            <td><input type="text" value="${U.info}" name="info"></td>  
  36.            <td><a href="DeleteServlet?id=${U.id}">删除</a>  <input type="submit" value="更新"/></td>  
  37.        </tr>  
  38.     </form>   
  39.     </c:forEach>    
  40.     </table>  
  41.   </body>  
  42. </html>  

项目结构

原文地址:https://www.cnblogs.com/mjbrian/p/8746492.html