Java Servlet(七):JavaWeb MVC 操作(jdk7+tomcat7+eclipse)

之前一段时间一直忙于毕业设计,也没有空学习了,本篇继续学习。

本篇将开始学习java web下使用servlet下来操作数据库,并展示到界面上的使用方法。

新建工程ServletMvc001。

目录结构如下:

web.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3     xmlns="http://java.sun.com/xml/ns/javaee"
 4     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 5     id="WebApp_ID" version="3.0">
 6     <display-name>ServletMvc001</display-name>
 7     <welcome-file-list>    
 8         <welcome-file>logon.jsp</welcome-file>
 9     </welcome-file-list>
10     <servlet>
11         <servlet-name>logOnServlet</servlet-name>
12         <servlet-class>com.dx.javamvc.servlets.LogOnServlet</servlet-class>
13     </servlet>
14     <servlet-mapping>
15         <servlet-name>logOnServlet</servlet-name>
16         <url-pattern>/LogOnServlet</url-pattern>
17     </servlet-mapping>
18 </web-app>

logon.jsp

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10     <form name="form1" id="form1" method="get" action="LogOnServlet">
11         <input type="submit" id="btnOk" name="btnOk" value="提交" />
12     </form>
13 </body>
14 </html>

showPerfileInfo.jsp

 1 <%@page import="com.mysql.fabric.Response"%>
 2 <%@page import="java.util.List" %>
 3 <%@page import="com.dx.javamvc.entity.User" %>
 4 <%@ page language="java" contentType="text/html; charset=UTF-8"
 5     pageEncoding="UTF-8" %>
 6 
 7 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 8 <html>
 9 <head>
10 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
11 <title>Insert title here</title>
12 </head>
13 <body>
14 <% List<User> userItem= (List<User>)request.getAttribute("UserItems"); %>
15 <%for(User user :userItem){
16     out.write("llddd");
17     %>
18     <%=user.getId() %><br/>
19     <%=user.getUserName() %><br/>
20     <%=user.getPassword() %><br/>
21     <%
22 } %>
23 </body>
24 </html>
View Code

jdbc.properties

1 DriverClass=com.mysql.jdbc.Driver
2 
3 JdbcUrl=jdbc:mysql://localhost:3306/servletmvc001
4 
5 UserName=root
6 
7 Password=123456

DbConfiguration.java

 1 package com.dx.javamvc.configuration;
 2 
 3 import java.io.*;
 4 import java.net.URISyntaxException;
 5 import java.util.*;
 6 
 7 public class DbConfiguration {
 8     private static final String FILENAME = "jdbc.properties";
 9     private static String userName = null;
10     private static String password = null;
11     private static String jdbcUrl = null;
12     private static String driverClass = null;
13 
14     public DbConfiguration() {
15         Properties property = new Properties();
16 
17         try {
18             String path = this.getClass().getClassLoader().getResource("").toURI().getPath();
19             FileInputStream inStream = new FileInputStream(new File(path + FILENAME));
20             property.load(inStream);
21             setUserName(property.getProperty("UserName"));
22             setPassword(property.getProperty("Password"));
23             setJdbcUrl(property.getProperty("JdbcUrl"));
24             setDriverClass(property.getProperty("DriverClass"));
25         } catch (URISyntaxException e) {
26             // TODO Auto-generated catch block
27             e.printStackTrace();
28         } catch (FileNotFoundException e) {
29             // TODO Auto-generated catch block
30             e.printStackTrace();
31         } catch (IOException e) {
32             // TODO Auto-generated catch block
33             e.printStackTrace();
34         }
35     }
36 
37     public  String getUserName() {
38         return userName;
39     }
40 
41     private  void setUserName(String userName) {
42         DbConfiguration.userName = userName;
43     }
44 
45     public  String getPassword() {
46         return password;
47     }
48 
49     private  void setPassword(String password) {
50         DbConfiguration.password = password;
51     }
52 
53     public  String getJdbcUrl() {
54         return jdbcUrl;
55     }
56 
57     private  void setJdbcUrl(String jdbcUrl) {
58         DbConfiguration.jdbcUrl = jdbcUrl;
59     }
60 
61     public  String getDriverClass() {
62         return driverClass;
63     }
64 
65     private  void setDriverClass(String driverClass) {
66         DbConfiguration.driverClass = driverClass;
67     }
68 
69 }

