web 小项目 在线书签的安全问题

本文介绍如何在 Eclipse Java EE IDE for Web Developers 中配置 Web 项目,包括解决常见的 servlet 编写错误、配置 tomcat 和端口冲突问题,并通过示例展示了如何实现书签的安全登录功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注意事项:

在使用:

Eclipse Java EE IDE for Web Developers.

Version: Indigo Service Release 1

Build id: 20110916-0149

(c) Copyright Eclipse contributors and others 2005, 2011. All rights reserved.

Visit http://www.eclipse.org/webtools

来开发软件:

在编写servlet 时会出错时我们这样的做:

在 java Build Path 里找到 Libraries

Add library server runnrime

1、 测试tomcat工作是否正常
运行tomcat安装目录下startup.bat,如果tomcat输出控制台有错误或者运行完后由于错误导致其窗口自

动关闭,表示tomcat运行时不正常的。如果在这之前我们的程序运行时正常的,而且我们没有做太多的程

序改动,那么很有可能是tomcat或者jsp运行中出现了未知错误。我们可以重新启动电脑试一下。大部分

情况下都是可以通过这种方式解决的。
2、测试8080端口是否被占用导致
假如在步骤1中tomcat运行时没有报错,那么我们可以修改server.xml文件中的8080端口为其它端口试一

下。

Bookmarkonline 的安全登录

package cc.openhome.controller;

import cc.openhome.model.Bookmark;

import cc.openhome.model.BookmarkService;

import java.io.IOException;

import java.util.ArrayList;

import java.util.List;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class AddBookmark extends HttpServlet {

private String SUCCESS_VIEW = "success.view";

private String ERROR_VIEW = "error.view";

@Override

public void init() throws ServletException {

super.init();

if(this.getInitParameter("SUCCESS") != null) {

SUCCESS_VIEW = this.getInitParameter("SUCCESS");

}

if(this.getInitParameter("ERROR") != null) {

ERROR_VIEW = this.getInitParameter("ERROR");

}

}

@Override

protected void doPost(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

request.setCharacterEncoding("UTF-8");

String url = request.getParameter("url");

String title = request.getParameter("title");

String category = request.getParameter("category");

String newCategory = request.getParameter("newCategory");

List<String> errors = new ArrayList<String>();

if (url == null || url.length() == 0) {

errors.add("网址不能空白");

}

if (title == null || title.length() == 0) {

errors.add("请输入网页标题");

}

if ((category == null || category.length() == 0) &&

(newCategory == null || newCategory.length() == 0)) {

errors.add("请设置网页分类");

}

if (errors.size() != 0) {

request.setAttribute("errors", errors);

request.getRequestDispatcher(ERROR_VIEW)

.forward(request, response);

} else {

url = url.trim();

title = title.trim();

if(newCategory != null) {

newCategory = newCategory.trim();

if(newCategory.length() != 0) {

category = newCategory;

}

}

else {

category = category.trim();

}

Bookmark bookmark = new Bookmark(url, title, category);

BookmarkService bookmarkService = (BookmarkService)

getServletContext().getAttribute("bookmarkService");

bookmarkService.addBookmark(bookmark);

request.setAttribute("bookmark", bookmark);

request.getRequestDispatcher(SUCCESS_VIEW)

.forward(request, response);

}

}

}

package cc.openhome.model;

public class Bookmark {

private String url;

private String title;

private String category;

public Bookmark() {

}

public Bookmark(String url, String title, String category) {

this.url = url;

this.title = title;

this.category = category;

}

public String getCategory() {

return category;

}

public void setCategory(String category) {

this.category = category;

}

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;

}

}

package cc.openhome.model;

import java.io.*;

import java.util.*;

import java.util.logging.*;

