1. 程式人生 > >實驗7 JSP

實驗7 JSP

設計一個簡單的基於Web的留言板,要求:1)系統中所有頁面,如果使用者沒登入,則讓使用者返回到登入頁面login.jsp(說明:login.jsp頁面填寫使用者的使用者名稱和密碼);2)留言板(message.jsp)頁面中以表格的形式(留言者使用者名稱、留言標題、留言時間)顯示出所有的使用者留言,點選一個標題後,可以在新頁面(showmessage.jsp)中顯示留言的內容;3)在留言頁面addMessage.jsp可以新增新的留言。留言包括:標題、內容。

說明:(1)採用JSP+JavaBean結構;(2)所有的留言內容需要儲存到伺服器的檔案中。

Login.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>登入</title>
<link rel="stylesheet" href="css/amazeui.min.css">
  <link rel="stylesheet" href="css/app.css">
</head>
<body background="img/5.jpg"
	style="background-repeat: no-repeat; background-size: cover; background-attachment: fixed;"
	text="#68228B" >
	<div class="am-g myapp-login">
		 <div class="myapp-login-logo">
		 	<i class="am-icon-stumbleupon"></i>
		 </div>
		 <div class="am-u-sm-10 myapp-login-form">
		 	<form class="am-form" action="LoginServe" method="POST">
			    <div class="am-form-group">
			      <input type="text"  value="請輸入使用者名稱 " name="id">
			    </div>
			    <div class="am-form-group">
			      <input type="password" value="123456" name="password">
			    </div> 
			      <p style="color:green">預設密碼為123456</p>
			    <p><button type="submit" class="am-btn am-btn-default">Login</button></p>

			</form>
		 </div>
	</div>
</body>
</html>

message.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8" %>

<%@page import="java.util.*,com.whh.www.*" %>
<%! String id;
	String title;
	Date time;
%>
<!DOCTYPE html>
<html>
<head>
<title>主介面</title>
</head>
<body>
	<!-- <form  action="" method="post"> -->
  		<table >
  			<caption>所有留言資訊</caption>
  			<tr><th>留言ID</th><th>留言時間</th>
				<th>留言標題</th></tr>
  		 <%
  		if(messageRecord.record!=null){
  			Iterator iter=messageRecord.record.iterator();
  			while(iter.hasNext()){
  				Mess mb=(Mess)iter.next();
				
  		%><tr><td><%=mb.getId() %></td>
  					<td><%= mb.getTime() %></td>
  					<td><a href="showMessage.jsp?number=<%= mb.getNumber()%>"><%= mb.getTitle() %></a></td>
  		<%	}
  		} %> 
  		</table>
  		<br>
  		<%if(request.getSession().getAttribute("id")==null){
  			response.sendRedirect("Login.jsp");
  		}
  		%>
  		<br>
  		<br>
  	<!-- </form> -->
  	  	<a style="margin-left:22%" href="addmessage.jsp">留言</a>
</body>
</html>

addmessage.jsp

<%@ page language="java"  contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>留言</title>
</head>
<body>
	 <h1 >請留言</h1>
   <form action="leaveMessageServlet" method="post">
  			<table style="margin-left: 37%" border="1">
  			<caption>填寫留言資訊</caption>
  		    	<tr><td>留言標題</td>
  				<td><input type="text" name="title"/></td></tr>
  			<tr><td>留言內容</td>
  				<td><textarea name="message" rows="5" cols="35"></textarea></td>
			</tr>
  			</table>
  		<input type="submit" value="提交"/>
  		<input type="reset" value="重置"/>
  	</form>
    <a href="message.jsp">返回留言板介面</a>
</body>
</html>

showmessage.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
    <%@page import="java.util.*,com.whh.www.*" %>
<!DOCTYPE html>
<html>
<head>
<%
if(request.getSession().getAttribute("id")==null){
		response.sendRedirect("Login.jsp");
}
%>
<title><%=messageRecord.mp.get(Integer.parseInt(request.getParameter("number"))).getTitle() %></title>
</head>
<body>
	標題:<%=messageRecord.mp.get(Integer.parseInt(request.getParameter("number"))).getTitle() %>
	<br>
	<br>
	內容:<%=messageRecord.mp.get(Integer.parseInt(request.getParameter("number"))).getMessage()%>
</body>
</html>

success.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>

<title>Success</title>
</head>
<body>
	<div style="margin-left:42%;margin-top:240px;font-family:Microsoft YaHei" >
		留言成功,單擊<a href="message.jsp">這裡</a>返回主介面。
	</div>

