实习第三周2
Servlet对包的需求更少的了。因为没用Spring,数据库的连接和操作需要自己来实现,这样就需要mysql-connector-java-5.1.36.jar。为了以后配置方便,我还把数据配置写到了一个db.property
url=jdbc:mysql://localhost:3306/iciss?useUnicode=true&characterEncoding=UTF-8 username=root password=
这里还用了一个convertList函数把数据库的返回ResultSet转化为List
package common; import java.io.InputStream; import java.sql.*; import java.util.*; /** * Created by PRO_HD_Rorz on 2015/7/28. */ public class Dbcon { private Connection conn = null; private Statement st = null; private ResultSet rs = null; protected ErrorLogger errorLogger = new ErrorLogger(); public Dbcon() { /*databaseName = "iciss"; userName = "root"; password = "";*/ String url = getproperty("url"); String username = getproperty("username"); String password = getproperty("password"); try { //写入驱动所在处,打开驱动 Class.forName("com.mysql.jdbc.Driver").newInstance(); //数据库,用户,密码,创建与具体数据库的连接 conn = DriverManager.getConnection(url, username, password); //创建执行sql语句的对象 st = conn.createStatement(); } catch (Exception e) { errorLogger.write("数据库连接失败\t" + url + "\r\n" + e.toString()); } } public Dbcon(String databaseName, String userName, String password) { /*databaseName = "iciss"; userName = "root"; password = "";*/ try { //写入驱动所在处,打开驱动 Class.forName("com.mysql.jdbc.Driver").newInstance(); //数据库,用户,密码,创建与具体数据库的连接 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/?useUnicode=true&characterEncoding=UTF-8" + databaseName, userName, password); //创建执行sql语句的对象 st = conn.createStatement(); } catch (Exception e) { errorLogger.write("数据库连接失败" + e.toString()); } } public String getproperty(String key) { String path = this.getClass().getResource("/").getPath(); Properties prop = new Properties(); try { //InputStream is = this.getClass().getResourceAsStream("../" + path + "db.property"); InputStream is = this.getClass().getResourceAsStream("../../" + "db.property"); prop.load(is); if(is != null) { is.close(); } } catch(Exception e) { errorLogger.write("数据库配置文件载入失败" + "\t" + "../../" + "db.property" + "\r\n" + e.toString() + e.getStackTrace()); } return prop.getProperty(key); } public String query(String sql, int n) { String result = ""; try { rs = st.executeQuery(sql); while (rs != null && rs.next()) { result = rs.getString(n); //列的记数是从1开始的,这个适配器和C#的不同 } rs.close(); return result; } catch (Exception e) { errorLogger.write("执行sql失败\t" + sql + "\r\n" + e.toString()); return null; } } public int query(String sql) { int row = 0; try { row = st.executeUpdate(sql); this.close(); return row; } catch (Exception e) { errorLogger.write("执行sql失败\t" + sql + "\r\n" + e.toString()); this.close(); return row; } } public List query(String sql, Object... args) { try { PreparedStatement pst = conn.prepareStatement(sql); for(int i=0 ; i<args.length ; i++) { pst.setObject(i+1, args[i]); } pst.execute(); List re = convertList(pst.getResultSet()); this.close(); return re; } catch (Exception e) { errorLogger.write("执行sql失败\t" + sql + "\r\n" + e.toString()); this.close(); return null; } } public int update(String sql, Object... args) { try { PreparedStatement pst = conn.prepareStatement(sql); for(int i=0 ; i<args.length ; i++) { pst.setObject(i+1, args[i]); } int re = pst.executeUpdate(); this.close(); return re; } catch (Exception e) { errorLogger.write("执行sql失败\t" + sql + "\r\n" + e.toString()); this.close(); return 0; } } public void close() { try { if (rs != null) this.rs.close(); if (st != null) this.st.close(); if (conn != null) this.conn.close(); } catch (Exception e) { errorLogger.write("关闭数据库连接失败" + e.toString()); } } private static List convertList(ResultSet rs) throws SQLException { List list = new ArrayList(); ResultSetMetaData md = rs.getMetaData(); int columnCount = md.getColumnCount(); //Map rowData; while (rs.next()) { //rowData = new HashMap(columnCount); Map rowData = new HashMap(); for (int i = 1; i <= columnCount; i++) { rowData.put(md.getColumnName(i), rs.getObject(i)); } list.add(rowData); } return list; } }
这里没用log4j,我自己实现了2个日志类,一个记录事件,一个记录错误
package common; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by PRO_HD_Rorz on 2015/7/29. */ public class InfoLogger { private String logpath = "e:\\sources\\iciss\\log\\log.txt"; private OutputStreamWriter outputStreamWriter; public OutputStreamWriter getOutputStreamWriter() { return outputStreamWriter; } public void setOutputStreamWriter(OutputStreamWriter outputStreamWriter) { this.outputStreamWriter = outputStreamWriter; } public InfoLogger() { try { File log =new File(logpath); if(!log.exists()){ log.createNewFile(); } FileOutputStream fileOutputStream = new FileOutputStream(log, true);//追加写入 outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8"); } catch (Exception e) { System.out.println("infolog文件打开错误\r\n" + e.toString() + "\r\n"); } } public void write(String event) { try { Date date = new Date(); DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time = format.format(date); outputStreamWriter.write(time + ": " + event + "\r\n"); outputStreamWriter.flush(); } catch (Exception e) { System.out.println("infolog文件写入错误\r\n" + e.toString() + "\r\n"); } } }
写了一个Servlethelp类用于存储数据库连接和2个日志,给servlet继承
package common; import javax.servlet.http.HttpServlet; /** * Created by PRO_HD_Rorz on 2015/7/29. */ public class Servlethelp extends HttpServlet { //protected Dbcon dbcon = new Dbcon("iciss","root",""); protected Dbcon dbcon = new Dbcon(); protected InfoLogger infologger = new InfoLogger(); protected ErrorLogger errorLogger = new ErrorLogger(); }
Intellij IDEA在创建新的servlet时好像不会自动在web.xml中增加配置,需要手动增加
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>iciss</display-name> <servlet> <servlet-name>Test</servlet-name> <servlet-class>servlet.Test</servlet-class> </servlet> <servlet-mapping> <servlet-name>Test</servlet-name> <url-pattern>/test</url-pattern> </servlet-mapping> <servlet> <servlet-name>Login</servlet-name> <servlet-class>servlet.Login</servlet-class> </servlet> <servlet-mapping> <servlet-name>Login</servlet-name> <url-pattern>/Login</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>
登陆处理,登陆后在服务器端的session中存储当前用户信息User。
其中response.sendRedirect可以重定向url
request.getRequestDispatcher(page).forward(request, response)则是由服务器来获取那个页面再转发给浏览器,不会改变url
package servlet; import common.Servlethelp; import common.User; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import java.util.Map; /** * Created by PRO_HD_Rorz on 2015/7/28. */ @WebServlet(name = "Login") public class Login extends Servlethelp { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String currEntity = "登陆"; response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); String username = ""; String password = ""; String page = "/Login.jsp"; HttpSession session = request.getSession(); try { username = request.getParameter("username"); password = request.getParameter("password"); username = ""; String sql = "select userid, password, role from users where username like '%?%'"; List re = dbcon.query(sql, username); if(re.size() >= 1) { if(((Map)re.get(0)).get("password").equals(password)) { page = "/test"; String userid = (String) ((Map)re.get(0)).get("userid"); String role = (String) ((Map)re.get(0)).get("role"); SaveToSession(session, userid, username, role); infologger.write(username + "\t" + currEntity); out.println("success"); return; } else { out.println("fail"); } } else { out.println("fail"); } } catch (Exception e) { errorLogger.write(currEntity + "\t" + e.toString()); } finally { RequestDispatcher rd = request.getRequestDispatcher(page); rd.forward(request, response); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } public void SaveToSession(HttpSession session, String userid, String username ,String role) { User user = new User(); user.setRole(role); user.setUserid(userid); user.setUsername(username); session.setAttribute("user", user); } }
登出则直接销毁那个session
package servlet; import common.Servlethelp; import common.User; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.io.PrintWriter; /** * Created by PRO_HD_Rorz on 2015/7/31. */ @WebServlet(name = "Logout") public class Logout extends Servlethelp { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String currEntity = "登出"; response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(); User currUser = (User) session.getAttribute("user"); String username = currUser.getUsername(); String userid = currUser.getUserid(); session.invalidate(); infologger.write(username + "\t" + currEntity); response.sendRedirect("Login.jsp"); } }
接收表单参数可以用String name = request.getParameter(“name”)
接收一个数组时则需要String name[] = request.getParameterValues(“name”);
获取DBcon返回的list时还需要转化为map
package servlet; import common.Servlethelp; import common.User; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.*; /** * Created by PRO_HD_Rorz on 2015/7/30. */ @WebServlet(name = "QuestionsManager") public class QuestionsManager extends Servlethelp { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String currEntity = "问题管理"; response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(); User currUser = (User) session.getAttribute("user"); String currname = currUser.getUsername(); String currid = currUser.getUserid(); String ques_id = UUID.randomUUID().toString(); String ref = request.getParameter("ref"); String ques = request.getParameter("ques"); int qtype = Integer.parseInt(request.getParameter("qtype")); String remark = request.getParameter("remark"); String help = request.getParameter("help"); String opt_dest[] = request.getParameterValues("opt_dest"); String opt_score[] = request.getParameterValues("opt_score"); String opt_lremark[] = request.getParameterValues("opt_lremark"); Map map = request.getParameterMap(); String sql1 = "insert into questionsdb values (?,?,?,?,?,?)"; int re1 = 0; try{ re1 = dbcon.update(sql1, ques_id, ref, ques, qtype, remark, help); } catch (Exception e) { out.println("fail"); } List re2 = new ArrayList(); String sql2 = "select ques_id from questionsdb where ref like ? and ques like ? and qtype = ? and remark like ? and help like ?"; try{ re2 = dbcon.query(sql2, ref, ques, qtype, remark, help); } catch (Exception e) { out.println("fail"); } if(re2.size() >= 1) { int quesid = Integer.parseInt((String) ((Map)re2.get(0)).get("ques_id")); int re3 = 0; String sql3 = "insert into optiondb values (NULL,?,?,?,?)"; for(int i=0 ; i<opt_dest.length ; i++ ) { try{ re3 = dbcon.update(sql3, quesid, opt_dest[i], opt_score[i], opt_lremark[i]); } catch (Exception e) { out.println("fail"); } if(re3 >= 1) { out.println("Success"); return; } else { out.println("fail"); } } } else { out.println("fail"); } out.println("fail"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
这里扔个test.jsp。实际上在tomcat上运行System.out.printIn会把内容打印到tomcat的log里(
<%@ page import="common.User" %> <%-- Created by IntelliJ IDEA. User: PRO_HD_Rorz Date: 2015/7/29 Time: 13:35 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <% String urole = ""; String uname = ""; if(session.getAttribute("user") != null) { urole = ((User)session.getAttribute("user")).getRole(); uname = ((User)session.getAttribute("user")).getUsername(); } else { response.sendRedirect("Login.jsp"); } System.out.println(session.getId()); System.out.println(uname); %> <html> <head> <title>test</title> </head> <body> <form action="test" method="get"> <input name="action" value="edit" type="hidden" hidden="hidden"> <input name="toadd" value="aaaa" type="text"> <input name="toadd" value="bbb" type="text"> <input name="toadd" value="cccc" type="text"> <input name="username" value="123" type="text"> <input name="password" value="111" type="text"> <input type="submit"> </form> <% out.println(uname); %> </body> </html>