RSS源显示采用开源的dtree项目进行二次开发。首先根据之前放入session中的uid获取当前用户的RSS分组数据,每获取到一个分组就根据该分组的gid获取属于该组内的的RSS源数据,然后将数据放入dtree中,依次循环直至获取到所有数据。最后由dtree根据获取到的数据按照树形样式显示出来。用户点击列表中的项目将会在右侧主框架中打开相应的文章列表。
主框架的文章列表:
主框架从左框架中发来的链接中提取feed参数中的url值,解析该url获取到相应文章列表。对url和xml文件的解析采用rss解析器(rome.jar和jdom.jar)进行解析获取相应数据。
同时,为了解决部分文章不支持在框架中打开,文章列表设计了在新窗口打开的选项。主要实现方法是:用户改变"在新窗口中打开"的选项的状态后,js立即将该选项状态写入Cookie并发送刷新请求。服务器根据Cookies值动态修改文章链接的target属性并向客户端发送新的页面。
文章内容显示:
文章内容未做任何处理直接显示原文,简单方便。但是有些文章不支持在框架中显示,这时需要勾选"在新窗口中打开"的选项,使文章在新开的浏览器窗口中显示。
RSS源的添加与管理:
添加分为添加源与添加分组,两个界面属于同一个弹窗,通过顶部tab切换,直观快捷。
添加源时需要提交:Feed地址、标题、分组。feed地址填写需要订阅的rss地址;标题可以从Feed地址中提取(具体实现方式为服务器获取到feed地址,根据feed地址解析出订阅标题,然后向客户端发送带有订阅标题的新页面);分组通过列表框选择用户已有的分组。客户端提交表单后,服务器获取到相应的信息并添加至数据库,然后返回成功信息;用户可再次添加新的源。
添加分组时只需要提交需要添加的分组名称即可。
管理界面属于新的弹窗,初始显示用户的所有分组,每个分组包含"展开"、"修改"和"删除"三个菜单。点击分组名或"展开"菜单将会跳转到该分组下的RSS源列表。RSS源列表与分组列表相识,每个分组包含"修改"与"删除"两个菜单。
修改时提交需要修改的项目,服务器根据获取到的gid、pd以及修改后的信息更新对应项目数据并返回相应提示。
删除时提交对应分组的gid或RSS源的pd,服务器根据获取到的id信息输出相应项目并返回提示。删除非空分组时将会删除该分组下所有RSS源(有提示)。
提示信息:
提示信息显示页面或根据获取到的参数显示相应的提示信息并在延迟特定时间后跳转到相应界面,参数为空时显示"未知错误"并跳转至主页。
网络安全补充
为了保护网站与用户数据安全,采取了一下辅助安全措施:
注册输入限制:
用户名只能为字母与数字的组合
密码长度太短
用户名限制为字母与数字组合,防止用户使用SQL语言中的符号进行SQL注入。密码长度限制为8~20位。太短,密码不安全;太长,用户可以通过密码框使用SQL注入攻击
使用过滤器防止SQL注入:
只通过表单的输入限制来防止SQL注入是远远不够的,用户依然可一使用URL参数的形式进行注入攻击。所以我在原项目中加入了一个过滤器来防护一些简单的SQL注入攻击。
该过滤器的原理是,截取用户的所有输入,检测是否是否包含特定关键词,有则重定向到一个错误信息页面error.jsp。没有则通过过滤器。
当然只是用过滤器是不能完全防护SQL注入攻击的,更有效的方式是项目中所有SQL语句都采用预编译语句(PreparedStatement)接口来实现【6】。
面对日益复杂的网络安全环境,以上的安全措施只是简单的做了一些防护,对于一个实际项目是远远不够的。在实际的项目还用采取更加严谨,更加有效的措施。
具体方法参考本文:JSP使用过滤器防止SQL注入
主要源代码
视图部分 /RSSreader/WebContent/rsscontent.jsp: <%@page contentType="text/html"%> <%@page pageEncoding="UTF-8" import="java.text.SimpleDateFormat"%> <html> <script language=javascript> function setCheck(){ var newWindow=document.getElementById("newWindow").value; if(newWindow==0) { document.getElementById("check").checked=true; } else { document.getElementById("check").checked=false; } } function check(){ var check=document.getElementById("check").checked; var feed=document.getElementById("feed").value; var url="rsscontent.jsp?feed="+feed; if(check) { document.cookie="newWindow=0"; } else { document.cookie="newWindow=1"; } self.location=url; } </script> <body> <% String pageTitle=""; String urlStr = request.getParameter("feed"); String target=""; Cookie cookies[]=request.getCookies(); //读出用户硬盘上的Cookie,并将所有的Cookie放到一个cookie对象数组里面 Cookie sCookie=null; for(int i=0;i<cookies.length;i++){ //用一个循环语句遍历刚才建立的Cookie对象数组 sCookie=cookies[i]; //取出数组中的一个Cookie对象 if(sCookie!=null){ if(("newWindow").equals(sCookie.getName())){ pageContext.setAttribute("newWindow",sCookie.getValue()); System.out.println(pageContext.getAttribute("newWindow")); } } } if(pageContext.getAttribute("newWindow")!=null) { if(pageContext.getAttribute("newWindow").equals("0")){ target="_blank"; } else{ target="_self"; } } try{ /* java.util.Properties systemSettings = System.getProperties(); systemSettings.put("http.proxyHost", "mywebcache.com"); systemSettings.put("http.proxyPort", "8080"); System.setProperties(systemSettings); */ if (!urlStr.startsWith("http://")) urlStr = "http://"+request.getParameter("feed"); //String urlStr = "http://feed.cnblogs.com/blog/u/249598/rss"; System.out.println(urlStr); java.net.URLConnection feedUrl = new java.net.URL(urlStr).openConnection(); feedUrl.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); com.sun.syndication.io.SyndFeedInput input = new com.sun.syndication.io.SyndFeedInput(); com.sun.syndication.feed.synd.SyndFeed feed = input.build(new com.sun.syndication.io.XmlReader(feedUrl)); pageTitle=feed.getTitle(); %> <div> <h1><%=pageTitle%></h1> <input type="hidden" value=https://www.jb51.net/<%=urlStr %>> <input type="hidden" value=<%=pageContext.getAttribute("newWindow")%>> <input type=checkbox>在新窗口中打开(部分网页不支持在框架中显示,请尝试勾选此项)</input> <table border=1 cellpadding=3 cellspacing="0"> <tr> <th>序号</th> <th>标题</th> <th>发布时间</th> </tr> <% String date="无"; java.util.List list = feed.getEntries(); for (int i=0; i< list.size(); i++) { com.sun.syndication.feed.synd.SyndEntry entry = (com.sun.syndication.feed.synd.SyndEntry)list.get(i); SimpleDateFormat sdf = new SimpleDateFormat(); sdf.applyPattern("yyyy年MM月dd日 HH:mm"); if(entry.getPublishedDate()!=null) { date=sdf.format(entry.getPublishedDate()); } %> <tr> <td><%=i+1%></td> <td><a href="https://www.jb51.net/<%=entry.getLink()%>" target=<%=target %>><%=entry.getTitle()%></a></td> <td><%=date %></td> </tr> <% } } catch (Exception e) { // TODO Auto-generated catch block response.sendRedirect("tips.jsp?type=rssContentfail"); e.printStackTrace(); } %> </table> </div> <br> </body> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title><%=pageTitle%></title> </head> </html> /RSSreader/WebContent/addGroup.jsp: <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" import="com.JDBConnection,java.sql.ResultSet,com.dataHelper,java.util.ArrayList"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>添加分组</title> <link href="https://www.jb51.net/css/tab.css" type="text/css" /> <script type="text/javascript" src="https://www.jb51.net/js/jquery.js"></script> </head> <% String lastAdd = request.getParameter("lastAdd"); String from = request.getParameter("from"); String tip=""; String backurl=""; String backname=""; if(lastAdd!=null){ String name =new String(request.getParameter("name").getBytes("ISO8859_1"), "utf-8"); if(lastAdd.equals("ture")){ tip="成功添加分组:"+name; } if(lastAdd.equals("false")){ tip="添加分组失败"; } } %> <body onunload="javascript:;window.opener.location.reload()"> <div> <div> <div><a href="https://www.jb51.net/addRss.jsp">添加源</a> | 添加分组</div> <form method="post" action="dealAddGroup"> <table> <tr> <td>组名:</td> <td> <input type="text" size="40"> <input type="hidden" value="<%=session.getAttribute("uid")%>"> </td> </tr> <tr> <td> </td> <td><%=tip %></td> </tr> <tr> <td> </td> <td><input type="submit" value="添加"></td> </tr> </table> </form> </div> </div> </body> </html> /RSSreader/WebContent/addRss.jsp: <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" import="com.JDBConnection,java.sql.ResultSet,com.dataHelper,java.util.ArrayList"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>添加RSS源</title> <link href="https://www.jb51.net/css/tab.css" type="text/css" /> <script type="text/javascript" src="https://www.jb51.net/js/jquery.js"></script> </head> <% String lastAdd = request.getParameter("lastAdd"); String title =""; String url =""; String tip=""; String Sgid=""; if(request.getParameter("title")!=null) { title=new String(request.getParameter("title").getBytes("ISO8859_1"), "utf-8"); } if(request.getParameter("url")!=null) { url=request.getParameter("url"); } if(request.getParameter("group")!=null) { Sgid=request.getParameter("group"); } if(lastAdd!=null){ String name =new String(request.getParameter("name").getBytes("ISO8859_1"), "utf-8"); if(lastAdd.equals("ture")){ tip="成功添加RSS源:"+name; } if(lastAdd.equals("false")){ tip="添加RSS源失败"; } } %> <body onunload="javascript:;window.opener.location.reload()"> <div> <div> <div>添加源 | <a href="https://www.jb51.net/addGroup.jsp">添加分组</a></div> <form method="post" action="dealAddRss"> <input type="hidden" value="addRss"> <table> <tr> <td>Feed地址:</td> <td><input type="text" size="40" value=https://www.jb51.net/<%=url %>></td> </tr> <tr> <td>标题:</td> <td> <input type="text" value=<%=title%>> <input type=button value=" 从feed中提取"> </td> </tr> <tr> <td>分组:</td> <td> <select> <% int gid; String gname; int uid; Object memo; int i; dataHelper dhp=new dataHelper(); ArrayList<dataHelper.Group> groupList =dhp.getGroup((Integer)session.getAttribute("uid")); for(i=0;i<groupList.size();i++) { dataHelper.Group group=groupList.get(i); %> <option value="<%=group.getGid()%>"><%=group.getGname()%></option> <% } %> </select> </td> </tr> <tr> <td> </td> <td><%=tip %></td> </tr> <tr> <td> </td> <td><input type="submit" value="添加"></td> </tr> </table> </form> </div> <div> </div> </div> </body> </html> /RSSreader/WebContent/delete.jsp: <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" import="com.JDBConnection,java.sql.ResultSet"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; utf-8"> <title>editGroup</title> </head> <body> <div> <% String name=(String)session.getAttribute("name"); String nickname=""; if(name==null) { response.sendRedirect("index.jsp"); } %> <% String gid =request.getParameter("gid"); String lid =request.getParameter("lid"); String type =request.getParameter("type"); String url=""; //DELETE FROM 表名称 WHERE 列名称 = 值 String sSql=""; if(type!=null){ if(type.equals("g")){ sSql="delete from rssGroup where gid="+gid; url="manage.jsp"; } if(type.equals("r")){ sSql="delete from rssList where lid="+lid; url="rssListOfGroup.jsp?gid="+gid; } } System.out.println("rssListOfGroup.Sql:"+sSql); JDBConnection JDBC=new JDBConnection(); if(JDBC.executeUpdate(sSql)){ out.print("删除成功"); } else{ out.print("删除失败"); } %> </div> <br> <div> <a href=https://www.jb51.net/<%=url %>>返回</a> </div> </body> </html> JAVA部分 /RSSreader/src/com/JDBConnection.java package com; import java.sql.*; public class JDBConnection { private final String url = "jdbc:sqlserver://localhost:1433;DatabaseName=RSSreader"; private final String userName = "sa"; private final String password = "123456"; private Connection con = null; //通过构造方法加载数据库驱动 static { try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch (Exception ex) { System.out.println("数据库加载失败"); } } //创建数据库连接 public boolean creatConnection() { try { con = DriverManager.getConnection(url, userName, password); con.setAutoCommit(true); } catch (SQLException e) { System.out.println(e.getMessage()); System.out.println("creatConnectionError!"); } return true; } public void close(Connection con,Statement stmt,PreparedStatement pst,ResultSet rs){ if(rs!=null){ try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(stmt!=null){ try { stmt.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(pst!=null){ try { pst.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(con!=null){ try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void closeConnection(){ if(con!=null){ try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } //对数据库的增加、修改和删除的操作 public boolean executeUpdate(String sql) { if (con == null) { creatConnection(); } try { Statement stmt = con.createStatement(); int iCount = stmt.executeUpdate(sql); System.out.println("操作成功,所影响的记录数为" + String.valueOf(iCount)); this.close(con, stmt,null, null); return true; } catch (SQLException e) { System.out.println(e.getMessage()); return false; } } //对数据库的查询操作 public ResultSet executeQuery(String sql) { ResultSet rs; try { if (con == null) { creatConnection(); } Statement stmt = con.createStatement(); try { rs = stmt.executeQuery(sql); } catch (SQLException e) { System.out.println(e.getMessage()); return null; } } catch (SQLException e) { System.out.println(e.getMessage()); System.out.println("executeQueryError!"); return null; } return rs; } } /RSSreader/src/com/SqlFilter.java package com; import java.io.IOException; import java.util.Enumeration; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //过滤sql关键字的Filter public class SqlFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; //获得所有请求参数名 Enumeration params = req.getParameterNames(); String sql = ""; while (params.hasMoreElements()) { //得到参数名 String name = params.nextElement().toString(); //System.out.println("name===========================" + name + "--"); //得到参数对应值 String[] value = req.getParameterValues(name); for (int i = 0; i < value.length; i++) { sql = sql + value[i]; } } System.out.println("被匹配字符串:"+sql); if (sqlValidate(sql)) { res.sendRedirect("error.jsp"); } else { chain.doFilter(req, res); } } //效验 protected static boolean sqlValidate(String str) { str = str.toLowerCase();//统一转为小写 //String badStr = "and|exec"; String badStr = "'|and|exec|execute|insert|select|delete|update|count|drop|chr|mid|master|truncate|char|declare|sitename|net user|xp_cmdshell|or|like"; /*String badStr = "'|and|exec|execute|insert|create|drop|table|from|grant|use|group_concat|column_name|" + "information_schema.columns|table_schema|union|where|select|delete|update|order|by|count|*|" + "chr|mid|master|truncate|char|declare|or|;|-|--|+|,|like|//|/|%|#"; */ //过滤掉的sql关键字,可以手动添加 String[] badStrs = badStr.split("\\|"); for (int i = 0; i < badStrs.length; i++) { if (str.indexOf(badStrs[i]) !=-1) { System.out.println("匹配到:"+badStrs[i]); return true; } } return false; } public void init(FilterConfig filterConfig) throws ServletException { //throw new UnsupportedOperationException("Not supported yet."); } public void destroy() { //throw new UnsupportedOperationException("Not supported yet."); } } /RSSreader/src/dataCtrl/addGroup.java package dataCtrl; import com.JDBConnection; public class addGroup { private String gname; private String uid; public String getGname() { return gname; } public void setGname(String gname) { this.gname = gname; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public boolean doAddGroup(){ String sSql = "insert into rssGroup(gname,uid) values('"+gname+"',"+uid+")"; System.out.println(sSql); JDBConnection JDBC=new JDBConnection(); return JDBC.executeUpdate(sSql); } } /RSSreader/src/dataCtrl/addRss.java package dataCtrl; import java.sql.*; import com.JDBConnection; import javafx.beans.property.adapter.JavaBeanProperty; public class addRss { private String title; private String url; private String gid; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getGid() { return gid; } public void setGid(String gid) { this.gid = gid; } public boolean doAddRss() throws SQLException{ //INSERT INTO table_name (列1, 列2,...) VALUES (值1, 值2,....); String sSql = "insert into rssList(title,url,gid) values('"+title+"','"+url+"',"+gid+")"; System.out.println(sSql); JDBConnection JDBC=new JDBConnection(); return JDBC.executeUpdate(sSql); } } /RSSreader/src/dataCtrl/dealaddGroup.java package dataCtrl; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class dealaddGroup */ @WebServlet("/dealaddGroup") public class dealaddGroup extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public dealaddGroup() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String gname=request.getParameter("gname"); String sgname =new String(gname.getBytes("ISO8859_1"), "utf-8"); String uid=request.getParameter("uid"); addGroup adgp=new addGroup(); adgp.setGname(sgname); adgp.setUid(uid); if(adgp.doAddGroup()){ request.getRequestDispatcher("/addGroup.jsp?name="+gname+"&lastAdd=ture").forward(request,response); //response.sendRedirect("index.jsp"); } else{ request.getRequestDispatcher("/addGroup.jsp?name="+gname+"&lastAdd=false").forward(request,response); } doGet(request, response); } } /RSSreader/src/dataCtrl/dealAddRss.java package dataCtrl; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class dealAddRss1 */ @WebServlet("/dealAddRss1") public class dealAddRss extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public dealAddRss() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //response.setContentType("text/html;charset=utf-8"); String title=request.getParameter("title"); String stitle =new String(title.getBytes("ISO8859_1"), "utf-8"); String url =request.getParameter("url"); String gid=request.getParameter("group"); addRss adrs=new addRss(); adrs.setTitle(stitle); adrs.setUrl(url); adrs.setGid(gid); try { if(adrs.doAddRss()){ request.getRequestDispatcher("/addRss.jsp?name="+title+"&lastAdd=ture").forward(request,response); //response.sendRedirect("index.jsp"); } else{ request.getRequestDispatcher("/addRss.jsp?name="+title+"&lastAdd=false").forward(request,response); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } doGet(request, response); } } /RSSreader/src/dataCtrl/getFeedTitle.java package dataCtrl; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.sun.syndication.io.FeedException; /** * Servlet implementation class getFeedTitle */ @WebServlet("/getFeedTitle") public class getFeedTitle extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public getFeedTitle() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String urlStr =request.getParameter("url"); String title=""; String gid=request.getParameter("group"); String lid=request.getParameter("lid"); String Lastgid=request.getParameter("Lastgid"); String from=request.getParameter("from"); if (!urlStr.startsWith("http://")) urlStr = "http://"+request.getParameter("feed"); //String urlStr = "http://feed.cnblogs.com/blog/u/249598/rss"; System.out.print(urlStr); java.net.URLConnection feedUrl = new java.net.URL(urlStr).openConnection(); feedUrl.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); com.sun.syndication.io.SyndFeedInput input = new com.sun.syndication.io.SyndFeedInput(); com.sun.syndication.feed.synd.SyndFeed feed; try { feed = input.build(new com.sun.syndication.io.XmlReader(feedUrl)); title=feed.getTitle(); } catch (IllegalArgumentException | FeedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(from.equals("addRss")){ response.sendRedirect("addRss.jsp?title="+title+"&url="+urlStr+"&group="+gid+"&Lastgid="+Lastgid+"&lid="+lid); } if(from.equals("editRss")){ response.sendRedirect("editRss.jsp?title="+title+"&url="+urlStr+"&group="+gid+"&Lastgid="+Lastgid+"&lid="+lid); } doGet(request, response); } } /RSSreader/src/loginCtrl/checkUser.java package loginCtrl; import java.sql.ResultSet; import java.sql.SQLException; import com.JDBConnection; public class checkUser { private int uid=0; private String; private String pwd=" "; public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public boolean check() { String sPwd=""; String sSql = "select * from users where uname='"+name+"'"; System.out.println(sSql); try { JDBConnection JDBC=new JDBConnection(); ResultSet rs =JDBC.executeQuery(sSql); System.out.println(rs.isBeforeFirst()); if(rs.next()) { System.out.println("?"); sPwd=rs.getString("upwd"); uid=rs.getInt("uid"); //System.out.println(sPwd); JDBC.closeConnection(); } } catch (SQLException e) { // TODO Auto-generated catch block System.out.println(e.getMessage()); System.out.println("ConnectError!"); } System.out.println(name+"-"+pwd+"-"+sPwd); if(pwd.equals(sPwd)) { return true; } else { return false; } } } /RSSreader/src/loginCtrl/dealsignup.java package loginCtrl; import java.io.IOException; import java.sql.Connection; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet implementation class dealsignup */ @WebServlet("/dealsignup") public class dealsignup extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public dealsignup() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html;charset=utf-8"); String name =request.getParameter("account"); String url =request.getParameter("url"); String nickname =request.getParameter("nickname"); if (nickname==null||nickname=="") nickname=null; else nickname=new String(request.getParameter("nickname").getBytes("ISO8859_1"), "utf-8"); String pwd= request.getParameter("password"); String enpwd= request.getParameter("ensurepassword"); signup snp=new loginCtrl.signup(); System.out.println("dealsingnup:"+name+"-"+nickname+"-"+pwd+"-"+enpwd); if(!pwd.equals(enpwd)) { response.sendRedirect("tips.jsp?type=signupwithwrongpwd"); System.out.println("两次密码不一致"); } else { snp.setName(name); snp.setNickname(nickname); snp.setPwd(pwd); Connection conn=snp.connect(); if(snp.signupcheck(conn)) { if(snp.dosignup(conn)) { response.sendRedirect("tips.jsp?type=signupsuccess&str="+name); System.out.println("注册成功"); } else { response.sendRedirect("tips.jsp?type=sinupfail"); System.out.println("未知错误"); } } else { response.sendRedirect("tips.jsp?type=usernamevalid"); System.out.println("用户名已被注册"); } snp.closeConnection(conn); } doGet(request, response); } } /RSSreader/src/loginCtrl/loginCheck.java package loginCtrl; import java.io.IOException; import java.sql.ResultSet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.JDBConnection; /** * Servlet implementation class loginCheck */ @WebServlet("/loginCheck") public class loginCheck extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public loginCheck() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String name =request.getParameter("account"); String pwd= request.getParameter("password"); checkUser uc=new loginCtrl.checkUser(); System.out.println(name+"-"+pwd); uc.setName(name); uc.setPwd(pwd); if(uc.check()) { HttpSession session=request.getSession(); session.setAttribute("name", name); session.setAttribute("uid", uc.getUid()); response.sendRedirect("index.jsp"); } else { response.sendRedirect("tips.jsp?type=logfail"); } doGet(request, response); } } /RSSreader/src/loginCtrl/signup.java package loginCtrl; import java.sql.*; public class signup { private String; private String nickname=""; private String pwd=" "; private Connection conn; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public Connection connect() { try { String JDriver="com.microsoft.sqlserver.jdbc.SQLServerDriver";//SQL数据库引擎 String connectDB= "jdbc:sqlserver://localhost:1433;DatabaseName=RSSreader";//数据源 try { Class.forName(JDriver);//加载数据库引擎,返回给定字符串名的类 }catch(ClassNotFoundException e) { //e.printStackTrace(); System.out.println("加载数据库引擎失败:"+e); System.exit(0); } System.out.println("数据库驱动成功"); String user="sa"; String password="123456"; conn=DriverManager.getConnection(connectDB,user,password);//连接数据库对象 System.out.println("连接数据库成功"); } catch(Exception e) { System.out.println("链接数据库失败:"+e); } return conn; } public boolean signupcheck(Connection conn) { try{ Statement stmt=conn.createStatement(); ResultSet rs=stmt.executeQuery("select * from users where uname='"+name+"'"); if(!rs.next()) return true; } catch(Exception e) { System.out.println("查询失败"+e); return false; } return false; } public boolean dosignup(Connection conn) { try { PreparedStatement ps = conn.prepareStatement("insert into users (uname,nickname,upwd) values(?,?,?)"); ps.setString(1, name); ps.setString(2, nickname); ps.setString(3, pwd); int num =ps.executeUpdate(); System.out.println(num); if (num==0) return false; ps.close(); } catch(Exception e) { System.out.println("添加失败"+e); return false; } return true; } public boolean closeConnection(Connection conn) { try { System.out.println("关闭链接成功"); conn.close(); } catch(Exception e) { System.out.println("关闭链接失败"+e); return false; } return true; } }
阅读器使用说明
注册与登录