public class BookmarkService {

private String filename;

private List<Bookmark> bookmarks;

private List<String> categories;

public BookmarkService(String filename) {

this.filename = filename;

BufferedReader reader = null;

try {

reader = new BufferedReader(

new InputStreamReader(

new FileInputStream(filename), "UTF-8"));

bookmarks = new LinkedList<Bookmark>();

categories = new LinkedList<String>();

String input = null;

while ((input = reader.readLine()) != null) {

String[] tokens = input.split(",");

Bookmark bookmark =

new Bookmark(tokens[0], tokens[1], tokens[2]);

bookmarks.add(bookmark);

if(!categories.contains(tokens[2])) {

categories.add(tokens[2]);

}

}

} catch (IOException ex) {

Logger.getLogger(BookmarkService.class.getName())

.log(Level.SEVERE, null, ex);

} finally {

try {

reader.close();

} catch (IOException ex) {

Logger.getLogger(BookmarkService.class.getName())

.log(Level.SEVERE, null, ex);

}

}

}

public List<Bookmark> getBookmarks() {

return bookmarks;

}

public List<String> getCategories() {

return categories;

}

public List<Bookmark> addBookmark(Bookmark bookmark) {

BufferedWriter writer = null;

try {

writer = new BufferedWriter(new OutputStreamWriter(

new FileOutputStream(filename, true), "UTF-8"));

writer.write(bookmark.getUrl() + "," + bookmark.getTitle() +

"," + bookmark.getCategory()

+ System.getProperty("line.separator"));

this.getBookmarks().add(bookmark);

if (!categories.contains(bookmark.getCategory())) {

categories.add(bookmark.getCategory());

}

} catch (IOException ex) {

Logger.getLogger(BookmarkService.class.getName())

.log(Level.SEVERE, null, ex);

} finally {

try {

writer.close();

} catch (IOException ex) {

Logger.getLogger(BookmarkService.class.getName())

.log(Level.SEVERE, null, ex);

}

}

return this.getBookmarks();

}

}

package cc.openhome.web;

import cc.openhome.model.BookmarkService;

import javax.servlet.*;

public class BookmarkInitializer implements ServletContextListener {

public void contextInitialized(ServletContextEvent sce) {

ServletContext context = sce.getServletContext();

String bookmarkFile = context.getInitParameter("BOOKMARK");

BookmarkService bookmarkService = new BookmarkService(

this.getClass().getClassLoader()

.getResource("../" + bookmarkFile).getFile());

context.setAttribute("bookmarkService", bookmarkService);

}

public void contextDestroyed(ServletContextEvent sce) {

}

}

/*

* To change this template, choose Tools | Templates

* and open the template in the editor.

*/

package cc.openhome.web;

import java.io.*;

import java.util.*;

import java.util.logging.Level;

import java.util.logging.Logger;

import javax.servlet.*;

import javax.servlet.http.*;

public class CharacterFilter implements Filter {

private Map<String, String> escapeMap;

public void init(FilterConfig filterConfig)

throws ServletException {

BufferedReader reader = null;

try {

String escapeListFile = filterConfig

.getInitParameter("ESCAPE_LIST");

reader = new BufferedReader(

new InputStreamReader(

filterConfig.getServletContext()

.getResourceAsStream(escapeListFile)));

String input = null;

escapeMap = new HashMap<String, String>();

while ((input = reader.readLine()) != null) {

String[] tokens = input.split("\t");

escapeMap.put(tokens[0], tokens[1]);

}

} catch (IOException ex) {

Logger.getLogger(CharacterFilter.class.getName())

.log(Level.SEVERE, null, ex);

}

finally {

try {

reader.close();

} catch (IOException ex) {

Logger.getLogger(CharacterFilter.class.getName())

.log(Level.SEVERE, null, ex);

}

}

}

public void doFilter(ServletRequest request, ServletResponse response,

FilterChain chain) throws IOException, ServletException {

HttpServletRequest requestWrapper =

new CharacterRequestWrapper(

(HttpServletRequest) request, escapeMap);

chain.doFilter(requestWrapper, response);

}

public void destroy() {

}

}

package cc.openhome.web;

import java.util.*;

import javax.servlet.http.*;

import javax.servlet.http.HttpServletRequestWrapper;

public class CharacterRequestWrapper extends HttpServletRequestWrapper {

private Map<String, String> escapeMap;

public CharacterRequestWrapper(HttpServletRequest request,

Map<String, String> escapeMap) {

super(request);

this.escapeMap = escapeMap;

}

@Override

public String getParameter(String name) {

return doEscape(this.getRequest().getParameter(name));

}

private String doEscape(String parameter) {

if(parameter == null) {

return null;

}

String result = parameter;

Iterator<String> iterator = escapeMap.keySet().iterator();

while (iterator.hasNext()) {

String origin = iterator.next();

String escape = escapeMap.get(origin);

result = result.replaceAll(origin, escape);

}

return result;

}

}

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<title>添加书签</title>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