SexType.java

 1 package com.dx.javamvc.entity;
 2 
 3 public enum SexType {
 4     Mail(0), Femail(1);
 5 
 6     private int value;
 7 
 8     private SexType(int value) {
 9         setValue(value);
10     }
11 
12     public int getValue() {
13         return value;
14     }
15 
16     public void setValue(int value) {
17         this.value = value;
18     }
19 
20     public static SexType valueOf(int value) {
21         SexType sexType;
22         switch (value) {
23         case 1:
24             sexType = SexType.Femail;
25             break;
26         default:
27             sexType = SexType.Mail;
28             break;
29         }
30 
31         return sexType;
32     }
33 }

User.java

 1 package com.dx.javamvc.entity;
 2 
 3 import java.util.Date;
 4 
 5 public class User {
 6     private int id;
 7     private String userName;
 8     private String password;
 9     private SexType sex;
10     private Date createDate;
11 
12     public int getId() {
13         return id;
14     }
15 
16     public void setId(int id) {
17         this.id = id;
18     }
19 
20     public String getUserName() {
21         return userName;
22     }
23 
24     public void setUserName(String userName) {
25         this.userName = userName;
26     }
27 
28     public String getPassword() {
29         return password;
30     }
31 
32     public void setPassword(String password) {
33         this.password = password;
34     }
35 
36     public SexType getSex() {
37         return sex;
38     }
39 
40     public void setSex(SexType sex) {
41         this.sex = sex;
42     }
43 
44     public Date getCreateDate() {
45         return createDate;
46     }
47 
48     public void setCreateDate(Date createDate) {
49         this.createDate = createDate;
50     }
51 }

DbUtil.java

 1 package com.dx.javamvc.utils;
 2 
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 import java.sql.PreparedStatement;
 6 import java.sql.ResultSet;
 7 import java.sql.SQLException;
 8 
 9 import com.dx.javamvc.configuration.DbConfiguration;
10 import com.dx.javamvc.types.IExecuteQueryAction;
11 import com.dx.javamvc.types.IPreparedStatementAction;
12 
13 public class DbUtil {
14     public static void executeQuery(String sql, IPreparedStatementAction preparedStatementAction,
15             IExecuteQueryAction executeQueryAction) {
16         Connection connection = null;
17         PreparedStatement preparedStatement = null;
18         ResultSet resultSet = null;
19         
20         DbConfiguration configuration=new DbConfiguration();
21         String driverClass = configuration.getDriverClass();
22         String jdbcUrl = configuration.getJdbcUrl();
23         String userName = configuration.getUserName();
24         String password = configuration.getPassword();
25 
26         try {
27             Class.forName(driverClass);
28 
29             connection = DriverManager.getConnection(jdbcUrl, userName, password);
30             preparedStatement = connection.prepareStatement(sql);
31 
32             if (preparedStatementAction != null) {
33                 preparedStatementAction.action(preparedStatement);
34             }
35 
36             resultSet = preparedStatement.executeQuery();
37 
38             if (executeQueryAction != null) {
39                 executeQueryAction.action(resultSet);
40             }
41         } catch (ClassNotFoundException e) {
42             // TODO Auto-generated catch block
43             e.printStackTrace();
44         } catch (SQLException e) {
45             // TODO Auto-generated catch block
46             e.printStackTrace();
47         } finally {
48             if (resultSet != null) {
49                 try {
50                     resultSet.close();
51                 } catch (SQLException e) {
52                     // TODO Auto-generated catch block
53                     e.printStackTrace();
54                 }
55             }
56             if (preparedStatement != null) {
57                 try {
58                     preparedStatement.close();
59                 } catch (SQLException e) {
60                     // TODO Auto-generated catch block
61                     e.printStackTrace();
62                 }
63             }
64             if (connection != null) {
65                 try {
66                     connection.close();
67                 } catch (SQLException e) {
68                     // TODO Auto-generated catch block
69                     e.printStackTrace();
70                 }
71             }
72         }
73 
74     }
75 
76 }
View Code

