人的命运呐,就是不能预料。草根……
导入jar包,贴好代码(Java命名存在不规范)
建表(sql建表语句.txt)
1 CREATE TABLE `userinfo` ( 2 `id` int(11) NOT NULL AUTO_INCREMENT, 3 `username` varchar(45) DEFAULT NULL, 4 `password` varchar(45) DEFAULT NULL, 5 PRIMARY KEY (`id`) 6 ) 7 8 CREATE TABLE `useraddr` ( 9 `id` int(11) NOT NULL AUTO_INCREMENT, 10 `country` varchar(45) DEFAULT NULL, 11 `city` varchar(45) DEFAULT NULL, 12 `userid` varchar(45) DEFAULT NULL, 13 PRIMARY KEY (`id`) 14 )
userServlet.java
1 package com.roadArchitectWeb.control; 2 3 import java.io.IOException; 4 import java.sql.Connection; 5 import java.sql.SQLException; 6 7 import javax.servlet.RequestDispatcher; 8 import javax.servlet.ServletException; 9 import javax.servlet.http.HttpServlet; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 13 import com.roadArchitectWeb.Service.userService; 14 import com.roadArchitectWeb.entity.UserInfo; 15 import com.roadArchitectWeb.util.ConnectionFactory; 16 17 public class userServlet extends HttpServlet { 18 userService userService = new userService(); 19 20 @Override 21 protected void doPost(HttpServletRequest req, HttpServletResponse resp) 22 throws ServletException, IOException { 23 String userName = req.getParameter("userName"); 24 String passWord = req.getParameter("passWord"); 25 UserInfo user = new UserInfo(); 26 user.setUsername(userName); 27 user.setPassword(passWord); 28 29 ConnectionFactory connectionFactory = ConnectionFactory.getInstance(); 30 Connection conn = connectionFactory.getConnection(); 31 try { 32 if (userService.checkUser(conn, user)) { 33 System.out.println("userServlet.doPost()" + "登陆成功"); 34 RequestDispatcher rd = req 35 .getRequestDispatcher("/login/welcome.jsp"); 36 req.setAttribute("userName", userName); 37 req.setAttribute("passWord", passWord); 38 req.setAttribute("login", "1"); 39 rd.forward(req, resp); 40 } else { 41 System.out.println("userServlet.doPost()" + "登陆失败"); 42 RequestDispatcher rd = req 43 .getRequestDispatcher("/login/welcome.jsp"); 44 req.setAttribute("userName", userName); 45 req.setAttribute("passWord", passWord); 46 rd.forward(req, resp); 47 } 48 } catch (SQLException e) { 49 e.printStackTrace(); 50 } 51 } 52 53 }
userService.java
1 package com.roadArchitectWeb.Service; 2 3 import java.sql.Connection; 4 import java.sql.SQLException; 5 6 import com.roadArchitectWeb.dao.UserDao; 7 import com.roadArchitectWeb.dao.UserDaoImpl; 8 import com.roadArchitectWeb.entity.UserInfo; 9 10 public class userService { 11 UserDao userDao = new UserDaoImpl(); 12 13 public boolean checkUser(Connection conn, UserInfo userInfo) 14 throws SQLException { 15 Boolean status = false; 16 try { 17 conn.setAutoCommit(false); 18 status = userDao.queryUser(conn, userInfo); 19 conn.commit(); 20 } catch (Exception e) { 21 e.printStackTrace(); 22 conn.rollback(); 23 try { 24 conn.setAutoCommit(true); 25 } catch (SQLException e3) { 26 e3.printStackTrace(); 27 } 28 } 29 return status; 30 } 31 32 }
UserDao.java
1 package com.roadArchitectWeb.dao; 2 3 import java.sql.Connection; 4 import java.sql.SQLException; 5 6 import com.roadArchitectWeb.entity.UserAddr; 7 import com.roadArchitectWeb.entity.UserInfo; 8 9 public interface UserDao { 10 public void save(Connection conn, UserAddr userAddr) throws SQLException; 11 12 public void update(Connection conn, UserAddr userAddr) throws SQLException; 13 14 public void delete(Connection conn, long id) throws SQLException; 15 16 public UserAddr singalSelect(Connection conn, long id) throws SQLException; 17 18 public boolean queryUser(Connection conn, UserInfo userInfo) 19 throws SQLException; 20 }
UserDaoImpl.java
1 package com.roadArchitectWeb.dao; 2 3 import java.sql.Connection; 4 import java.sql.PreparedStatement; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 8 import com.roadArchitectWeb.entity.UserAddr; 9 import com.roadArchitectWeb.entity.UserInfo; 10 11 public class UserDaoImpl implements UserDao { 12 13 @Override 14 public void save(Connection conn, UserAddr userAddr) throws SQLException { 15 String saveSql = "insert into useraddr(country,city,userid) values(?,?,?)"; 16 PreparedStatement ps = conn.prepareCall(saveSql); 17 ps.setString(1, userAddr.getCountry()); 18 ps.setString(2, userAddr.getCity()); 19 ps.setString(3, userAddr.getUserid()); 20 ps.execute(); 21 } 22 23 @Override 24 public void update(Connection conn, UserAddr userAddr) throws SQLException { 25 String updateSql = "update useraddr set country=?,city=?,userid=? where id=?"; 26 PreparedStatement ps = conn.prepareStatement(updateSql); 27 ps.setString(1, userAddr.getCountry()); 28 ps.setString(2, userAddr.getCity()); 29 ps.setString(3, userAddr.getUserid()); 30 ps.setLong(4, userAddr.getId()); 31 ps.execute(); 32 } 33 34 @Override 35 public void delete(Connection conn, long id) throws SQLException { 36 String deleteSql = "delete from useraddr where id = ?"; 37 PreparedStatement ps = conn.prepareStatement(deleteSql); 38 ps.setLong(1, id); 39 ps.execute(); 40 } 41 42 @Override 43 public UserAddr singalSelect(Connection conn, long id) throws SQLException { 44 String selectSql = "select * from useraddr where id = ?"; 45 PreparedStatement ps = conn.prepareStatement(selectSql); 46 ps.setLong(1, id); 47 ResultSet rs = ps.executeQuery(); 48 UserAddr userAddr = new UserAddr(); 49 while (rs.next()) { 50 userAddr.setId(id); 51 userAddr.setCountry(rs.getString("country")); 52 userAddr.setCity(rs.getString("city")); 53 userAddr.setUserid(rs.getString("userid")); 54 } 55 return userAddr; 56 } 57 58 public boolean queryUser(Connection conn, UserInfo userInfo) 59 throws SQLException { 60 String sql = "select * from userinfo where username=? and password=?"; 61 PreparedStatement st = conn.prepareStatement(sql); 62 st.setString(1, userInfo.getUsername()); 63 st.setString(2, userInfo.getPassword()); 64 ResultSet rst = st.executeQuery(); 65 if (rst.next()) 66 return true; 67 else { 68 return false; 69 } 70 } 71 }
ConnectionFactory.java
1 package com.roadArchitectWeb.util; 2 3 import java.io.InputStream; 4 import java.sql.Connection; 5 import java.sql.DriverManager; 6 import java.util.Properties; 7 8 public class ConnectionFactory { 9 10 private static Connection conn = null; 11 private static String driver; 12 private static String dburl; 13 private static String user; 14 private static String password; 15 16 private static ConnectionFactory connectionFactory = new ConnectionFactory(); 17 18 static { 19 Properties prop = new Properties(); 20 try { 21 InputStream in = ConnectionFactory.class.getClassLoader() 22 .getResourceAsStream("dbconfig.properties"); 23 prop.load(in); 24 } catch (Exception e) { 25 System.out.println("properties file read error"); 26 } 27 28 driver = prop.getProperty("driver"); 29 dburl = prop.getProperty("dbUrl"); 30 user = prop.getProperty("user"); 31 password = prop.getProperty("password"); 32 } 33 34 private ConnectionFactory() { 35 36 } 37 38 public Connection getConnection() { 39 try { 40 Class.forName(driver); 41 conn = DriverManager.getConnection(dburl, user, password); 42 } catch (Exception e) { 43 e.printStackTrace(); 44 } 45 return conn; 46 } 47 48 public static ConnectionFactory getInstance() { 49 return connectionFactory; 50 } 51 }
IdEntity.java
1 package com.roadArchitectWeb.entity; 2 3 public abstract class IdEntity { 4 protected long id; 5 6 public long getId() { 7 return id; 8 } 9 10 public void setId(long id) { 11 this.id = id; 12 } 13 14 @Override 15 public String toString() { 16 return "IdEntity [id=" + id + ", getId()=" + getId() + ", getClass()=" 17 + getClass() + ", hashCode()=" + hashCode() + ", toString()=" 18 + super.toString() + "]"; 19 } 20 21 }
UserAddr.java
1 package com.roadArchitectWeb.entity; 2 3 public class UserAddr extends IdEntity { 4 private String country; 5 private String city; 6 private String userid; 7 8 public String getCountry() { 9 return country; 10 } 11 12 public void setCountry(String country) { 13 this.country = country; 14 } 15 16 public String getCity() { 17 return city; 18 } 19 20 public void setCity(String city) { 21 this.city = city; 22 } 23 24 public String getUserid() { 25 return userid; 26 } 27 28 public void setUserid(String userid) { 29 this.userid = userid; 30 } 31 32 @Override 33 public String toString() { 34 return "UserAddr [country=" + country + ", city=" + city + ", userid=" 35 + userid + ", id=" + id + ", getCountry()=" + getCountry() 36 + ", getCity()=" + getCity() + ", getUserid()=" + getUserid() 37 + ", getId()=" + getId() + ", toString()=" + super.toString() 38 + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() 39 + "]"; 40 } 41 42 }
UserInfo.java
1 package com.roadArchitectWeb.entity; 2 3 public class UserInfo extends IdEntity { 4 private String username; 5 private String password; 6 private String email; 7 8 public String getUsername() { 9 return username; 10 } 11 12 public void setUsername(String username) { 13 this.username = username; 14 } 15 16 public String getPassword() { 17 return password; 18 } 19 20 public void setPassword(String password) { 21 this.password = password; 22 } 23 24 public String getEmail() { 25 return email; 26 } 27 28 public void setEmail(String email) { 29 this.email = email; 30 } 31 32 @Override 33 public String toString() { 34 return "UserInfo [username=" + username + ", password=" + password 35 + ", email=" + email + ", id=" + id + ", getUsername()=" 36 + getUsername() + ", getPassword()=" + getPassword() 37 + ", getEmail()=" + getEmail() + ", getId()=" + getId() 38 + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() 39 + ", toString()=" + super.toString() + "]"; 40 } 41 42 }
测试方法(3个):
createjson.java
1 package com.roadArchitectWeb.Test; 2 3 import com.google.gson.JsonArray; 4 import com.google.gson.JsonObject; 5 6 public class createjson { 7 public static void main(String[] args) { 8 JsonObject jsonObject = new JsonObject(); 9 jsonObject.addProperty("start", "This is start"); 10 11 JsonArray jsonArray = new JsonArray(); 12 JsonObject jsonObject1 = new JsonObject(); 13 jsonObject1.addProperty("1", 1); 14 jsonObject1.addProperty("2", 2); 15 JsonObject jsonObject2 = new JsonObject(); 16 jsonObject2.addProperty("3", "3"); 17 jsonObject2.addProperty("4", "4"); 18 JsonObject jsonObject3 = new JsonObject(); 19 jsonObject3.addProperty("5", true); 20 jsonObject3.addProperty("6", false); 21 jsonArray.add(jsonObject1); 22 jsonArray.add(jsonObject2); 23 jsonArray.add(jsonObject3); 24 25 jsonObject.add("middle", jsonArray); 26 jsonObject.addProperty("end", "This is end"); 27 28 System.out.println("createjson.main():" + jsonObject.toString()); 29 } 30 }
测试结果:
JsonRead.java
1 package com.roadArchitectWeb.Test; 2 3 import java.io.FileNotFoundException; 4 import java.io.FileReader; 5 6 import com.google.gson.JsonArray; 7 import com.google.gson.JsonObject; 8 import com.google.gson.JsonParser; 9 import com.google.gson.stream.JsonReader; 10 11 public class JsonRead { 12 public static void main(String[] args) { 13 JsonParser jsonParser = new JsonParser(); 14 JsonReader jsonReader=null; 15 try { 16 jsonReader = new JsonReader(new FileReader("src/test.json"));//这里为什么不能用相对路径 17 } catch (FileNotFoundException e) { 18 e.printStackTrace(); 19 } 20 JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonReader); 21 22 String start = jsonObject.get("start").getAsString(); 23 24 JsonArray middleObject = jsonObject.get("middle").getAsJsonArray(); 25 26 int middle1 = ((JsonObject) middleObject.get(0)).get("1").getAsInt(); 27 String middle2a = ((JsonObject) middleObject.get(0)).get("2").getAsString(); 28 int middle3 = ((JsonObject) middleObject.get(1)).get("3").getAsInt(); 29 String middle4a = ((JsonObject) middleObject.get(1)).get("4").getAsString(); 30 int middle5 = ((JsonObject) middleObject.get(2)).get("5").getAsInt(); 31 String middle6a = ((JsonObject) middleObject.get(2)).get("6").getAsString(); 32 33 Boolean end = jsonObject.get("end").getAsBoolean(); 34 System.out.println("JsonRead.main():"+start); 35 System.out.println("JsonRead.main():"+middle1+" "+middle2a+" "+middle3+" "+middle4a+" "+middle5+" "+middle6a); 36 System.out.println("JsonRead.main():"+end); 37 } 38 39 40 }
测试结果:
UserDaoTest.java
1 package com.roadArchitectWeb.Test; 2 3 import java.sql.Connection; 4 import java.sql.SQLException; 5 6 import com.roadArchitectWeb.dao.UserDao; 7 import com.roadArchitectWeb.dao.UserDaoImpl; 8 import com.roadArchitectWeb.entity.UserAddr; 9 import com.roadArchitectWeb.util.ConnectionFactory; 10 11 public class UserDaoTest { 12 public static void main(String[] args) throws SQLException{ 13 ConnectionFactory connectionFactory = ConnectionFactory.getInstance(); 14 Connection conn = connectionFactory.getConnection(); 15 16 UserDao userDao = new UserDaoImpl(); 17 UserAddr userAddr = new UserAddr(); 18 // userAddr.setCountry("China"); 19 // userAddr.setCity("hangzhou"); 20 // userAddr.setUserid("10"); 21 // userDao.save(conn,userAddr); 22 23 // userAddr.setId(5); 24 // userAddr.setCity("nanjing"); 25 // userAddr.setCountry("USA"); 26 // userAddr.setUserid("11"); 27 // userDao.update(conn, userAddr); 28 29 // userDao.delete(conn, 4); 30 31 // userAddr = userDao.singalSelect(conn,5); 32 } 33 }
测试结果(useraddr表):
等
login.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>login.jsp</title> 8 </head> 9 <body> 10 11 <form action="<%=request.getContextPath()%>/userServlet" method="post"> 12 用户名:<input type="text" name="userName"></input> 13 密码:<input type="password" name="passWord"></input> 14 <input type="submit" value="submit"></input> 15 </form> 16 17 </body> 18 </html>
welcome.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></title> 8 </head> 9 <body> 10 <% 11 String userName = request.getAttribute("userName").toString(); 12 if (null != request.getAttribute("login") && !"".equals(request.getAttribute("login").toString())) 13 out.println(userName + " success,欢迎来到登陆界面"); 14 else 15 out.println(userName + " fail,请回到登陆界面"); 16 %> 17 </body> 18 </html>
web.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> 3 <display-name>roadArchitectWeb</display-name> 4 <welcome-file-list> 5 <welcome-file>index.html</welcome-file> 6 <welcome-file>index.htm</welcome-file> 7 <welcome-file>index.jsp</welcome-file> 8 <welcome-file>default.html</welcome-file> 9 <welcome-file>default.htm</welcome-file> 10 <welcome-file>default.jsp</welcome-file> 11 </welcome-file-list> 12 13 <servlet> 14 <servlet-name>userServlet</servlet-name> 15 <servlet-class>com.roadArchitectWeb.control.userServlet</servlet-class> 16 <init-param> 17 <param-name>firstName</param-name> 18 <param-value>majintao</param-value> 19 </init-param> 20 <init-param> 21 <param-name>firstPassword</param-name> 22 <param-value>majintaop</param-value> 23 </init-param> 24 </servlet> 25 <servlet-mapping> 26 <servlet-name>userServlet</servlet-name> 27 <url-pattern>/userServlet</url-pattern> 28 </servlet-mapping> 29 30 </web-app>
dbconfig.properties
driver=com.mysql.jdbc.Driver dbUrl=jdbc\:mysql\://localhost\:3306/chenyu_db user=root password=
test.json
{ "start":"this is start", "middle": [{"1":1,"2":"2a"}, {"3":3,"4":"4a"}, {"5":5,"6":"6a"}], "end":true }
3个jar包:gson-2.2.4-sources.jar、gson-2.2.4.jar、mysql-connector-java-5.1.38-bin.jar
在useraddr中插入数据:
发布工程,访问http://localhost:9080/roadArchitectWeb/login/login.jsp
提交,登陆成功。
代码就是详细理解的过程了。
参考原文:http://blog.csdn.net/jintao_ma/article/details/51051281