</head>

<body>

<c:if test="${requestScope.errors != null}">

<h1>添加书签失败</h1>

<ul style="color: rgb(255, 0, 0);">

<c:forEach var="error" items="${requestScope.errors}">

<li>${error}</li>

</c:forEach>

</ul>

</c:if>

<form method="post" action="add.do">

网址&nbsp;http:// <input name="url" value="${param.url}"><br>

网页名称:<input name="title" value="${param.title}"><br>

分  类:<select name="category">

<c:forEach var="category"

items="${applicationScope.bookmarkService.categories}">

<option value="${category}">${category}</option>

</c:forEach>

</select>

添加分类:<input type="text" name="newCategory" value=""><br>

<input value="送出" type="submit"><br>

</form>

</body>

</html>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!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>

</head>

<body>

<table style="text-align: left; width: 100%;" border="0">

<tbody>

<tr>

<td style="background-color: rgb(51, 255, 255);">网页</td>

<td style="background-color: rgb(51, 255, 255);">分类</td>

</tr>

<c:forEach var="bookmark"

items="${applicationScope.bookmarkService.bookmarks}">

<tr>

<td>

<a href="http://${bookmark.url}">${bookmark.title}</a>

</td>

<td>${bookmark.category}</td>

</tr>

</c:forEach>

</tbody>

</table>

</body>

</html>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<title>登录</title>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

</head>

<body>

<form action="j_security_check" method="post">

名称:<input type="text" name="j_username"><br>

密码:<input type="password" name="j_password"><br><br>

<input type="submit" value="登录">

</form>

</body>

</html>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!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>

</head>

<body>

<h1>添加书签成功</h1>

<ul>

<li>网址:http:// ${requestScope.bookmark.url} </li>

<li>名称:${requestScope.bookmark.title}</li>

<li>分类:${requestScope.bookmark.category}</li>

</ul>

<a href="index.html">返回首页</a>

</body>

</html>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<title>登录</title>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

</head>

<body>

<form action="j_security_check" method="post">

名称:<input type="text" name="j_username"><br>

密码:<input type="password" name="j_password"><br><br>

<input type="submit" value="登录">

</form>

</body>

</html>

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<context-param>

<param-name>BOOKMARK</param-name>

<param-value>bookmarks.txt</param-value>

</context-param>

<filter>

<filter-name>CharacterFilter</filter-name>

<filter-class>cc.openhome.web.CharacterFilter</filter-class>

<init-param>

<param-name>ESCAPE_LIST</param-name>

<param-value>/WEB-INF/escapelist.txt</param-value>

</init-param>

</filter>

<filter-mapping>

<filter-name>CharacterFilter</filter-name>

<url-pattern>/add.do</url-pattern>

</filter-mapping>

<listener>

<listener-class>cc.openhome.web.BookmarkInitializer</listener-class>

</listener>

<servlet>

<servlet-name>AddBookmark</servlet-name>

<servlet-class>cc.openhome.controller.AddBookmark</servlet-class>

<init-param>

<param-name>SUCCESS</param-name>

<param-value>success.jsp</param-value>

</init-param>

<init-param>

<param-name>ERROR</param-name>

<param-value>add.jsp</param-value>

</init-param>

</servlet>

<servlet-mapping>

<servlet-name>AddBookmark</servlet-name>

<url-pattern>/add.do</url-pattern>

</servlet-mapping>

<session-config>

<session-timeout>

30

</session-timeout>

</session-config>

<welcome-file-list>

<welcome-file>index.html</welcome-file>

</welcome-file-list>

<security-constraint>

<web-resource-collection>

<web-resource-name>Login Required</web-resource-name>

<url-pattern>*.jsp</url-pattern>

<url-pattern>/add.do</url-pattern>

</web-resource-collection>

<auth-constraint>

<description/>

<role-name>admin</role-name>

</auth-constraint>

</security-constraint>

<login-config>

<auth-method>FORM</auth-method>

<realm-name/>

<form-login-config>

<form-login-page>/login.html</form-login-page>

<form-error-page>/login.html</form-error-page>

</form-login-config>

</login-config>

<security-role>

<role-name>admin</role-name>

</security-role>

</web-app>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值