IExecuteQueryAction.java

1 package com.dx.javamvc.types;
2 
3 import java.sql.ResultSet;
4 import java.sql.SQLException;
5 
6 public interface IExecuteQueryAction {
7     void action(ResultSet result) throws SQLException;
8 }
View Code

IPreparedStatementAction.java

1 package com.dx.javamvc.types;
2 
3 import java.sql.PreparedStatement;
4 import java.sql.SQLException;
5 
6 public interface IPreparedStatementAction {
7     void action(PreparedStatement preparedStatement) throws SQLException;
8 }
View Code

UserDao.java

 1 package com.dx.javamvc.domain;
 2 
 3 import java.sql.PreparedStatement;
 4 import java.sql.ResultSet;
 5 import java.sql.SQLException;
 6 import java.util.ArrayList;
 7 import java.util.List;
 8 
 9 import com.dx.javamvc.entity.SexType;
10 import com.dx.javamvc.entity.User;
11 import com.dx.javamvc.types.IPreparedStatementAction;
12 import com.dx.javamvc.types.IExecuteQueryAction;
13 import com.dx.javamvc.utils.DbUtil;
14 
15 public class UserDao {
16     public List<User> getUserByUserName(final String userName) {
17         final List<User> userItems = new ArrayList<User>();
18 
19         String sql = "Select * From User Where Name=?";
20 
21         IPreparedStatementAction preparedStatementAction = new IPreparedStatementAction() {
22             @Override
23             public void action(PreparedStatement preparedStatement) throws SQLException {
24                 preparedStatement.setString(1, userName);
25             }
26         };
27 
28         IExecuteQueryAction executeQueryAction = new IExecuteQueryAction() {
29             @Override
30             public void action(ResultSet result) throws SQLException {
31                 try {
32                     while (result.next()) {
33                         User user = new User();
34 
35                         user.setId(result.getInt("Id"));
36                         user.setUserName(result.getString("Name"));
37                         user.setPassword(result.getString("Password"));
38                         user.setSex(SexType.valueOf(result.getInt("Sex")));
39                         user.setCreateDate(result.getDate("CreateDate"));
40 
41                         userItems.add(user);
42                     }
43                 } catch (SQLException e) {
44                     e.printStackTrace();
45                 }
46             }
47         };
48 
49         DbUtil.executeQuery(sql, preparedStatementAction, executeQueryAction);
50 
51         return userItems;
52 
53     }
54 }
View Code

LogOnServlet.java

 1 package com.dx.javamvc.servlets;
 2 
 3 import java.io.IOException;
 4 import java.util.List;
 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.dx.javamvc.domain.UserDao;
12 import com.dx.javamvc.entity.User;
13 
14 public class LogOnServlet extends HttpServlet {
15     private static final long serialVersionUID = -8807878351076369807L;
16     private static final UserDao userDao = new UserDao();
17 
18     @Override
19     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
20         List<User> userItems = userDao.getUserByUserName("yy3b2007com");
21         req.setAttribute("UserItems", userItems);
22         req.getRequestDispatcher("/showPerfileInfo.jsp").forward(req, resp);
23     }
24 }
View Code

 

posted @ 2016-05-05 23:45  cctext  阅读(328)  评论(0编辑  收藏  举报