JSP论坛项目练习
1 创建数据库
USE db_1;
DROP TABLE tab_user;
CREATE TABLE tab_user(
uid INT PRIMARY KEY AUTO_INCREMENT,
uname VARCHAR(11),
upwd VARCHAR(11),
usex CHAR(1),
udate DATETIME,
uscore INT,
upwd VARCHAR(254)
);
INSERT INTO tab_user VALUES(11,"张三","123","男","2020-11-11 12:13:14",1100,"0");
INSERT INTO tab_user VALUES(12,"李四","123","男","2020-11-11 12:13:14",1200,"0");
INSERT INTO tab_user VALUES(13,"王五","123","女","2020-11-11 12:13:14",1300,"0");
INSERT INTO tab_user VALUES(14,"赵六","123","女","2020-11-11 12:13:14",1400,"0");
CREATE TABLE tab_title(
tid INT PRIMARY KEY AUTO_INCREMENT,
tname VARCHAR(100),
tcontent TEXT,
tcount INT DEFAULT 0,
tcreate DATETIME,
uid INT,
CONSTRAINT fk_11 FOREIGN KEY(uid) REFERENCES tab_user(uid)
);
INSERT INTO tab_title VALUES(1001,"十一放假","放假去哪里?老铁们给个意见把!",1100,'2021-11-11 12:13:14',11);
INSERT INTO tab_title VALUES(NULL,"五一放假","放假去哪里?老铁们给个意见把!",1200,'2020-11-21 12:13:14',12);
INSERT INTO tab_title VALUES(NULL,"元旦放假","放假去哪里?老铁们给个意见把!",1300,'2020-11-11 12:23:14',13);
INSERT INTO tab_title VALUES(NULL,"春节放假","放假去哪里?老铁们给个意见把!",1400,'2020-12-11 12:13:14',14);
INSERT INTO tab_title VALUES(NULL,"中秋节放假","放假去哪里?老铁们给个意见把!",101,'2020-11-13 12:13:14',11);
INSERT INTO tab_title VALUES(NULL,"六一放假","放假去哪里?老铁们给个意见把!",102,'2020-11-11 13:13:14',12);
INSERT INTO tab_title VALUES(NULL,"八一放假","放假去哪里?老铁们给个意见把!",130,'2020-11-11 12:33:14',13);
INSERT INTO tab_title VALUES(NULL,"清明放假","放假去哪里?老铁们给个意见把!",106,'2020-10-11 12:13:14',14);
CREATE TABLE Message(
`mid` INT PRIMARY KEY AUTO_INCREMENT,
mcontent VARCHAR(200),
uid INT,
tid INT,
mcreate DATETIME,
mzan INT,
mxu INT,
CONSTRAINT fk_12 FOREIGN KEY(uid) REFERENCES tab_user(uid),
CONSTRAINT fk_13 FOREIGN KEY(tid) REFERENCES tab_title(tid)
);
INSERT INTO Message VALUES(
NULL,
CONCAT("说的真好",TRUNCATE(RAND()*100,0)),
TRUNCATE(RAND()*4+11,0),
TRUNCATE(RAND()*8+1001,0),
CONCAT(TRUNCATE(RAND()*3+2019,0),"-",TRUNCATE(RAND()*12+1,0),"-",TRUNCATE(RAND()*30+1,0)," ",TRUNCATE(RAND()*24+1,0),":",
TRUNCATE(RAND()*60,0),":",TRUNCATE(RAND()*60,0)),
TRUNCATE(RAND()*100,0),
TRUNCATE(RAND()*100,0)
);
2 创建项目
- 更改编码集
- servlet选择2.5
ps:如果eclipse版本过高需要更改根目录为src,以及webContent名称
3 分包 导入jar
- 导入jar
4 准备工作:实体类 工具类 连接池配置文件
- 连接池配置文件c3p0-config.xml
<?xml version="1.0" encoding="UTF-8"?> <!-- 声明区:当前xml页面属性 -->
<c3p0-config>
<default-config>
<!--mysql数据库连接的各项参数-->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/db_1</property>
<property name="user">root</property>
<property name="password">root</property>
<!--配置数据库连接池的初始连接数、最小链接数、获取连接数、最大连接数、最大空闲时间-->
<property name="initialPoolSize">10</property>
<property name="minPoolSize">10</property>
<property name="acquireIncrement">5</property>
<property name="maxPoolSize">100</property>
<property name="maxIdleTime">30</property>
</default-config>
</c3p0-config>
-
实体类:根据表创建
User.javapackage com.zhiyou.entity; import java.io.Serializable; import java.util.Date; public class User implements Serializable{ private Integer uid; private String uname; private String upwd; private String usex; private Date udate; private Integer uscore; private String head; public Integer getUid() { return uid; } public void setUid(Integer uid) { this.uid = uid; } public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } public String getUpwd() { return upwd; } public void setUpwd(String upwd) { this.upwd = upwd; } public String getUsex() { return usex; } public void setUsex(String usex) { this.usex = usex; } public Date getUdate() { return udate; } public void setUdate(Date udate) { this.udate = udate; } public Integer getUscore() { return uscore; } public void setUscore(Integer uscore) { this.uscore = uscore; } public String getHead() { return head; } public void setHead(String head) { this.head = head; } @Override public String toString() { return "User [uid=" + uid + ", uname=" + uname + ", upwd=" + upwd + ", usex=" + usex + ", udate=" + udate + ", uscore=" + uscore + ", head=" + head + "]"; } public User(Integer uid, String uname, String upwd, String usex, Date udate, Integer uscore, String head) { super(); this.uid = uid; this.uname = uname; this.upwd = upwd; this.usex = usex; this.udate = udate; this.uscore = uscore; this.head = head; } public User() { super(); } }
Title.java
package com.zhiyou.entity; import java.io.Serializable; import java.util.Date; import java.util.List; public class Title implements Serializable{ // tid INT PRIMARY KEY AUTO_INCREMENT, // tname VARCHAR(100), // tcontent TEXT, // tcount INT DEFAULT 0, // tcreate DATETIME, // uid INT, // CONSTRAINT fk_11 FOREIGN KEY(uid) REFERENCES tab_user(uid) private Integer tid; private String tname; private String tcontent; private Integer tcount; private Date tcreate; private Integer uid; private User user;//此属性指向的是uid对应的对象 private List<Message> MessageList;//记录当前回话下的所有留言 public List<Message> getMessageList() { return MessageList; } public void setMessageList(List<Message> MessageList) { this.MessageList = MessageList; } public Integer getTid() { return tid; } public void setTid(Integer tid) { this.tid = tid; } public String getTname() { return tname; } public void setTname(String tname) { this.tname = tname; } public String getTcontent() { return tcontent; } public void setTcontent(String tcontent) { this.tcontent = tcontent; } public Integer getTcount() { return tcount; } public void setTcount(Integer tcount) { this.tcount = tcount; } public Date getTcreate() { return tcreate; } public void setTcreate(Date tcreate) { this.tcreate = tcreate; } public Integer getUid() { return uid; } public void setUid(Integer uid) { this.uid = uid; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } @Override public String toString() { return "Title [tid=" + tid + ", tname=" + tname + ", tcontent=" + tcontent + ", tcount=" + tcount + ", tcreate=" + tcreate + ", uid=" + uid + ", user=" + user + "]"; } public Title(Integer tid, String tname, String tcontent, Integer tcount, Date tcreate, Integer uid, User user) { super(); this.tid = tid; this.tname = tname; this.tcontent = tcontent; this.tcount = tcount; this.tcreate = tcreate; this.uid = uid; this.user = user; } public Title() { super(); } }
Message.java
package com.zhiyou.entity; import java.util.Date; public class Message { private Integer mid; private String mcontent; private Integer uid; private User user; private Integer tid; private Title title; private Date mcreate; private Integer mzan; private Integer mxu; public Integer getMid() { return mid; } public void setMid(Integer mid) { this.mid = mid; } public String getMcontent() { return mcontent; } public void setMcontent(String mcontent) { this.mcontent = mcontent; } public Integer getUid() { return uid; } public void setUid(Integer uid) { this.uid = uid; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Integer getTid() { return tid; } public void setTid(Integer tid) { this.tid = tid; } public Title getTitle() { return title; } public void setTitle(Title title) { this.title = title; } public Date getMcreate() { return mcreate; } public void setMcreate(Date mcreate) { this.mcreate = mcreate; } public Integer getMzan() { return mzan; } public void setMzan(Integer mzan) { this.mzan = mzan; } public Integer getMxu() { return mxu; } public void setMxu(Integer mxu) { this.mxu = mxu; } @Override public String toString() { return "Message [mid=" + mid + ", mcontent=" + mcontent + ", uid=" + uid + ", user=" + user + ", tid=" + tid + ", title=" + title + ", mcreate=" + mcreate + ", mzan=" + mzan + ", mxu=" + mxu + "]"; } public Message(Integer mid, String mcontent, Integer uid, User user, Integer tid, Title title, Date mcreate, Integer mzan, Integer mxu) { super(); this.mid = mid; this.mcontent = mcontent; this.uid = uid; this.user = user; this.tid = tid; this.title = title; this.mcreate = mcreate; this.mzan = mzan; this.mxu = mxu; } public Message() { super(); } }
-
工具类 JdbcUtil.java
package com.zhiyou.utils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class JdbcUtil {
//静态属性获取连接池对象:自动加载src下的配置文件:c3p0-config.xml
private static DataSource ds=new ComboPooledDataSource();
//获取连接
public static Connection getCon(){
try {
return ds.getConnection();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
//归还连接:通过DataSource获取的Connection对象的close方法已经被重写:不再是关闭连接 而是把连接归还给连接池
public static void release(ResultSet set,Statement sta,Connection con){
if(set!=null){
try {
set.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
if(sta!=null){
try {
sta.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
if(con!=null){
try {
con.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public static void main(String[] args) {
System.out.println(getCon());
}
}
5 dao
UserDao
package com.zhiyou.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import com.zhiyou.entity.User;
import com.zhiyou.utils.JdbcUtil;
public class UserDao {
public User getOneByUname(String uname){
User user=null;
//获取链接
Connection con=JdbcUtil.getCon();
//准备sql模板
String sql="select * from tab_user where uname=?";
//获取预编译对象
PreparedStatement pre=null;
ResultSet set=null;
try {
pre=con.prepareStatement(sql);
pre.setString(1, uname);
set=pre.executeQuery();
if(set.next()){
user=new User(set.getInt("uid"),
uname,
set.getString("upwd"),
set.getString("usex"),
set.getDate("udate"),
set.getInt("uscore"),
"0");
}
} catch (Exception e) {
throw new RuntimeException(e);
}finally{
JdbcUtil.release(set, pre, con);
}
//给占位符赋值
//执行execute方法 获取结果集
//处理数据
//关闭连接
return user;
}
public User getOneById(Integer uid){
User user=null;
//获取链接
Connection con=JdbcUtil.getCon();
//准备sql模板
String sql="select * from tab_user where uid=?";
//获取预编译对象
PreparedStatement pre=null;
ResultSet set=null;
try {
pre=con.prepareStatement(sql);
pre.setInt(1, uid);
set=pre.executeQuery();
if(set.next()){
user=new User(uid,
set.getString("uname"),
set.getString("upwd"),
set.getString("usex"),
set.getDate("udate"),
set.getInt("uscore"),
set.getString("head"));
}
} catch (Exception e) {
throw new RuntimeException(e);
}finally{
JdbcUtil.release(set, pre, con);
}
//给占位符赋值
//执行execute方法 获取结果集
//处理数据
//关闭连接
return user;
}
public int AddOne(User user){
//获取链接
Connection con=JdbcUtil.getCon();
//准备sql模板
String sql="INSERT INTO tab_user(uname,upwd,usex,udate,uscore,head) VALUES (?,?,?,?,?,?)";
//获取预编译对象
PreparedStatement pre=null;
ResultSet set=null;
int hang=0;
try {
pre=con.prepareStatement(sql);
pre.setString(1, user.getUname());
pre.setString(2, user.getUpwd());
pre.setString(3, user.getUsex());
pre.setTimestamp(4, new java.sql.Timestamp(user.getUdate().getTime()));
pre.setFloat(5, user.getUscore());
pre.setString(6, user.getHead());
hang=pre.executeUpdate();
} catch (Exception e) {
throw new RuntimeException(e);
}finally{
JdbcUtil.release(set, pre, con);
}
//给占位符赋值
//执行execute方法 获取结果集
//处理数据
//关闭连接
return hang;
}
}
TitleDao
package com.zhiyou.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.zhiyou.entity.Title;
import com.zhiyou.utils.JdbcUtil;
public class TitleDao {
//添加
public int addOne(Title t){
//获取链接
Connection con=JdbcUtil.getCon();
//准备sql模板
String sql="insert into tab_title(tname,tcontent,tcreate,uid) values(?,?,?,?)";
//获取预编译对象
PreparedStatement pre=null;
int hang=0;
try {
pre=con.prepareStatement(sql);
pre.setString(1, t.getTname());
pre.setString(2, t.getTcontent());
//把java.util.date转换为java.sql.date
pre.setTimestamp(3, new java.sql.Timestamp(t.getTcreate().getTime()));
//The method setDate(int, java.sql.Date) in the type PreparedStatement is not applicable for the arguments (int, java.util.Date)
pre.setInt(4, t.getUid());
hang=pre.executeUpdate();
} catch (Exception e) {
throw new RuntimeException(e);
}finally{
JdbcUtil.release(null, pre, con);
}
//给占位符赋值
//执行execute方法 获取结果集
//处理数据
//关闭连接
return hang;
}
//查询所有
public List<Title> getAll(){
List<Title> list=new ArrayList<Title>();
//获取链接
Connection con=JdbcUtil.getCon();
//准备sql模板
String sql="select * from tab_title order by tcreate desc";
//获取预编译对象
PreparedStatement pre=null;
ResultSet set=null;
try {
pre=con.prepareStatement(sql);
set=pre.executeQuery();
while(set.next()){
Title title=new Title(
set.getInt("tid"),
set.getString("tname"),
set.getString("tcontent"),
set.getInt("tcount"),
set.getTimestamp("tcreate"),
set.getInt("uid"), null);
list.add(title);
}
} catch (Exception e) {
throw new RuntimeException(e);
}finally{
JdbcUtil.release(set, pre, con);
}
return list;
}
//根据uid查询所有
public List<Title> getAll(int uid){
List<Title> list=new ArrayList<Title>();
//获取链接
Connection con=JdbcUtil.getCon();
//准备sql模板
String sql="select * from tab_title where uid=? order by tcreate desc";
//获取预编译对象
PreparedStatement pre=null;
ResultSet set=null;
try {
pre=con.prepareStatement(sql);
pre.setInt(1, uid);
set=pre.executeQuery();
while(set.next()){
Title title=new Title(
set.getInt("tid"),
set.getString("tname"),
set.getString("tcontent"),
set.getInt("tcount"),
set.getTimestamp("tcreate"),
set.getInt("uid"), null);
list.add(title);
}
} catch (Exception e) {
throw new RuntimeException(e);
}finally{
JdbcUtil.release(set, pre, con);
}
return list;
}
//根据id查询
public Title getOneByTid(int tid){
Title t=null;
//获取链接
Connection con=JdbcUtil.getCon();
//准备sql模板
String sql="select * from tab_title where tid=?";
//获取预编译对象
PreparedStatement pre=null;
ResultSet set=null;
try {
pre=con.prepareStatement(sql);
pre.setInt(1, tid);
set=pre.executeQuery();
if(set.next()){
t=new Title(
tid,
set.getString("tname"),
set.getString("tcontent"),
set.getInt("tcount"),
set.getTimestamp("tcreate"),
set.getInt("uid"), null);
}
} catch (Exception e) {
throw new RuntimeException(e);
}finally{
JdbcUtil.release(set, pre, con);
}
return t;
}
//根据id删除
public int deleteOneByTid(Integer tid){
//获取链接
Connection con=JdbcUtil.getCon();
//准备sql模板
String sql="delete from tab_title where tid=?";
//获取预编译对象
PreparedStatement pre=null;
int hang=0;
try {
pre=con.prepareStatement(sql);
pre.setInt(1, tid);
hang=pre.executeUpdate();
} catch (Exception e) {
throw new RuntimeException(e);
}finally{
JdbcUtil.release(null, pre, con);
}
return hang;
}
//修改:关注度+1
public int addTcount(Integer tid){
//获取链接
Connection con=JdbcUtil.getCon();
//准备sql模板
String sql="update tab_title set tcount=tcount+1 where tid=?";
//获取预编译对象
PreparedStatement pre=null;
int hang=0;
try {
pre=con.prepareStatement(sql);
pre.setInt(1, tid);
hang=pre.executeUpdate();
} catch (Exception e) {
throw new RuntimeException(e);
}finally{
JdbcUtil.release(null, pre, con);
}
return hang;
}
}
MessageDao
package com.zhiyou.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.zhiyou.entity.Message;
import com.zhiyou.utils.JdbcUtil;
public class MessageDao {
//1 添加留言
public int addOne(Message m){
//获取链接
Connection con=JdbcUtil.getCon();
//准备sqm模板
String sqm="insert into tab_message(mcontent,uid,tid,mcreate,mzan,mxu) values(?,?,?,?,?,?)";
//获取预编译对象
PreparedStatement pre=null;
int hang=0;
try {
pre=con.prepareStatement(sqm);
pre.setString(1, m.getMcontent());
pre.setInt(2,m.getUid());
pre.setInt(3,m.getTid());
//需要的是java.sqm.* 有的是java.utim.Date
pre.setTimestamp(4, new java.sql.Timestamp(m.getMcreate().getTime()));
pre.setInt(5,m.getMzan());
pre.setInt(6,m.getMxu());
hang=pre.executeUpdate();
} catch (Exception e) {
throw new RuntimeException(e);
}finally{
JdbcUtil.release(null, pre, con);
}
return hang;
}
//2 删除留言
public int deleteOneBymid(int mid){
//获取链接
Connection con=JdbcUtil.getCon();
//准备sqm模板
String sqm="delete from tab_Message where mid=?";
//获取预编译对象
PreparedStatement pre=null;
int hang=0;
try {
pre=con.prepareStatement(sqm);
pre.setInt(1,mid);
hang=pre.executeUpdate();
} catch (Exception e) {
throw new RuntimeException(e);
}finally{
JdbcUtil.release(null, pre, con);
}
return hang;
}
//3 根据tid获取所有留言
public List<Message> getAllByTid(int tid){
List<Message> mist=new ArrayList();
//获取链接
Connection con=JdbcUtil.getCon();
//准备sqm模板
String sqm="select * from tab_Message where tid=? order by mcreate desc";
//获取预编译对象
PreparedStatement pre=null;
ResultSet set=null;
try {
pre=con.prepareStatement(sqm);
pre.setInt(1,tid);
set=pre.executeQuery();
while(set.next()){
Message Message=new Message(
set.getInt("mid"),
set.getString("mcontent"),
set.getInt("uid"),
null,
set.getInt("tid"),
null,
set.getTimestamp("mcreate"),
set.getInt("mzan"),
set.getInt("mxu"));
mist.add(Message);
}
} catch (Exception e) {
throw new RuntimeException(e);
}finally{
JdbcUtil.release(set, pre, con);
}
return mist;
}
//4 点赞 点嘘
public int changeZanXu(int mid,int zanXu){
//获取链接
Connection con=JdbcUtil.getCon();
//准备sqm模板
String sql;
if(zanXu==1){
sql="update tab_Message set mzan=mzan+1 where mid=?";
}else{
sql="update tab_Message set mxu=mxu+1 where mid=?";
}
//获取预编译对象
PreparedStatement pre=null;
int hang=0;
try {
pre=con.prepareStatement(sql);
pre.setInt(1,mid);
hang=pre.executeUpdate();
} catch (Exception e) {
throw new RuntimeException(e);
}finally{
JdbcUtil.release(null, pre, con);
}
return hang;
}
//根据mid获取
public Message getOneBymid(int mid){
Message m=null;
//获取链接
Connection con=JdbcUtil.getCon();
//准备sqm模板
String sqm="select * from tab_Message where mid=?";
//获取预编译对象
PreparedStatement pre=null;
ResultSet set=null;
try {
pre=con.prepareStatement(sqm);
pre.setInt(1,mid);
set=pre.executeQuery();
if(set.next()){
m=new Message(
set.getInt("mid"),
set.getString("mcontent"),
set.getInt("uid"),
null, set.getInt("tid"),
null, set.getTimestamp("mcreate"),
set.getInt("mzan"),
set.getInt("mxu"));
}
} catch (Exception e) {
throw new RuntimeException(e);
}finally{
JdbcUtil.release(set, pre, con);
}
return m;
}
public int deleteAllByTid(int tid) {
//获取链接
Connection con=JdbcUtil.getCon();
//准备sqm模板
String sqm="delete from tab_Message where tid=?";
//获取预编译对象
PreparedStatement pre=null;
int hang=0;
try {
pre=con.prepareStatement(sqm);
pre.setInt(1, tid);
hang=pre.executeUpdate();
} catch (Exception e) {
throw new RuntimeException(e);
}finally{
JdbcUtil.release(null, pre, con);
}
return hang;
}
}
css样式
1.css
.tab1{
border:1px solid blue;
width:400px;
margin:200px auto;
border-collapse: collapse;
}
.tab2{
border:1px solid blue;
width:800px;
margin:10px auto;
border-collapse: collapse;
}
td,th{
border:1px solid blue;
padding:10px;
}
h2{
text-align: center;
color:blue;
margin:10px;
}
h3{
text-align: center;
margin:10px;
color:red;
}
div{
text-align: center;
}
bbs.css
#tab_login,#tab_title_add{
width:1000px;
height:200px;
margin:200px auto;
border:1px solid blue;
border-collapse: collapse;
}
#tab_title_list{
width:600px;
margin:50px auto;
border:1px solid blue;
border-collapse: collapse;
}
#headphoto{
margin:auto;
}
td,th{
border:1px solid blue;
padding:10px;
}
h3{
background-color: #cccccc;
color:red;
text-align: center;
}
h1{
background-color: #aaaaaa;
color:blue;
text-align: center;
}
div{
margin:2px;
padding:5px;
}
#div_title_dateil{
width:1000px;
margin:2px auto;
border:1px solid blue;
}
#dateil_head{
text-align: center;
font-size: 28px;
color:#aacc99;
font-weight: bold;
}
#dateil_message{
text-align: right;
font-weight: bold;
font-size: 14px;
}
#dateil_content{
text-indent:50px;
font-weight: bold;
font-size: 20px;
}
hr{
margin:5px;
}
.cla_ly{
width:1000px;
margin:1px auto;
border:1px solid blue;
}
.cla_ly_head{
font-weight: bold;
}
.cla_ly_content{
text-indent:50px;
}
#tab_ly_add{
margin:2px auto;
width:600px;
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>java37_forum_plus</display-name>
<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>
<servlet>
<description></description>
<display-name>UserLoginServlet</display-name>
<servlet-name>UserLoginServlet</servlet-name>
<servlet-class>com.zhiyou.servlet.UserLoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserLoginServlet</servlet-name>
<url-pattern>/user/login</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>TitleGetAllServlet</display-name>
<servlet-name>TitleGetAllServlet</servlet-name>
<servlet-class>com.zhiyou.servlet.TitleGetAllServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TitleGetAllServlet</servlet-name>
<url-pattern>/title/getAll</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>TitleAddOneServlet</display-name>
<servlet-name>TitleAddOneServlet</servlet-name>
<servlet-class>com.zhiyou.servlet.TitleAddOneServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TitleAddOneServlet</servlet-name>
<url-pattern>/title/addOne</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>TitleDeleteOneServlet</display-name>
<servlet-name>TitleDeleteOneServlet</servlet-name>
<servlet-class>com.zhiyou.servlet.TitleDeleteOneServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TitleDeleteOneServlet</servlet-name>
<url-pattern>/title/deleteOne</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>TitleGetOneServlet</display-name>
<servlet-name>TitleGetOneServlet</servlet-name>
<servlet-class>com.zhiyou.servlet.TitleGetOneServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TitleGetOneServlet</servlet-name>
<url-pattern>/title/getOne</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>TitleGetAllByUid</display-name>
<servlet-name>TitleGetAllByUid</servlet-name>
<servlet-class>com.zhiyou.servlet.TitleGetAllByUid</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TitleGetAllByUid</servlet-name>
<url-pattern>/title/getAllByUid</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>MessageAddOneServlet</display-name>
<servlet-name>MessageAddOneServlet</servlet-name>
<servlet-class>com.zhiyou.servlet.MessageAddOneServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MessageAddOneServlet</servlet-name>
<url-pattern>/message/addOne</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>MessageZanXu</display-name>
<servlet-name>MessageZanXu</servlet-name>
<servlet-class>com.zhiyou.servlet.MessageZanXu</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MessageZanXu</servlet-name>
<url-pattern>/message/zanXu</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>UserLoginRegistServlet</display-name>
<servlet-name>UserLoginRegistServlet</servlet-name>
<servlet-class>com.zhiyou.servlet.UserLoginRegistServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserLoginRegistServlet</servlet-name>
<url-pattern>/user/regist</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>UserYzmServlet</display-name>
<servlet-name>UserYzmServlet</servlet-name>
<servlet-class>com.zhiyou.servlet.UserYzmServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserYzmServlet</servlet-name>
<url-pattern>/user/yzm</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>UserHeadServlet</display-name>
<servlet-name>UserHeadServlet</servlet-name>
<servlet-class>com.zhiyou.servlet.UserHeadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserHeadServlet</servlet-name>
<url-pattern>/user/head</url-pattern>
</servlet-mapping>
</web-app>
6 功能1 登录
登录页:/jsp/user_login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>论坛登录界面</title>
<link type="text/css" rel="stylesheet" href="<c:url value='/css/1.css'/>">
</head>
<body>
<%String x=(String)request.getAttribute("message");
if(x!=null){
out.print("<font color='red'>"+x+"</font>");
}
%>
<a href="<c:url value='/jsp/user_regist.jsp'/>">注册</a>
<form action="<c:url value='/user/login'/>" method="post">
<table class="tab1">
<tr>
<th colspan="2">论坛登录</th>
</tr>
<tr>
<th>用户名称:</th>
<td><input type="text" name="uname"/></td>
</tr>
<tr>
<th>用户密码:</th>
<td><input type="password" name="upwd"/></td>
</tr>
<tr>
<th><img src="<c:url value='/user/yzm'/>" id="img_yzm"/></th>
<td><input type="text" name="uyzm"/></td>
</tr>
<tr>
<th colspan="2">
<input type="reset" value="重置"/>
<input type="submit" value="登录"/>
</th>
</tr>
</table>
</form>
<!-- 添加js事件 点击图片 图片更新 -->
<script type="text/javascript">
//文档加载完毕 给img_yzm注册点击事件
window.onload=function(){
//获取img_yzm
var oimg=document.getElementById("img_yzm");
oimg.onclick=function(){
//请求时 为了不使用缓存 添加一个无用的参数 参数值每次不同即可
this.src="<c:url value='/user/yzm?n='/>"+Math.random();
}
}
</script>
</body>
</html>
用户登录servlet---/user/login
UserLoginServlet.java
package com.zhiyou.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zhiyou.dao.UserDao;
import com.zhiyou.entity.User;
public class UserLoginServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1 设置部门集
req.setCharacterEncoding("UTF-8");
//2 获取请求参数
String uname=req.getParameter("uname");
String upwd=req.getParameter("upwd");
String uyzm=req.getParameter("uyzm");
//3 访问数据库
User user=new UserDao().getOneByUname(uname);
//4 判断
String message="";
if(user==null){
message="账号不存在,请先注册!";
}else if(!user.getUpwd().equals(upwd)){
message="密码错误,请重新登录!";
}else {
String yzm=req.getSession().getAttribute("yzm")+"";
if(!uyzm.equals(yzm)){
message="验证码错误!";
}
}
if(!message.isEmpty()){
req.setAttribute("message", message);
req.getRequestDispatcher("/jsp/user_login.jsp").forward(req, resp);
return;
}
//跳转到话题管理页面
req.getSession().setAttribute("user", user);
resp.sendRedirect(req.getServletContext().getContextPath()+"/jsp/title_manager.jsp");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
验证码servlet---/user/yzm
UserYzmServlet.java
package com.zhiyou.servlet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UserYzmServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String message="3456789abcdefghjkmnpqstuvwxy";
//1 在内存中开辟空间 用于画画
BufferedImage bin=new BufferedImage(200, 50, BufferedImage.TYPE_INT_RGB);
//2 获取画笔
Graphics2D g=(Graphics2D)bin.getGraphics();
//3 涂染料 画背景
g.setColor(Color.WHITE);
//4 画背景:长方形
g.fillRect(2, 2, 195, 45);
//5 画主题
//随机四五个字符
String str="";
for (int i = 0; i <4; i++) {
str+=message.charAt((int)(Math.random()*message.length()));
}
//给字符设置文字样式
Font font=new Font(null, Font.BOLD, 34);
g.setFont(font);
//把字符串中的所有字符画到画布上
for (int i = 0; i < str.length(); i++) {
//笔蘸墨
g.setColor(new Color((int)(Math.random()*100+120), (int)(Math.random()*100+120), (int)(Math.random()*100+120)));
//写字
g.drawString(str.charAt(i)+"", i*45+10, 40);
}
//画干扰线
for (int i = 0; i < (int)(Math.random()*5+5); i++) {
g.setColor(new Color((int)(Math.random()*50+120), (int)(Math.random()*50+120), (int)(Math.random()*50+120)));
g.drawLine(2, (int)(Math.random()*43+2), 195, (int)(Math.random()*43+2));
}
//把验证码的信息装入session
request.getSession().setAttribute("yzm", str);
//把内存中图片的信息通过respionse的输出流 响应给客户端
ImageIO.write(bin, "JPEG", response.getOutputStream());
}
/**
* @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);
}
}
登录测试
7 功能2 查询所有话题
管理展示页:/jsp/title_manager.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!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">
<link type="text/css" rel="stylesheet" href="<c:url value='/css/bbs.css'/>"/>
<title>话题管理页面</title>
</head>
<body>
<!-- 判断request域中是否有titleList 如果没有去servlet要 -->
<c:if test="${empty requestScope.titleList}">
<jsp:forward page="/title/getAll"/>
</c:if>
<c:if test="${not empty requestScope.head}">
<h1>${requestScope.head}</h1>
</c:if>
<table id="tab_title_list">
<tr>
<th>顺序</th>
<th>编号</th>
<th>标题</th>
<th>关注</th>
<th>时间</th>
<th>作者</th>
<th>操作</th>
</tr>
<c:forEach items="${requestScope.titleList}" var="title" varStatus="vs">
<tr>
<td>${vs.index}</td>
<td><a href="<c:url value='/title/getOne?tid=${title.tid}'/>">${title.tid}</a></td>
<td><a href="<c:url value='/title/getOne?tid=${title.tid}'/>">${title.tname}</a></td>
<td>${title.tcount}</td>
<td><fmt:formatDate pattern="yyyy-MM-dd HH:mm:ss" value="${title.tcreate}" /></td>
<td><a href="<c:url value='/title/getAllByUid?uid=${title.uid}'/>">${title.user.uname}</a></td>
<td>
<c:if test="${title.uid eq sessionScope.user.uid}">
<a href="<c:url value='/title/deleteOne?tid=${title.tid}'/>">删除</a>
</c:if>
</td>
</tr>
</c:forEach>
</table>
<c:if test="${not empty requestScope.message}">
<h3>${requestScope.message}</h3>
</c:if>
<h3><a href="<c:url value='/jsp/title_add.jsp'/>">添加话题</a></h3>
</body>
</html>
获取全部话题servlet---/title/getAll
TitleGetAllServlet.java
package com.zhiyou.servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zhiyou.dao.TitleDao;
import com.zhiyou.dao.UserDao;
import com.zhiyou.entity.Title;
public class TitleGetAllServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Title> list=new TitleDao().getAll();
request.setAttribute("titleList", list);
//给所有话题的作者设置值
UserDao userDao=new UserDao();
for (Title title : list) {
title.setUser(userDao.getOneById(title.getUid()));
}
request.getRequestDispatcher("/jsp/title_manager.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
管理展示测试
8 功能3 添加
添加话题页 /jsp/title_add.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
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">
<link type="text/css" rel="stylesheet" href="<c:url value='/css/bbs.css'/>"/>
<title>话题添加页面</title>
</head>
<body>
<h1>添加话题</h1>
<form action="<c:url value='/title/addOne'/>" method="post">
<table id="tab_title_add">
<tr>
<th>话题标题:</th>
<td><input type="text" name="tname"/></td>
</tr>
<tr>
<th>话题内容:</th>
<td>
<textarea rows="30" cols="100" name="tcontent"></textarea>
</td>
</tr>
<tr>
<th colspan="2">
<input type="reset" value="重置"/>
<input type="submit" value="添加"/>
</th>
</tr>
</table>
</form>
<h3><a href="javascript:history.go(-1);">回到管理页面</a></h3>
</body>
</html>
添加话题servlet---/title/addOne
TitleAddOneServlet.java
package com.zhiyou.servlet;
import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zhiyou.dao.TitleDao;
import com.zhiyou.entity.Title;
import com.zhiyou.entity.User;
public class TitleAddOneServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
//设置编码集
req.setCharacterEncoding("utf-8");
//获取参数
String tname=req.getParameter("tname");
String tcontent=req.getParameter("tcontent");
int uid=((User)req.getSession().getAttribute("user")).getUid();
//封装数据
Title title=new Title(null, tname, tcontent, 0, new Date(), uid, null);
//调用数据库
new TitleDao().addOne(title);
//跳转
req.setAttribute("message", "添加'"+tname+"'话题成功!");
req.getRequestDispatcher("/jsp/title_manager.jsp").forward(req, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
添加测试
9 功能4 删除
话题删除servlet---/title/deleteOne
TitleDeleteOneServlet.java
package com.zhiyou.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zhiyou.dao.MessageDao;
import com.zhiyou.dao.TitleDao;
public class TitleDeleteOneServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
//设置编码集
req.setCharacterEncoding("utf-8");
//获取参数
int tid=Integer.parseInt(req.getParameter("tid"));
//调用数据库
new MessageDao().deleteAllByTid(tid);//先删除话题下的留言
new TitleDao().deleteOneByTid(tid);
//跳转
req.setAttribute("message", "删除'"+tid+"'话题成功!");
req.getRequestDispatcher("/jsp/title_manager.jsp").forward(req, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
删除测试
10 功能5 展示某个用户的话题列表
根据uid获取话题---/title/getAllByUid
TitleGetAllByUid.java
package com.zhiyou.servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zhiyou.dao.TitleDao;
import com.zhiyou.dao.UserDao;
import com.zhiyou.entity.Title;
public class TitleGetAllByUid extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int uid=Integer.parseInt(request.getParameter("uid"));
List<Title> list=new TitleDao().getAll(uid);
request.setAttribute("titleList", list);
//给所有话题的作者设置值
UserDao userDao=new UserDao();
for (Title title : list) {
title.setUser(userDao.getOneById(title.getUid()));
}
request.setAttribute("head", "用户'"+list.get(0).getUser().getUname()+"'的所有话题");
request.getRequestDispatcher("/jsp/title_manager.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
在管理页显示head提示信息
<c:if test="${not empty requestScope.head}">
<h1>${requestScope.head}</h1>
</c:if>
单个用户空间测试
11 功能6 展示某个话题详情
话题详情页 /jsp/title_dateil.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!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">
<link type="text/css" rel="stylesheet" href="<c:url value='/css/bbs.css'/>"/>
<title>话题详情页面</title>
</head>
<body>
<c:if test="${not empty requestScope.head}">
<h1>${requestScope.head}</h1>
</c:if>
<c:if test="${not empty requestScope.message}">
<h3>${requestScope.message}</h3>
</c:if>
<div id="div_title_dateil">
<div id="dateil_head">${requestScope.title.tname}</div>
<div id="dateil_message">作者:${requestScope.title.user.uname} |
时间:<fmt:formatDate pattern="yyyy-MM-dd HH:mm:ss" value="${requestScope.title.tcreate}" /> |
关注:${requestScope.title.tcount}</div>
<div id="dateil_content">${requestScope.title.tcontent}</div>
</div>
<div id="headphoto">
<img src="<c:url value='/user/head?uid=${sessionScope.user.uid}'/>" align="middle" height="100px" width="150px" alt="图片加载失败" />
</div>
<hr/>
<c:forEach items="${requestScope.title.messageList}" var="ly">
<div class="cla_ly">
<div class="cla_ly_head">
<a href="<c:url value='/title/getAllByUid?uid=${ly.uid}'/>">${ly.user.uname}</a>
<fmt:formatDate pattern="yyyy-MM-dd HH:mm:ss" value="${ly.mcreate}" />
<span class="span_zanxu">
<a href="<c:url value='/message/zanXu?mid=${ly.mid}&tid=${title.tid}&zanXu=1'/>">赞</a>:${ly.mzan} |
<a href="<c:url value='/message/zanXu?mid=${ly.mid}&tid=${title.tid}&zanXu=-1'/>">嘘</a>:${ly.mxu}
</span>
</div>
<div class="cla_ly_content">
${ly.mcontent}
</div>
</div>
</c:forEach>
<form action="<c:url value='/message/addOne'/>" method="post">
<input type="hidden" name="tid" value="${title.tid}"/>
<table id="tab_ly_add">
<tr>
<td>
<textarea rows="5" cols="40" name="mcontent"></textarea>
</td>
<th>
<input type="submit" value="留言"/>
</th>
</tr>
</table>
</form>
<h3><a href="<c:url value='/jsp/title_manager.jsp'/>">回到管理页面</a></h3>
</body>
</html>
根据tid获取话题详情Servlet---/title/getOne
TitleGetOneServlet.java
package com.zhiyou.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import com.zhiyou.dao.MessageDao;
import com.zhiyou.dao.TitleDao;
import com.zhiyou.dao.UserDao;
import com.zhiyou.entity.Message;
import com.zhiyou.entity.Title;
public class TitleGetOneServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int tid=Integer.parseInt(request.getParameter("tid"));
Title title=new TitleDao().getOneByTid(tid);
UserDao userDao=new UserDao();
title.setUser(userDao.getOneById(title.getUid()));
List<Message> list=new MessageDao().getAllByTid(title.getTid());
for (Message ly : list) {
ly.setUser(userDao.getOneById(ly.getUid()));
}
title.setMessageList(list);
String path=request.getServletContext().getRealPath("/imgs/")+title.getUser().getHead();
System.out.println(path);
// File file=new File(path);
// FileInputStream fis = new FileInputStream(file);
// ServletOutputStream fos = response.getOutputStream();
// IOUtils.copy(fis,fos);
// request.setAttribute("fos", fos);
request.setAttribute("path", path);
request.setAttribute("title", title);
request.setAttribute("head", "话题'"+title.getTname()+"'的详情");
request.getRequestDispatcher("/jsp/title_dateil.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
展示单个话题测试
12 功能7 添加留言
添加留言Servlet---/message/addOne
MessageAddOneServlet.java
package com.zhiyou.servlet;
import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zhiyou.dao.MessageDao;
import com.zhiyou.entity.Message;
import com.zhiyou.entity.User;
public class MessageAddOneServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");//设置编码集
String lcontent=request.getParameter("mcontent");//获取留言内容
int tid=Integer.parseInt(request.getParameter("tid"));//获取话题编号
User user=(User)(request.getSession().getAttribute("user"));//获取当前登录者的信息
Message ly=new Message(null, lcontent, user.getUid(), user, tid, null, new Date(), 0, 0);//创建留言对象
new MessageDao().addOne(ly);//添加数据库
request.setAttribute("message", "添加留言成功!");//设置页面信息
request.getRequestDispatcher("/title/getOne?tid="+tid).forward(request, response);//跳转到详情页面
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
添加留言测试
13 功能8 留言点赞
留言点赞Servlet---/message/zanXu
MessageZanXu.java
package com.zhiyou.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zhiyou.dao.MessageDao;
public class MessageZanXu extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int mid=Integer.parseInt(request.getParameter("mid"));
int tid=Integer.parseInt(request.getParameter("tid"));
int zanXu=Integer.parseInt(request.getParameter("zanXu"));
new MessageDao().changeZanXu(mid, zanXu);
request.setAttribute("message", "点"+(zanXu>0?"赞":"嘘")+"成功!");//设置页面信息
request.getRequestDispatcher("/title/getOne?tid="+tid).forward(request, response);//跳转到详情页面
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
留言点赞测试
14 功能补充9 注册与上传头像
注册页 /jsp/user_regist.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="<c:url value='/css/1.css'/>">
<meta charset="UTF-8">
<title>用户注册页面</title>
</head>
<body>
<h1>用户注册表单</h1>
<form method="post" action="<c:url value='/user/regist'/>" enctype="multipart/form-data">
<table class="tab1">
<tr>
<th>用户名称</th>
<td><input type="text" name="uname" required="required"></input></td>
</tr>
<tr>
<th>用户密码</th>
<td><input type="password" name="upw" required="required"></input></td>
</tr>
<tr>
<th>用户性别</th>
<td><input type="radio" name="sex" value="男" checked="checked">男</input>/<input type="radio" name="sex" value="女">女</input></td>
</tr>
<tr>
<th>用户头像</th>
<td><input type="file" name="uphoto" ></input></td>
</tr>
<tr>
<td><input type="reset"></input></td>
<td><input type="submit"></input></td>
</tr>
</table>
</form>
</body>
</html>
注册Servlet---/user/regist
UserLoginRegistServlet.java
package com.zhiyou.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import com.zhiyou.dao.UserDao;
import com.zhiyou.entity.User;
public class UserLoginRegistServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DiskFileItemFactory factory=new DiskFileItemFactory();//创建工厂对象
ServletFileUpload upload=new ServletFileUpload(factory);//创建一个多部件表单解析器对象 并关联工厂对象
String message="";//提示信息
User user=new User();//创建user
FileOutputStream out=null;//创建输出流
try {
List<FileItem> list=upload.parseRequest(request);//获取请求所有参数放入集合中
// String fieldValue=list.get(3).getString("UTF-8");//获取第三个即文件参数的值,因为是文件所以不能直接获取需要通过流
String fileName=list.get(3).getName();//获取第三个参数的名字
InputStream in=list.get(3).getInputStream();//获取输入流
System.out.println(fileName);
String path=request.getServletContext().getRealPath("/imgs/")+UUID.randomUUID()+".jpg";//创建输出路径
System.out.println(path);
File muDiFile=new File(path);//创建文件
out=new FileOutputStream(muDiFile);//创建输出流
IOUtils.copy(in, out);//将输入流拷贝☞输出流
//创建user对象将参数一一对应放入
user = new User(
null,//uid自增
list.get(0).getString("UTF-8"),//第一个参数姓名
list.get(1).getString("UTF-8"),//第二个参数密码
list.get(2).getString("UTF-8"),//第三个参数性别
new Date(),//日期
0,//积分
muDiFile.getName()//传的是文件名
);
new UserDao().AddOne(user);//调用Dao层加入数据库
message="注册成功";//设置成功信息
request.setAttribute("message", message);//放入request域中
}catch (Exception e) {
throw new RuntimeException(e);
}finally{
if(out!=null){
out.close();//关闭创建的输出流,输入流只调用了未创建不用关
}
}
//设置两个编码集
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//转发至登陆界面
request.getRequestDispatcher("/jsp/user_login.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
显示头像Servlet---/user/head
UserHeadServlet.java
package com.zhiyou.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import com.zhiyou.dao.TitleDao;
import com.zhiyou.dao.UserDao;
import com.zhiyou.entity.Title;
public class UserHeadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int uid=Integer.parseInt(request.getParameter("uid"));
System.out.println(uid);
UserDao userDao=new UserDao();
String fileName=userDao.getOneById(uid).getHead();
String path=request.getServletContext().getRealPath("/imgs/")+fileName;
File file=new File(path);
FileInputStream fis = new FileInputStream(file);
IOUtils.copy(fis, response.getOutputStream());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}