JavaWeb Experiment (2019 Summer) – Day2

目标要求:

  1. User类、Diary类、CityMap类、MyPagination的编写
  2. 过滤器的编写与配置
  3. Dao的编写
  4. Servlet的编写以及配置
  5. 编写有关的js文件
  6. 编写CSS文件
  7. 通用页面的编写

1. User类、Diary类、CityMap类、MyPagination的编写

1.1 User类的编写

在包com.zyb.model下创建Class

package com.zyb.model;

public class User {
	/**
	 * 
	 * 声明对象
	 */
	private int id=0;
	private String username="";
	private String pwd="";
	private String email="";
	private String question="";
	private String answer="";
	private String city="";
	/**
	 * 使用getter and setter自动生成所有get和set方法
	 * @return
	 */
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getQuestion() {
		return question;
	}
	public void setQuestion(String question) {
		this.question = question;
	}
	public String getAnswer() {
		return answer;
	}
	public void setAnswer(String answer) {
		this.answer = answer;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	
	
}

1.2 Diary类的编写

package com.zyb.model;

import java.util.Date;

public class Diary {
	/**
	 * 声明对象
	 */
	private int id=0;
	private String title="";
	private String address="";
	private Date writeTime=null;
	private int userid=0;
	private String username="";
	/**
	 * 使用getter and setter生成所有对象的get和set方法
	 * @return
	 */
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public Date getWriteTime() {
		return writeTime;
	}
	public void setWriteTime(Date writeTime) {
		this.writeTime = writeTime;
	}
	public int getUserid() {
		return userid;
	}
	public void setUserid(int userid) {
		this.userid = userid;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	
}

1.3 CityMap类的编写

package com.zyb.model;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.LinkedHashMap;
import java.util.Map;

public class CityMap {
	   /**
     *  全国(省,直辖市,自治区,特别行政区)映射集合
     */
    public static Map<String,String[]> model=new LinkedHashMap();
    static{
        model.put("北京", new String[]{"北京"});
        model.put("上海", new String[]{"上海"});
        model.put("天津", new String[]{"天津"});
        model.put("重庆", new String[]{"重庆"});
        model.put("黑龙江", new String[]{"哈尔滨","齐齐哈尔","牡丹江","大庆","伊春","双鸭山","鹤岗","鸡西","佳木斯","七台河","黑河","绥化","大兴安岭"});
        model.put("吉林", new String[]{"长春","延边","吉林","白山","白城","四平","松原","辽源","大安","通化"});
        model.put("辽宁", new String[]{"沈阳","大连","葫芦岛","旅顺","本溪","抚顺","铁岭","辽阳","营口","阜新","朝阳","锦州","丹东","鞍山"});
        model.put("内蒙古", new String[]{"呼和浩特","呼伦贝尔","锡林浩特","包头","赤峰","海拉尔","乌海","鄂尔多斯","通辽"});
        model.put("河北", new String[]{"石家庄","唐山","张家口","廊坊","邢台","邯郸","沧州","衡水","承德","保定","秦皇岛"});
        model.put("河南", new String[]{"郑州","开封","洛阳","平顶山","焦作","鹤壁","新乡","安阳","濮阳","许昌","漯河","三门峡","南阳","商丘","信阳","周口","驻马店"});
        model.put("山东", new String[]{"济南","青岛","淄博","威海","曲阜","临沂","烟台","枣庄","聊城","济宁","菏泽","泰安","日照","东营","德州","滨州","莱芜","潍坊"});
        model.put("山西", new String[]{"太原","阳泉","晋城","晋中","临汾","运城","长治","朔州","忻州","大同","吕梁"});
        model.put("江苏", new String[]{"南京","苏州","昆山","南通","太仓","吴县","徐州","宜兴","镇江","淮安","常熟","盐城","泰州","无锡","连云港","扬州","常州","宿迁"});
        model.put("安徽", new String[]{"合肥","巢湖","蚌埠","安庆","六安","滁州","马鞍山","阜阳","宣城","铜陵","淮北","芜湖","毫州","宿州","淮南","池州"});
        model.put("陕西", new String[]{"西安","韩城","安康","汉中","宝鸡","咸阳","榆林","渭南","商洛","铜川","延安"});
        model.put("宁夏", new String[]{"银川","固原","中卫","石嘴山","吴忠"});
        model.put("甘肃", new String[]{"兰州","白银","庆阳","酒泉","天水","武威","张掖","甘南","临夏","平凉","定西","金昌"});
        model.put("青海", new String[]{"西宁","海北","海西","黄南","果洛","玉树","海东","海南"});
        model.put("湖北", new String[]{"武汉","宜昌","黄冈","恩施","荆州","神农架","十堰","咸宁","襄樊","孝感","随州","黄石","荆门","鄂州"});
        model.put("湖南", new String[]{"长沙","邵阳","常德","郴州","吉首","株洲","娄底","湘潭","益阳","永州","岳阳","衡阳","怀化","韶山","张家界"});
        model.put("浙江", new String[]{"杭州","湖州","金华","宁波","丽水","绍兴","雁荡山","衢州","嘉兴","台州","舟山","温州"});
        model.put("江西", new String[]{"南昌","萍乡","九江","上饶","抚州","吉安","鹰潭","宜春","新余","景德镇","赣州"});
        model.put("福建", new String[]{"福州","厦门","龙岩","南平","宁德","莆田","泉州","三明","漳州"});
        model.put("贵州", new String[]{"贵阳","安顺","赤水","遵义","铜仁","六盘水","毕节","凯里","都匀"});
        model.put("四川", new String[]{"成都","泸州","内江","凉山","阿坝","巴中","广元","乐山","绵阳","德阳","攀枝花","雅安","宜宾","自贡","甘孜州","达州","资阳","广安","遂宁","眉山","南充"});
        model.put("广东", new String[]{"广州","深圳","潮州","韶关","湛江","惠州","清远","东莞","江门","茂名","肇庆","汕尾","河源","揭阳","梅州","中山","德庆","阳江","云浮","珠海","汕头","佛山"});
        model.put("广西", new String[]{"南宁","桂林","阳朔","柳州","梧州","玉林","桂平","贺州","钦州","贵港","防城港","百色","北海","河池","来宾","崇左"});
        model.put("云南", new String[]{"昆明","保山","楚雄","德宏","红河","临沧","怒江","曲靖","思茅","文山","玉溪","昭通","丽江","大理"});
        model.put("海南", new String[]{"海口","三亚","儋州","琼山","通什","文昌"});
        model.put("新疆", new String[]{"乌鲁木齐","阿勒泰","阿克苏","昌吉","哈密","和田","喀什","克拉玛依","石河子","塔城","库尔勒","吐鲁番","伊宁"});
    }
}

1.4 MyPagination的编写

MyPagination中有关于分页及导航的功能

package com.zyb.tool;

import java.util.ArrayList;
import java.util.List;

import com.zyb.model.Diary;

public class MyPagination {
	public List<Diary> list=null;
	private int recordCount=0;
	private int pagesize=0;
	private int maxPage=0;
	/**
	 * 初始化分页信息
	 * @param list
	 * @param Page
	 * @param pagesize
	 * @return
	 */
	public List<Diary> getInitPage(List<Diary> list,int Page,int pagesize){
		List<Diary> newList=new ArrayList<Diary>();
		this.list=list;
		recordCount=list.size();
		this.pagesize=pagesize;
		this.maxPage=getMaxPage();
		try {
			for(int i=(Page-1)*pagesize;i<=Page*pagesize-1;i++) {
				try {
					if(i>=recordCount) {break;}
				}catch(Exception e) {}
				newList.add((Diary)list.get(i));
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		return newList;
	}
	/**
	 * 获取最大记录数
	 * @return
	 */
	private int getMaxPage() {
		int maxPage=(recordCount%pagesize==0)?(recordCount/pagesize):(recordCount/pagesize+1);
		return maxPage;
	}
	/**
	 * 获取指定页的数据
	 * @param Page
	 * @return
	 */
	public List<Diary> getAppointPage(int Page){
		List<Diary> newList=new ArrayList<Diary>();
		try {
			for(int i=(Page-1)*pagesize;i<=Page*pagesize-1;i++) {
				try {
					if(i>=recordCount) {break;}
				}catch(Exception e) {}
				newList.add((Diary)list.get(i));
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		return newList;
	}
	/**
	 * 获取当前页数
	 * @param str
	 * @return
	 */
	public int getPage(String str) {
		if(str==null) {
			str="0";
		}
		int Page=Integer.parseInt(str);
		if(Page<1) {
			Page=1;
		}else {
			if(((Page-1)*pagesize+1)>recordCount) {
				Page=maxPage;
			}
		}
		return Page;
	}
	/**
	 * 获取总记录数
	 * @return
	 */
	public int getRecourdSize() {
		return recordCount;
	}
	/**
	 * 分页导航
	 * @param Page
	 * @param url
	 * @param para
	 * @return
	 */
	public String printCtrl(int Page,String url,String para) {
		String strHtml="<table width='100%' border='0' cellspacint='0' cellpadding='0'><tr><td height='24' align='right'>当前页数:【"+Page+"/"+maxPage+"】 ";
		try {
			if(Page>1) {
				strHtml=strHtml+"<a href='"+url+"&Page=1"+para+"'>第一页</a>";
				strHtml=strHtml+"<a href='"+url+"&Page="+(Page-1)+para+"'>上一页</a>";
			}
			if(Page<maxPage) {
				strHtml=strHtml+"<a href='"+url+"&Page="+(Page+1)+para+"'>下一页</a> <a href='"+url+"&Page="+maxPage+para+"'>最后一页 </a>";
			}
			strHtml=strHtml+"</td></tr></table>";
		}catch(Exception e) {
			e.printStackTrace();
		}
		return strHtml;
	}
}

2. 过滤器的编写与配置

2.1 过滤器的编写

在com.zyb.filter包下创建新的filter,命名为CharacterEncodingFilter

package com.zyb.filter;

import java.io.IOException;
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.annotation.WebFilter;

/**
 * Servlet Filter implementation class CharacterEncodingFilter
 */
@WebFilter("/CharacterEncodingFilter")
public class CharacterEncodingFilter implements Filter {
	protected String encoding=null;
	protected FilterConfig filterConfig=null;
	

    /**
     * Default constructor. 
     */
    public CharacterEncodingFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		this.encoding=null;
		this.filterConfig=null;
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 * 过滤器的接口方法,用于执行过滤业务
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		if(encoding!=null) {
			request.setCharacterEncoding(encoding);
			response.setContentType("text/html;charset="+encoding);
		}
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		this.filterConfig=fConfig;
		this.encoding=filterConfig.getInitParameter("encoding");
	}

}

2.2 在过滤器中配置filter

在web.xml中添加以下代码

<filter>
  	<filter-name>CharacterEncodingFilter</filter-name>
  	<filter-class>com.zyb.filter.CharacterEncodingFilter</filter-class>
  	<init-param>
  		<param-name>encoding</param-name>
  		<param-value>UTF-8</param-value>
  	</init-param>
  </filter>
  <filter-mapping>
  	<filter-name>CharacterEncodingFilter</filter-name>
  	<url-pattern>/*</url-pattern>
  	<dispatcher>REQUEST</dispatcher>
  	<dispatcher>FORWARD</dispatcher>
  </filter-mapping>

3. Dao类的编写

3.1 UserDao编写

在 com.zyb.dao包下新建一个Class,命名为UserDao

UserDao包含验证用户登录,验证是否已有用户注册,保存用户信息,以及找回密码的方法

package com.zyb.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import com.zyb.model.User;
import com.zyb.tool.ConnDB;

public class UserDao {
	private ConnDB conn=null;
	
	public UserDao() {
		conn=new ConnDB();
	}
	
	/**
	 * 验证用户登录
	 * @param user
	 * @return
	 */
	public int login(User user) {
		int flag=0;
		String sql="SELECT * FROM tb_user WHERE username='"+user.getUsername()+"'";
		ResultSet rs=conn.executeQuery(sql);
		try {
			if(rs.next()) {
				String pwd=user.getPwd();
				int uid=rs.getInt(1);
				if(pwd.equals(rs.getString(3))) {
					flag=uid;
					rs.last();
					int rowSum=rs.getRow();
					rs.first();
					if(rowSum!=1) {
						flag=0;
					}
				}else {
					flag=0;
				}
			}else {
				flag=0;
			}
		}catch(SQLException e) {
			e.printStackTrace();
			flag=0;
		}finally {
			conn.close();
		}
		return flag;
	}
	
	/**
	 * 检测是否有用户已注册该用户名
	 * @param sql
	 * @return
	 */
	public String checkUser(String sql) {
		ResultSet rs=conn.executeQuery(sql);
		String result="";
		try {
			if(rs.next()) {
				result="很抱歉,【"+rs.getString(2)+"】已经被注册!";
			}else {
				result="1";
			}
		}catch(SQLException e) {
			e.printStackTrace();
		}finally {
			conn.close();
		}
		return result;
	}
	/**
	 * 保存用户的注册信息
	 * @param sql
	 * @return
	 */
	public String save(String sql) {
		int rtn=conn.executeUpdate(sql);
		String result="";
		if(rtn>0) {
			result="用户注册成功!";
		}else {
			result="用户注册失败!";
		}
		conn.close();
		return result;
	}
	/**
	 * 查找密码第一步
	 * @param username
	 * @return
	 */
	public String forgetPwd1(String username) {
		String sql="SELECT question FROM tb_user WHERE username='"+username+"'";
		ResultSet rs=conn.executeQuery(sql);
		String result="";
		try {
			if(rs.next()) {
				result=rs.getString(1);
			}else {
				result="您输入的用户名不存在!";
			}
		}catch(SQLException e) {
			e.printStackTrace();
			result="您输入的用户名不存在!";
		}finally {
			conn.close();
		}
		return result;
	}
	/**
	 * 找回密码第二步
	 * @param username
	 * @param question
	 * @param answer
	 * @return
	 */
	public String forgetPwd2(String username,String question,String answer) {
		String sql="SELECT pwd FROM tb_user WHERE username='"+username+"' AND question='"+question+"' AND answer='"+answer+"'";
		ResultSet rs=conn.executeQuery(sql);
		String result="";
		try {
			if(rs.next()) {
				result=rs.getString(1);
			}else {
				result="您输入的密码提示问题答案错误!";
			}
		}catch(SQLException e) {
			e.printStackTrace();
		}finally {
			conn.close();
		}
		return result;
	}
}

3.2 DiaryDao的编写

在com.zyb.dao包下新建Class,命名为DiaryDao

该dao类包含查询日记信息,保存日记信息,删除日记信息的方法

package com.zyb.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.zyb.model.Diary;
import com.zyb.tool.ConnDB;

public class DiaryDao {
	private ConnDB conn=null;
	
	public DiaryDao() {
		conn=new ConnDB();
	}
	/**
	 * 功能:查询日记
	 * @param sql
	 * @return
	 */
	public List<Diary> queryDiary(String sql){
		ResultSet rs=conn.executeQuery(sql);
		List<Diary> list=new ArrayList<Diary>();
		try {
			while(rs.next()) {
				Diary diary=new Diary();
				diary.setId(rs.getInt(1));
				diary.setTitle(rs.getString(2));
				diary.setAddress(rs.getString(3));
				Date date;
				try {
					date=DateFormat.getDateInstance().parse(rs.getString(4));
					diary.setWriteTime(date);
				}catch(ParseException e) {
					e.printStackTrace();
				}
				diary.setUserid(rs.getInt(5));
				diary.setUsername(rs.getString(6));
				list.add(diary);
			}
		}catch(SQLException e) {
			e.printStackTrace();
		}finally {
			conn.close();
		}
		return list;
	}
	/**
	 * 保存日记信息
	 * @param diary
	 * @return
	 */
	public int saveDiary(Diary diary) {
		String sql="INSERT INTO tb_diary(title,address,userid) VALUES('"+diary.getTitle()+"','"+diary.getAddress()+"',"+diary.getUserid()+")";
		int ret=conn.executeUpdate(sql);
		conn.close();
		return ret;
	}
	/**
	 * 功能:删除日记信息
	 * @param id
	 * @return
	 */
	public int delDiary(int id) {
		String sql="DELETE FROM tb_diary WHERE id="+id;
		int ret=0;
		try {
			ret=conn.executeUpdate(sql);
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			conn.close();
		}
		return ret;
	}
}

4. Servlet的编写及配置

4.1 UserServlet的编写

在com.zyb.servlet包下创建新的Servlet,命名为UserServlet

UserServlet包含功能:

  1. 用户登录
  2. 找回密码
  3. 检测用户名是否已被注册
  4. 获取省市信息
  5. 保存用户信息
  6. 用户登出
package com.zyb.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

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.zyb.dao.UserDao;
import com.zyb.model.CityMap;
import com.zyb.model.User;

/**
 * Servlet implementation class UserServlet
 */
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserDao userDao=null;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserServlet() {
        super();
        userDao=new UserDao();
        // 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
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String action=request.getParameter("action");
		if("login".equals(action)) {
			this.login(request,response);
		}else if("exit".equals(action)) {
			this.exit(request,response);
		}else if("save".equals(action)) {
			this.save(request,response);
		}else if("getProvince".equals(action)) {
			this.getProvince(request,response);
		}else if("getCity".equals(action)) {
			this.getCity(request,response);
		}else if("checkUser".equals(action)) {
			this.checkUser(request,response);
		}else if("forgetPwd1".equals(action)) {
			this.forgetPwd1(request,response);
		}else if("forgetPwd2".equals(action)) {
			this.forgetPwd2(request,response);
		}
	}
	/**
	 * 找回密码第二步
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void forgetPwd2(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String username=request.getParameter("username");
		String question=request.getParameter("question");
		String answer=request.getParameter("answer");
		String pwd=userDao.forgetPwd2(username,question,answer);
		PrintWriter out=response.getWriter();
		if("您输入的密码提示问题答案错误!".equals(pwd)) {
			out.println("<script>alert('您输入的密码提示问题答案错误!');history.back();</script>");
		}else {
			out.println("<script>alert('您的密码是\\r\\n"+pwd+"\\r\\n请牢记!');window.location.href='DiaryServlet?action=listAllDiary';</script>");
		}
	}

	/**
	 * 找回密码第一步
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void forgetPwd1(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		String username=request.getParameter("username");
		String question=userDao.forgetPwd1(username);
		PrintWriter out=response.getWriter();
		if("".equals(question)) {
			out.println("<script>alert('您没有设置密码提示问题,不能找回密码!');history.back();</script>");
		}else if("您输入的用户名不存在!".equals(question)) {
			out.println("<script>alert('您输入的用户名不存在!');history.back();</script>");
		}else {
			request.setAttribute("question", question);
			request.setAttribute("username", username);
			request.getRequestDispatcher("forgetPwd_2.jsp").forward(request, response);
		}
	}

	/**
	 * 检测用户名是否被注册
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void checkUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String username=request.getParameter("username");
		String sql="SELECT * FROM tb_user WHERE username='"+username+"'";
		String result=userDao.checkUser(sql);
		response.setContentType("text/html");
		PrintWriter out=response.getWriter();
		out.print(result);
		out.flush();
		out.close();
	}

	/**
	 * 获取城市信息
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void getCity(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String result="";
		String selProvince=request.getParameter("parProvince");
		selProvince=new String(selProvince.getBytes("ISO-8859-1"),"GBK");
		CityMap cityMap=new CityMap();
		Map<String,String[]> map=cityMap.model;
		String[] arrCity=map.get(selProvince);
		for(int i=0;i<arrCity.length;i++) {
			result=result+arrCity[i]+",";
		}
		result=result.substring(0,result.length()-1);
		response.setContentType("text/html");
		PrintWriter out=response.getWriter();
		out.print(result);
		out.flush();
		out.close();
	}
	
	/**
	 * 获取省份信息
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void getProvince(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String result="";
		CityMap cityMap=new CityMap();
		Map<String,String[]> map=cityMap.model;
		Set<String> set=map.keySet();
		Iterator it=set.iterator();
		while(it.hasNext()) {
			result=result+it.hasNext()+",";
		}
		result=result.substring(0,result.length()-1);
		response.setContentType("text/html");
		PrintWriter out=response.getWriter();
		out.print(result);
		out.flush();
		out.close();
	}

	/**
	 * 保存用户注册信息
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void save(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String username=request.getParameter("user");
		String pwd=request.getParameter("pwd");
		String email=request.getParameter("eamil");
		String city=request.getParameter("city");
		String question=request.getParameter("question");
		String answer=request.getParameter("answer");
		String sql="INSERT INTO tb_user (username,pwd,email,question,answer,city) VALUES('"+username+"','"+pwd+"','"+email+"','"+question+"','"+answer+"','"+city+"')";
		String result=userDao.save(sql);
		response.setContentType("text/html");
		PrintWriter out=response.getWriter();
		out.print(result);
		out.flush();
		out.close();
	}
	
	/**
	 * 功能:用户退出
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void exit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session=request.getSession();
		session.invalidate();
		request.getRequestDispatcher("DiaryServlet?action=listAllDiary").forward(request, response);
	}

	/**
	 * 功能:用户登录
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		User user=new User();
		user.setUsername(request.getParameter("username"));
		user.setPwd(request.getParameter("pwd"));
		int r=userDao.login(user);
		if(r>0) {
			HttpSession session=request.getSession();
			session.setAttribute("username", user.getUsername());
			session.setAttribute("uid", r);
			session.setAttribute("returnValue", "登陆成功!");
			request.getRequestDispatcher("userMessage.jsp").forward(request, response);
		}else {
			request.setAttribute("returnValue", "您输入的用户名或密码有误,请重新输入!");
			request.getRequestDispatcher("userMessage.jsp").forward(request, response);
		}
	}

}

4.2 配置UserServlet

在web.xml中添加如下代码

<servlet>
  	<description></description>
  	<display-name>UserServlet</display-name>
  	<servlet-name>UserServlet</servlet-name>
  	<servlet-class>com.zyb.servlet.UserServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>UserServlet</servlet-name>
  	<url-pattern>/UserServlet</url-pattern>
  </servlet-mapping>

4.3 编写DiaryServlet

DiaryServlet功能包括查看我的日记,查看所有日记,预览日记,保存日记,删除日记。

package com.zyb.servlet;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.imageio.ImageIO;
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.zyb.dao.DiaryDao;
import com.zyb.model.Diary;
import com.zyb.tool.MyPagination;

/**
 * Servlet implementation class DiaryServlet
 */
@WebServlet("/DiaryServlet")
public class DiaryServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
      MyPagination pagination=null;
      DiaryDao dao=null;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DiaryServlet() {
        super();
        dao=new DiaryDao();
        // 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
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String action=request.getParameter("action");
		if("preview".equals(action)) {
			preview(request,response);
		}else if("save".equals(action)) {
			save(request,response);
		}else if("listAllDiary".equals(action)) {
			listAllDiary(request,response);
		}else if("listMyDiary".equals(action)) {
			listMyDiary(request,response);
		}else if("delDiary".equals(action)) {
			delDiary(request,response);
		}
	}
	/**
	 * 显示我的日记
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void listMyDiary(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session=request.getSession();
		String strPage=(String)request.getParameter("Page");
		int Page=1;
		List<Diary> list=null;
		if(strPage==null) {
			int userid=Integer.parseInt(session.getAttribute("uid").toString());
			String sql="SELECT d.*,u.username FROM tb_diary d INNER JOIN tb_user u ON u.id=d.userid WHERE d.userid="+userid+" ORDER BY d.writeTime DESC";
			pagination=new MyPagination();
			list=dao.queryDiary(sql);
			int pagesize=4;
			list=pagination.getInitPage(list, Page, pagesize);
			request.getSession().setAttribute("pagination", pagination);
		}else {
			pagination=(MyPagination)request.getSession().getAttribute("pagination");
			Page=pagination.getPage(strPage);
			list=pagination.getAppointPage(Page);
		}
		request.setAttribute("diaryList", list);
		request.setAttribute("Page", Page);
		request.setAttribute("url", "listMyDiary");
		request.getRequestDispatcher("listAllDiary.jsp").forward(request, response);
	}

	/**
	 * 显示所有日记
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void listAllDiary(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String strPage=(String)request.getParameter("Page");
		int Page=1;
		List<Diary> list=null;
		if(strPage==null) {
			String sql="SELECT d.*,u.username FROM tb_diary d INNER JOIN tb_user u ON u.uid=d.userid ORDER BY d.writeTime DESC limit 50";
			pagination =new MyPagination();
			list=dao.queryDiary(sql);
			int pagesize=4;
			list=pagination.getInitPage(list, Page, pagesize);
			request.getSession().setAttribute("pagination", pagination);
		}else {
			pagination=(MyPagination)request.getSession().getAttribute("pagination");
			Page=pagination.getPage(strPage);
			list=pagination.getAppointPage(Page);
		}
		request.setAttribute("diaryList", list);
		request.setAttribute("Page", Page);
		request.setAttribute("url", "listAllDiary");
		request.getRequestDispatcher("listAllDiary.jsp").forward(request, response);
	}

	/**
	 * 功能:保存日记
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void save(HttpServletRequest request, HttpServletResponse response) throws IOException {
		HttpSession session=request.getSession(true);
		BufferedImage image=(BufferedImage) session.getAttribute("diaryImg");
		String url=request.getRequestURL().toString();
		url=request.getRealPath("/");
		long date=new Date().getTime();
		Random r=new Random(date);
		long value=r.nextLong();
		url=url+"images/diary/"+value;
		String scaleImgUrl=url+"scale.jpg";
		url=url+".png";
		ImageIO.write(image,"PNG",new File(url));
		File file=new File(url);
		Image src=ImageIO.read(file);
		int old_w=src.getWidth(null);
		int old_h=src.getHeight(null);
		int new_w=0;
		int new_h=0;
		double temp=0;
		double tagSize=60;
		if(old_w>old_h) {
			temp=old_w/tagSize;
		}else {
			temp=old_h/tagSize;
		}
		new_w=(int)Math.round(old_w/temp);
		new_h=(int)Math.round(old_h/temp);
		image=new BufferedImage(new_w,new_h,BufferedImage.TYPE_INT_RGB);
		src=src.getScaledInstance(new_w, new_h, Image.SCALE_SMOOTH);
		image.getGraphics().drawImage(src, 0, 0, new_w, new_h, null);
		ImageIO.write(image,"JPG",new File(scaleImgUrl));
		Diary diary=new Diary();
		diary.setAddress(String.valueOf(value));
		diary.setTitle(session.getAttribute("title").toString());
		diary.setUserid(Integer.parseInt(session.getAttribute("uid").toString()));
		int rtn=dao.saveDiary(diary);
		PrintWriter out=response.getWriter();
		if(rtn>0) {
			out.println("<script>alert('保存成功!');window.location.href='DiaryServlet?action=listAllDiary';</script>");
		}else {
			out.println("<script>alert('保存日记失败,请稍后重试!');history.back();</script>");
		}
	}

	/**
	 * 功能:日记预览
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void preview(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String title=request.getParameter("title");
		String template=request.getParameter("template");
		String weather=request.getParameter("weather");
		String[] content=request.getParameterValues("content");
		for(int i=0;i<content.length;i++) {
			if(content[i].equals(null)||content[i].equals("")||content[i].equals("请在此输入文字")) {
				content[i]="没啥可说的";
			}
		}
		HttpSession session=request.getSession(true);
		session.setAttribute("template", template);
		session.setAttribute("weather", weather);
		session.setAttribute("title", title);
		session.setAttribute("diart", content);
		request.getRequestDispatcher("preview.jsp").forward(request, response);
	}

	/**
	 * 删除日记
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void delDiary(HttpServletRequest request, HttpServletResponse response) throws IOException {
		int id=Integer.parseInt(request.getParameter("id"));
		String imgName=request.getParameter("imgName");
		String url=request.getParameter("url");
		int rtn=dao.delDiary(id);
		PrintWriter out=response.getWriter();
		if(rtn>0) {
			String path=getServletContext().getRealPath("\\")+"images\\diary\\";
			java.io.File file=new java.io.File(path+imgName+"scale.jpg");
			file.delete();
			file=new java.io.File(path+imgName+".png");
			file.delete();
			out.println("<script>alert('删除日记成功!');window.location.href='DiaryServlet?action="+url+"';</script>");
		}else {
			out.println("<script>alert('删除日记失败!');history.back();</script>");
		}
	}

}

4.4 配置DiaryServlet

在web.xml中添加如下代码

<servlet>
  	<description></description>
  	<display-name>DiaryServlet</display-name>
  	<servlet-name>DiaryServlet</servlet-name>
  	<servlet-class>com.zyb.servlet.DiaryServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>DiaryServlet</servlet-name>
  	<url-pattern>/DiaryServlet</url-pattern>
  </servlet-mapping>

4.5 编写CreateImg

CreateImg功能包括图片的生成

package com.zyb.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.imageio.ImageIO;
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 CreateImg
 */
@WebServlet("/CreateImg")
public class CreateImg extends HttpServlet {
	public void service(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "No-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
		int width=600;
		int height=600;
		BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
		Graphics g=image.getGraphics();
		HttpSession session=request.getSession(true);
		String template=session.getAttribute("template").toString();
		String weather=session.getAttribute("weather").toString();
		weather=request.getRealPath("images/"+weather+".png");
		String[] content=(String[])session.getAttribute("diary");
		File bgImgFile;
		if("默认".equals(template)) {
			bgImgFile=new File(request.getRealPath("images/bg_00.jpg"));
			Image src=ImageIO.read(bgImgFile);
			g.drawImage(src, 0, 0, width, height, null);
			outWord(g,content,weather,0,0);
		}else if("女孩".equals(template)) {
			bgImgFile=new File(request.getRealPath("images/bg_01.jpg"));
			Image src=ImageIO.read(bgImgFile);
			g.drawImage(src, 0, 0, width, height, null);
			outWord(g,content,weather,0,0);
		}else{
			bgImgFile=new File(request.getRealPath("images/bg_02.jpg"));
			Image src=ImageIO.read(bgImgFile);
			g.drawImage(src, 0, 0, width, height, null);
			outWord(g,content,weather,0,0);
		}
		ImageIO.write(image,"PNG",response.getOutputStream());
		session.setAttribute("diaryImg", image);
	}

	private void outWord(Graphics g, String[] content, String weather, int offsetX, int offsetY) {
		Font mFont=new Font("微软雅黑",Font.PLAIN,26);
		g.setFont(mFont);
		g.setColor(new Color(0,0,0));
		int contentLen=0;
		int x=0;
		int y=0;
		for(int i=0;i<content.length;i++) {
			contentLen=content[i].length();
			x=45+(i%3)*170+offsetX;
			y=130+(i/3)*140+offsetY;
			if(content[i].equals("weathervalue")) {
				File bgImgFile=new File(weather);
				mFont=new Font("微软雅黑",Font.PLAIN,14);
				g.setFont(mFont);
				Date date=new Date();
				String newTime=new SimpleDateFormat("yyyy年m月d日 E").format(date);
				g.drawString(newTime, x-12, y-60);
				Image src;
				try {
					src=ImageIO.read(bgImgFile);
					g.drawImage(src, x+10, y-40, 80, 80, null);
				}catch(IOException e) {
					e.printStackTrace();
				}
				continue;
			}
			if(contentLen<5) {
				switch(contentLen%5) {
				case 1:
					mFont=new Font("微软雅黑",Font.PLAIN,40);
					g.setFont(mFont);
					g.drawString(content[i], x+40, y);
					break;
				case 2:
					mFont=new Font("微软雅黑",Font.PLAIN,36);
					g.setFont(mFont);
					g.drawString(content[i], x+25, y);
					break;
				case 3:
					mFont=new Font("微软雅黑",Font.PLAIN,30);
					g.setFont(mFont);
					g.drawString(content[i], x+20, y);
					break;
				case 4:
					mFont=new Font("微软雅黑",Font.PLAIN,28);
					g.setFont(mFont);
					g.drawString(content[i], x+10, y);
					break;
				}
			}else {
				mFont=new Font("微软雅黑",Font.PLAIN,22);
				g.setFont(mFont);
				if(Math.ceil(contentLen/5.0)==1) {
					g.drawString(content[i], x, y);
				}else if(Math.ceil(contentLen/5.0)==2) {
					g.drawString(content[i].substring(0,5), x, y-20);
					g.drawString(content[i].substring(5), x, y+10);
				}else if(Math.ceil(contentLen/5.0)==3) {
					g.drawString(content[i].substring(0,5), x, y-30);
					g.drawString(content[i].substring(5,10), x, y);
					g.drawString(content[i].substring(10), x, y+30);
				}
			}
		}
		g.dispose();
	}
}

4.6 配置CreateImg

在web.xml中添加如下代码

<servlet>
  	<description></description>
  	<display-name>CreateImg</display-name>
  	<servlet-name>CreateImg</servlet-name>
  	<servlet-class>com.zyb.servlet.CreateImg</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>CreateImg</servlet-name>
  	<url-pattern>/CreateImg</url-pattern>
  </servlet-mapping>

5. 编写有关的js文件

5.1 编写AjaxRequest

在js文件夹在新建JavaScript Source文件。

var net=new Object();
net.AjaxRequest=function(url,onload,onerror,method,params){
	this.req=null;
	this.onload=onload;
	this.onerror=(onerror)?onerror:this.defaultError;
	this.loadDate(url,method,params);
}

net.AjaxRequest.prototype.loadDate=function(url,method,params){
	if(!method){
		method="GET";
	}
	if(window.XMLHttpRequest){
		this.req=new XMLHttpRequest();
	}else if(windows.ActiveXObject){
		this.req=new ActiveXObject("Microsoft.XMLHttp");
	}
	if(this.req){
		try{
			var loader=this;
			this.req.onreadystatechange=function(){
				net.AjaxRequest.onReadyState.call(loader);
			}
			this.req.open(method,url,true);
			if(method=="POST"){
				this.req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
				this.req.setRequestHeader("x-requested-with","ajax");
			}
			this.req.send(params);
		}catch(err){
			this.onerror.call(this);
		}
	}
}

net.AjaxRequest.onReadyState=function(){
	var req=this.req;
	var ready=req.readyState;
	if(ready==4){
		if(req.status==200){
			this.onload.call(this);
		}else{
			this.onerror.call(this);
		}
	}
}

net.AjaxRequest.prototype.defaultError=function(){
	alert("错误数据\n\n回调状态:"+this.req.readyStete+"\n状态:"+this.req.status);
}

5.2 编写zybFunction.js

该文件中的函数为判读用户名、密码等是否符合规则

function checkstr(str,digit){
	var n=0;
	for(i=0;i<str.length;i++){
		var leg=str.charCodeAt(i);
		if(leg>255){
			n+=2;
		}else{
			n+=1;
		}
	}
	if(n>digit){
		return true;
	}else{
		return false;
	}
}

function checkeUser(user){
	if(checkstr(user,20)){
		return false;
	}else{
		return true;
	}
}

function ckeckePwd(user){
	var str=user;
	var Expression=/^[A-Za-z]{1}([A-Za-z0-9]|[._]){5,29}$/;
	var objExp=new RegExp(Expression);
	if(objExp.text(str)==true){
		return true;
	}else{
		return false;
	}
}

function checkemail(email){
	var str=email;
	var Expression=/\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
	var objExp=new RegExp(Expression);
	if(objExp.test(str)==true){
		return true;
	}else{
		return false;
	}
}

6. 编写CSS文件

在css文件夹下新建css文件

@charset "ISO-8859-1";
*{
	margin:0;
	padding:0;
}
body{
	font-size:9pt;
}
#box{
	margin:0 auto auto auto;
	width:800px;
	clear:both;
	background-color:#FFF;
}
a:hover{
	font-size:9pt;
	color:#F40;
}
a{
	font-size:9pt;
	text-decoration:none;
	color:#3C404D;
}

7. 通用页面的编写

7.1 bottom.jsp的编写

创建新的jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<style>
	#bottom{
		background-image:url(images/bg_bottom.jpg);
		width:800px;
		height:58px;
		clear:both;
		text-align:center;
		padding-top:10px;
	}
	#bottom ul{
		color:#FFF;
		list-style:none;
		line-height:20px;
	}
</style>
<div id="bottom">
	<ul>
		<li>技术服务热线: 400-675-1066 传真: 0431-84972266 企业邮箱: mingrisoft@mingrisoft.com
		<li>Copyright © www.mrbccd.com All Rights Reserved!
	</ul>
</div>

创建新的index.jsp页面,测试bottom.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>
	<%@ include file="bottom.jsp" %>
</body>
</html>
图 2.1 测试bottom

总结

问题:在编写Servlet时没有用到该servlet即在web.xml中注册了该servlet,以至于tomcat无法启动,删除该部分代码后tomcat正常运行。

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.