</body>
</html>

error.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Error</title>
</head>
<body>
	 <body bgcolor="#ddd" style="font-family:Microsoft YaHei">
  <div style="text-align:center;margin-top:130px">
    <p>輸入的使用者名稱不存在或者密碼錯誤</p>
    <a href="Login.jsp">點我返回登陸介面</a>
    </div>
</body>
</html>

LoginServlet

package com.whh.www;


import java.io.*;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

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 LoginServe
 */
@WebServlet("/LoginServe")
public class LoginServe extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	Map<String,String> mp=new HashMap<String,String>();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServe() {
        super();
        // TODO Auto-generated constructor stub
    }
    public void init() {
    	@SuppressWarnings("resource")
		String path=this.getServletContext().getRealPath("/WEB-INF/user.txt");
    	String path2=this.getServletContext().getRealPath("/WEB-INF/message.txt");
		InputStreamReader fis = null,fis2=null;
		try {
			fis = new InputStreamReader(new FileInputStream(path));
			fis2= new InputStreamReader(new FileInputStream(path2));
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} 
		BufferedReader in=new BufferedReader(fis);
		BufferedReader ins=new BufferedReader(fis2);
		String a[]=new String[3];
		String b[]=new String[5];
    	String line = null;
    	while(true) {
    		try {
				line=in.readLine();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    		if(line==null)break;
    		a=line.split("#");
    		mp.put(a[0],a[1]);
    	}
    	while(true) {
    		try {
				line=ins.readLine();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    		if(line==null)break;
    		b=line.split("#");
    		Mess mb=new Mess();
    		mb.setId(b[0]);
    		mb.setTime(b[1]);
    		mb.setTitle(b[2]);
    		mb.setMessage(b[3]);
    		mb.setNumber(Integer.parseInt(b[4]));
    		messageRecord.mp.put(mb.getNumber(),mb);
    	}
    	try {
			in.close();
			ins.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String id="";
		id=request.getParameter("id");
		String password=request.getParameter("password");
		String s="";
		if(mp.containsKey(id)) {
			if(mp.get(id).equals(password)) {
				s+=mp.get(id);
			}
		}
		if(s!="") {
			request.getSession().setAttribute("id", id);
			request.getRequestDispatcher("message.jsp").forward(request,response); 
		}
		else response.sendRedirect("Error.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

leaveMessageServlet

package com.whh.www;


import java.io.IOException;
import java.util.Date;

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 leaveMessageServlet
 */
@WebServlet("/leaveMessageServlet")
public class leaveMessageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public leaveMessageServlet() {
        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
		request.setCharacterEncoding("utf-8");
		String id=(String) request.getSession().getAttribute("id");
		String title=request.getParameter("title");
		String message=request.getParameter("message");
		Mess mb=new Mess();
		mb.setId(id);
		mb.setTime(new Date(System.currentTimeMillis()).toString());
		mb.setTitle(title);
		mb.setMessage(message);
		messageRecord.add(mb);
		String path=this.getServletContext().getRealPath("/WEB-INF/message.txt");
		System.out.println(path);
		if(save.Save(mb,path)) {
			request.getSession().setAttribute("mb", mb);
			response.sendRedirect("success.jsp") ;
		}
		else response.sendRedirect("message.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

Mess

package com.whh.www;


public class Mess {
	private int number;
	private String id;
	private String title;
	private String time;
	private String message;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	public String getTime() {
		return time;
	}
	public void setTime(String time) {
		this.time = time;
	}
	public int getNumber() {
		return number;
	}
	public void setNumber(int number) {
		this.number = number;
	}
}

save

package com.whh.www;

import java.io.*;
public class save {
	public static boolean Save(Mess mb,String path) throws IOException {
		String id=mb.getId();
		String title=mb.getTitle();
		String message=mb.getMessage();
		String time=mb.getTime();
		int number=mb.getNumber();
		try {
			PrintWriter out=new PrintWriter(new FileWriter(path,true));
			out.println(id+"#"+time+"#"+title+"#"+message+"#"+number);
			out.close();
			return true;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}
}

messageRecord

package com.whh.www;
import java.util.*;

public class messageRecord {
	public static ArrayList<Mess> record=new ArrayList<Mess>();
	public static Map<Integer,Mess>mp=new HashMap<Integer,Mess>();
	private static int count=0;
	public static void add(Mess mb) {
		count++;
		record.add(mb);
		mb.setNumber(count);
		mp.put(count, mb);
	}
}