用户可以选择登录,可以自行注册,登陆后,可以退出登录,再登别的账号(不关闭窗口,不回退,我所用到的是在用户登录后将user存入session域,点击退出登录之后就写一个方法,将session里的user置为空,这样退出后,用户只能再次登录)。在登录之后,才能看到的自己的博客,并且每个用户只能对自己的博客进行增删改查。即User与Blog之间是一对多的关系。
至于导包什么的,参考我之前总结的:https://blog.csdn.net/zl_stepbystep/article/details/80467870
项目目录结构:
配置文件:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>SSH01</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 让Spring容器随着Web的启动而创建的监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置Spring配置文件位置参数 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 扩大session作用范围 -->
<!-- 注意:web.xml的执行是有顺序的。任何filter一定要在Struts的filter之前调用,因为Struts一旦进去流程,是没有放行代码的,后序的过滤器都不会被执行-->
<filter>
<filter-name>openSessionInView</filter-name>
<filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openSessionInView</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Struts2核心过滤器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapmping>
<filter-nae>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">
<!-- 指定Spring读取db.properties配置 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置c3p0连接池 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 配置核心事务管理器 -->
<bean name="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 配置通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 以后配置大量事务时,需要使用通配符配置增删改查 -->
<!-- 以方法为单位,指定方法应该有什么事务属性,isolation隔离级别,propagation传播行为,read-only是否只读 -->
<tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
<tx:method name="add*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
<tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
<tx:method name="motified*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
<tx:method name="remove*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
<tx:method name="delete*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
<tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true"/>
<tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 配置将通知织入目标对象 -->
<aop:config>
<!-- 配置切点 -->
<aop:pointcut expression="execution(* com.zl.service.impl.*ServiceImpl.*(..))" id="txPc"/>
<!-- 配置切面 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPc"/>
</aop:config>
<!-- 将SessionFactory配置到Spring容器中 -->
<!-- 方案1.引入hibernate主配置文件,不推荐
<bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
</bean>-->
<!-- 方案2 配置hibernate基本信息-->
<bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!-- 将连接池注入到sessionFactory中,hibernate会通过连接池 获得连接-->
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<!-- <prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>
<prop key="hibernate.connection.url">jdbc:mysql://localhost:3306/testhibernate?useUnicode=true&characterEncoding=UTF-8</prop>
<prop key="hibernate.connection.username">root</prop>
<prop key="hibernate.connection.password">123456</prop>-->
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<!-- 上面5个必须配置,下面三个可选 -->
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<!-- 引入ORM元数据,指定ORM元数据所在的包路径,Spring会自动读取包中的所有配置 -->
<property name="mappingDirectoryLocations" value="classpath:com/zl/domain"></property>
</bean>
<!-- action -->
<!-- 注意,Action对象作用范围一定是多例的,这样才符合Struts2架构 -->
<bean name="userAction" class="com.zl.action.UserAction" scope="prototype">
<property name="usi" ref="usi"></property>
</bean>
<bean name="blogAction" class="com.zl.action.BlogAction" scope="prototype">
<property name="bsi" ref="bsi"></property>
</bean>
<!-- service -->
<bean name="usi" class="com.zl.service.impl.UserServiceImpl">
<property name="ud" ref="userDao"></property>
</bean>
<bean name="bsi" class="com.zl.service.impl.BlogServiceImpl">
<property name="blogDao" ref="blogDao"></property>
</bean>
<!-- dao -->
<bean name="userDao" class="com.zl.dao.impl.UserDaoImpl">
<!-- 注入sessionFactory -->
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean name="blogDao" class="com.zl.dao.impl.BlogDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
</beans>
db.properties
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///test
jdbc.user=root
jdbc.password=123456
struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- struts.objectFactory = spring 将Action的创建交给Spring容器
struts.objectFactory.spring.autoWire = name Spring负责自动装配Action依赖属性-->
<constant name="struts.objectFactory" value="spring"></constant>
<constant name="struts.devMode" value="true" />
<package name="SHH01" namespace="/" extends="struts-default">
<!-- 声明拦截器 -->
<interceptors>
<interceptor name="privilege" class="com.zl.interceptor.PrivilegeInterceptor" />
<interceptor-stack name="myStack">
<interceptor-ref name="defaultStack" />
<interceptor-ref name="privilege"></interceptor-ref>
</interceptor-stack>
</interceptors>
<global-exception-mappings>
<exception-mapping result="error" exception="java.lang.RuntimeException"></exception-mapping>
</global-exception-mappings>
<!-- 用户登录和注册 -->
<action name="UserAction_*" class="userAction" method="{1}">
<result>/index.jsp</result>
<result name="toHome" type="redirect">/index.jsp</result>
<result name="LOGOUT">/index.jsp</result>
<result name="error">/login.jsp</result>
<result name="TOREGISTER">/register.jsp</result>
<result ></result>
</action>
<!-- 关于book操作 -->
<action name="BlogAction_*" class="blogAction" method="{1}">
<!-- 在Action中使用自定义拦截器 -->
<interceptor-ref name="myStack"/>
<result name="login">/login.jsp</result>
<result name="toFINDALL">/findall.jsp</result>
<result name="toADD">/add.jsp</result>
<result name="ADD" type="redirect">BlogAction_tofindall</result>
<result name="DELETESUCCESS" type="redirect">BlogAction_tofindall</result>
<result name="BLOGDETAIL">/update.jsp</result>
<result name="UPDATESUCCESS" type="redirect">BlogAction_tofindall</result>
</action>
</package>
<!-- package里元素必须按照一定的顺序排列
result-types
interceptors
default-interceptor-ref
default-action-ref
default-class-ref
global-results
global-exception-mappings
action*(就是所有的action放到最后)
-->
</struts>
src下的.java文件
(1)User类相关的:
User.java
package com.zl.domain;
public class User {
private Long user_id;
private String user_code;
private String user_name;
private String user_password;
//一对多
private Set<Blog> blogs = new HashSet<Blog>();
public Set<Blog> getBlogs() {
return blogs;
}
public void setBlogs(Set<Blog> blogs) {
this.blogs = blogs;
}
public Long getUser_id() {
return user_id;
}
public void setUser_id(Long user_id) {
this.user_id = user_id;
}
public String getUser_code() {
return user_code;
}
public void setUser_code(String user_code) {
this.user_code = user_code;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getUser_password() {
return user_password;
}
public void setUser_password(String user_password) {
this.user_password = user_password;
}
@Override
public String toString() {
return "User [user_id=" + user_id + ", user_code=" + user_code + ", user_name=" + user_name + ", user_password="
+ user_password + "]";
}
}
User.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.zl.domain" >
<class name="User" table="sys_user" >
<id name="user_id" >
<generator class="native"></generator>
</id>
<property name="user_code" ></property>
<property name="user_name" ></property>
<property name="user_password" ></property>
<set name="blogs">
<key column="blog_user_id"></key>
<one-to-many class="Blog"/>
</set>
</class>
</hibernate-mapping>
UserAction.java
package com.zl.action;
public class UserAction extends ActionSupport implements ModelDriven<User>{
private IUserService usi;
private User user = new User();
public void setUsi(IUserService usi) {
this.usi = usi;
}
//登录
public String login() throws Exception {
//1.调用Service执行登录逻辑
User u = usi.getUserByCodePassword(user);
//2.将返回的User对象放入session域
ActionContext.getContext().getSession().put("user", u);
//3.重定向到项目首页
return "toHome";
}
//下线
public String logout() throws Exception {
ActionContext.getContext().getSession().put("user", null);
return "LOGOUT";
}
//跳转到注册页面
public String toRegister() {
return "TOREGISTER";
}
//判断是否注册过
public String isRegistered() throws IOException {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html;charset=UTF-8");
String user_code = request.getParameter("user_code");
if (usi.isRegistered(user_code)) {//此user_code已经被用过了
response.getWriter().print("true");
System.out.println("Action true");
} else {
response.getWriter().print("false");
System.out.println("Action false");
}
return null;
}
//注册
public String register() {
usi.saveUser(user);
return "REGISTER";
}
@Override
public User getModel() {
return user;
}
}
——————————————User的Service层———————————————
IUserService
package com.zl.service;
import com.zl.domain.User;
public interface IUserService {
//登录
User getUserByCodePassword(User u);
User getUserByCode(String user_code);
//注册用户
void saveUser(User u);
boolean isRegistered(String user_code);
}
UserServiceImpl.java
package com.zl.service.impl;
public class UserServiceImpl implements IUserService {
private IUserDao ud;
public IUserDao getUd() {
return ud;
}
public void setUd(IUserDao ud) {
this.ud = ud;
}
@Override
public User getUserByCodePassword(User u) {
//1.根据登录名称查询登录用户
User existU = ud.getByUserCode(u.getUser_code());
//2.判断用户是否存在,不存在=》抛出异常,提示用户名不存在
if(existU == null) {
throw new RuntimeException("用户不存在!");
}
//3.判断用户密码是否正确,不正确=》抛出异常,提示密码错误
if(!existU.getUser_password().equals(u.getUser_password())) {
throw new RuntimeException("用户密码错误!");
}
//4.返回查询到的用户对象
return existU;
}
@Override
public boolean isRegistered(String user_code) {
boolean flag = true; //true表示用户存在
//1.根据登录名称查询登录用户
User existU = ud.getByUserCode(user_code);
//2.判断用户是否存在,不存在,返回false
if(existU == null) {
flag = false;
System.out.println("用户不存在,可以注册");
}else{
System.out.println("用户存在,不能注册");
}
//3.返回查询到的用户对象
return flag;
}
@Override
public void saveUser(User u) {
ud.save(u);
}
@Override
public User getUserByCode(String user_code) {
User u = ud.getByUserCode(user_code);
return u;
}
}
————————————————User的DAO层————————————————————
IUserDao .java
package com.zl.dao;
public interface IUserDao {
//根据登录名称查询User对象
User getByUserCode(String usercode);
void save(User u);
}
UserDaoImpl.java
package com.zl.dao.impl;
//HibernateDaoSupport为dao注入sessionFactory
public class UserDaoImpl extends HibernateDaoSupport implements IUserDao {
@Override
public User getByUserCode(final String usercode) {
//HQL
return getHibernateTemplate().execute(new HibernateCallback<User>() {
@Override
public User doInHibernate(Session session) throws HibernateException {
String hql = "from User where user_code = ?";
Query query = session.createQuery(hql);
query.setParameter(0, usercode);
User user = (User) query.uniqueResult();
return user;
}
});
//Criteria
/*DetachedCriteria dc = DetachedCriteria.forClass(User.class);
dc.add(Restrictions.eq("user_code", usercode));
List<User> list =(List<User>)getHibernateTemplate().findByCriteria(dc);
if(list != null && list.size()>0) {
return list.get(0);
}else {
return null;
}*/
}
@Override
public void save(User u) {
getHibernateTemplate().save(u);
}
}
拦截器PrivilegeInterceptor.java
package com.zl.interceptor;
public class PrivilegeInterceptor extends AbstractInterceptor{
private static final long serialVersionUID = 2L;
@Override
public String intercept(ActionInvocation invocation) throws Exception {
//得到ActionContext
ActionContext actionContext = invocation.getInvocationContext();
//获取user对象
Object user = actionContext.getSession().get("user");
if(user != null) {
return invocation.invoke(); // 继续向下执行
}else {
actionContext.put("msg", "您还未登录,请先登录!");
return Action.LOGIN; //如果用户不存在,返回login值
}
}
}
(2)Blog类相关的:
Blog.java
package com.zl.domain;
public class Blog {
private Long blog_id;
private String blog_title;
private String blog_label;
private String blog_context;
//多对一
private User user;
//并不与数据库表中的某个字段对应,只是为了接收表单参数
private Long user_id;
public Long getUser_id() {
return user_id;
}
public void setUser_id(Long user_id) {
this.user_id = user_id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Long getBlog_id() {
return blog_id;
}
public void setBlog_id(Long blog_id) {
this.blog_id = blog_id;
}
public String getBlog_title() {
return blog_title;
}
public void setBlog_title(String blog_title) {
this.blog_title = blog_title;
}
public String getBlog_label() {
return blog_label;
}
public void setBlog_label(String blog_label) {
this.blog_label = blog_label;
}
public String getBlog_context() {
return blog_context;
}
public void setBlog_context(String blog_context) {
this.blog_context = blog_context;
}
@Override
public String toString() {
return "Blog [blog_id=" + blog_id + ", blog_title=" + blog_title + ", blog_label=" + blog_label
+ ", blog_context=" + blog_context + ", user=" + user + ", user_id=" + user_id + "]\n";
}
}
Blog.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.zl.domain" >
<class name="Blog" table="sys_blog" >
<id name="blog_id" >
<generator class="native"></generator>
</id>
<property name="blog_title" ></property>
<property name="blog_label" ></property>
<property name="blog_context" ></property>
<many-to-one name="user" column="blog_user_id" class="User" cascade="save-update"></many-to-one>
</class>
</hibernate-mapping>
BlogAction.java
package com.zl.action;
public class BlogAction extends ActionSupport implements ModelDriven<Blog>{
private IBlogService bsi;
private Blog blog = new Blog();
private List<Blog> blogList;
private User user;
private int currentPage; //当前页
//分页显示user的所有博客记录
public String tofindall() {
//在session域中获取user
user = (User) ActionContext.getContext().getSession().get("user");
if(user == null) {
return "login";
}
blogList = bsi.findall(user,currentPage);
ActionContext.getContext().put("bar", bsi.getBar(currentPage, user));
return "toFINDALL";
}
public String toadd() {
return "toADD";
}
public String add() {
//在session域中获取user
user = (User) ActionContext.getContext().getSession().get("user");
bsi.add(user, blog);
return "ADD";
}
public String delete() {
bsi.deleteBlogById(blog.getBlog_id());
return "DELETESUCCESS";
}
public String detail() {
blog = bsi.findBlogById(blog.getBlog_id());
return "BLOGDETAIL";
}
public String update() {
System.out.println(blog);
user = (User) ActionContext.getContext().getSession().get("user");
bsi.updateBlogs(user,blog);
System.out.println(" "+blog);
return "UPDATESUCCESS";
}
@Override
public Blog getModel() {
return blog;
}
//getter setter
public List<Blog> getBlogList() {
return blogList;
}
public void setBlogList(List<Blog> blogList) {
this.blogList = blogList;
}
public void setBsi(IBlogService bsi) {
this.bsi = bsi;
}
public Blog getBlog() {
return blog;
}
public void setBlog(Blog blog) {
this.blog = blog;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
}
————————————Blog 的 Service 层————————————
IBlogService.java
package com.zl.service;
public interface IBlogService {
List<Blog> findall(User user,int currentPage);
int getCount(User user);//查询某个人的博客数量
void add(User user, Blog blog);
int pageNum(User user);
String getBar(int cpage,User user);
void deleteBlogById(Long blog_id);
Blog findBlogById(Long blog_id);
void updateBlogs(User user,Blog blog);
}
BlogServiceImpl.java
package com.zl.service.impl;
public class BlogServiceImpl implements IBlogService {
private IBlogDao blogDao;
private int PAGESIZE = 3;
public IBlogDao getBlogDao() {
return blogDao;
}
public void setBlogDao(IBlogDao blogDao) {
this.blogDao = blogDao;
}
//查询某个user的所有博客
@Override
public List<Blog> findall(User user,int currentPage) {
List<Blog> blogList = blogDao.findallBlogs(user, currentPage,PAGESIZE);
return blogList;
}
//根据查询到的user所有博客,利用List.size得到博客的总数
@Override
public int getCount(User user) {
int count = blogDao.getCount(user);
return count;
}
//根据总记录数,算出需要显示的总页数
@Override
public int pageNum(User user) {
int count = getCount(user);
return count%PAGESIZE == 0 ? count/PAGESIZE : (count/PAGESIZE+1);
}
//页面下方页码超链接
@Override
public String getBar(int currentPage,User user) {
String string = "";
int pagenum = pageNum(user);
for(int i=1; i<=pagenum ;i++) {
if(i != currentPage) {
string += "<a href='BlogAction_tofindall?currentPage="+i+"'>"+i+"</a> ";
}else {
string += i + " ";
}
}
System.out.println(currentPage+" "+pagenum+" "+string);
return string;
}
//给某个user添加博客
@Override
public void add(User user, Blog blog) {
blogDao.addAblog(user,blog);
}
//按照id删除
@Override
public void deleteBlogById(Long blog_id) {
blogDao.deleteABlog(blog_id);
}
//查找指定id的博客
@Override
public Blog findBlogById(Long blog_id) {
Blog blog = blogDao.findABlog(blog_id);
return blog;
}
//更新博客
@Override
public void updateBlogs(User user,Blog blog) {
blogDao.updateBlog(user,blog);
}
}
————————————Blog的Service层————————————
IBlogDao
package com.zl.dao;
public interface IBlogDao {
List<Blog> findallBlogs(User user,int page,int pageSize);//分页查询所有博客
void addAblog(User user, Blog blog);
int getCount(User user);
void deleteABlog(Long blog_id);
Blog findABlog(Long blog_id);
void updateBlog(User user, Blog blog);
}
BlogDaoImpl.java
package com.zl.dao.impl;
public class BlogDaoImpl extends HibernateDaoSupport implements IBlogDao {
@Override
public List<Blog> findallBlogs(User user,final int currentpage,final int pageSize) {
return getHibernateTemplate().execute(new HibernateCallback<List<Blog>>() {
@Override
public List<Blog> doInHibernate(Session session) throws HibernateException {
String hql = "from Blog where user=?";
Query query = session.createQuery(hql);
query.setParameter(0, user);
int begin = (currentpage - 1)*pageSize;
query.setFirstResult(begin);//每一页的第一个
query.setMaxResults(pageSize);//每页的条数
List<Blog> blogs = query.list();
return blogs;
}
});
}
//查询博客的总记录数
@Override
public int getCount(User user) {
int count = getHibernateTemplate().execute(new HibernateCallback<List<Blog>>() {
@Override
public List<Blog> doInHibernate(Session session) throws HibernateException {
String hql = "from Blog where user=?";
Query query = session.createQuery(hql);
query.setParameter(0, user);
List<Blog> blogs = query.list();
return blogs;
}
}).size();
return count;
}
//给user对象添加一条博客
@Override
public void addAblog(User user, Blog blog) {
blog.setUser(user); //blog与User关联
getHibernateTemplate().save(blog);
}
//删除博客
@Override
public void deleteABlog(Long blog_id) {
Blog blog = getHibernateTemplate().get(Blog.class, blog_id);
getHibernateTemplate().delete(blog);
}
//查找博客
@Override
public Blog findABlog(Long blog_id) {
Blog blog = getHibernateTemplate().get(Blog.class, blog_id);
return blog;
}
//更新数据库中的博客
@Override
public void updateBlog(User user,Blog blog) {
// blog.setUser(user);
getHibernateTemplate().update(blog);
blog.setUser(user);
}
}
在写的过程中可以写一个专门用来测试的测试类
HibernateTest.java
package com.zl.test;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class HibernateTest {
@Resource(name="sessionFactory")
private SessionFactory sf;
// @Test
public void test02() {
Session session = sf.openSession();
Transaction tx =session.beginTransaction();
User u = new User();
u.setUser_code("hi");
u.setUser_name("哈哎");
u.setUser_password("12345");
session.save(u);
tx.commit();
session.close();
}
// @Test
public void test01() {
Configuration conf = new Configuration().configure();
SessionFactory sf = conf.buildSessionFactory();
Session session = sf.openSession();
Transaction tx =session.beginTransaction();
User u = new User();
u.setUser_code("Tomy");
u.setUser_name("haha");
session.save(u);
tx.commit();
session.close();
}
@Resource(name="userDao")
private IUserDao ud;
// @Test
public void test03() {
User user = ud.getByUserCode("hi");
System.out.println(user);
}
@Resource(name="usi")
private IUserService us;
// @Test
public void fun04() {
User u = new User();
u.setUser_code("Luna");
u.setUser_name("露娜");
u.setUser_password("888888");
us.saveUser(u);
}
@Resource(name="bsi")
private IBlogService bsi;
@Test
public void fun05() {
User user = us.getUserByCode("Rose");
List<Blog> blog = bsi.findall(user, 1);
System.out.println(blog);
// Blog blog = new Blog();
// blog.setBlog_title("TCP");
// blog.setBlog_label("协议");
// blog.setBlog_context("在不可靠的因特网上提供可靠的、端到端的字节流通信的协议");
//
// bsi.add(u, blog);
}
}
JSP
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>主界面</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/BlogAction_toadd">写博客</a><br>
<a href="${pageContext.request.contextPath}/BlogAction_tofindall">查看我的所有博客 </a><br>
</body>
</html>
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登录页面</title>
</head>
<body>
<p align="center"><font color="orange"> ${requestScope.msg} </font></p>
<br>
<form name="form1" action="${pageContext.request.contextPath}/UserAction_login" method="post">
<table align="center" border="0">
<tr>
<td>登录名:</td>
<td><input type="text" name="user_code" value="${user_code}"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="user_password" value="${user_password}"></td>
</tr>
</table>
<p align="center">
<input type="submit" value="登录">
<input type="reset" value="重置"> <br>
</p>
</form>
<p align="center" ><font color="red"><s:property value="exception.message"/></font></p>
<p align="center" ><font size="2">
还没有账号?<a href="${pageContext.request.contextPath}/UserAction_toRegister">马上去注册</a>
</font></p>
</body>
</html>
register.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>注册页面</title>
</head>
<script language="JavaScript">
var xmlHttp; //Ajax核心对象
var flag; //定义标志位
function createXMLHttp() { //创建XMLHttpRequest核心对象
if (window.XMLHttpRequest) { //判断当前使用浏览器的类型
xmlHttp = new XMLHttpRequest(); //表示使用的为Firefox内核的浏览器
} else { //表示使用的是IE内核的浏览器
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
function checkUserid(user_code) {
createXMLHttp(); //建立xmlHttp核心对象
var url = "UserAction_isRegistered?user_code=" + user_code;
xmlHttp.open("POST", url); //初始化HTTP连接请求对象,设置请求方法,地址
xmlHttp.onreadystatechange = checkUseridCallback; //设置请求对象状态readystate改变时要调用回调函数
xmlHttp.send(null); //发送请求,不传递任何参数
//document.getElementById("msg").innerHTML = "正在验证...";
}
function checkUseridCallback() { //定义回调函数
if (xmlHttp.readyState == 4) { //数据返回完毕
if (xmlHttp.status == 200) { //HTTP操作正常
var text = xmlHttp.responseText; //接收返回的内容
if (text == "true") {//此id已经被用过了
flag = false; //无法提交表单
document.getElementById("msg").innerHTML = "用昵称重复,无法使用,请再次输入!";
} else {
flag = true; //可以提交表单
document.getElementById("msg").innerHTML = "此昵称可以注册!";
}
}
}
}
function checkForm() {
return flag;
}
</script>
<body>
<form action="${pageContext.request.contextPath}/UserAction_register" method="post" οnsubmit="return checkForm()">
<p id="flag"></p>
<p>
用户昵称:<input type="text" name="user_code" οnblur="checkUserid(this.value)" />
<font id="msg" color="red"></font>
</p>
<p>
密 码:<input type="password" name="user_password" />
</p>
<p>
真实姓名:<input type="text" name="user_name" />
</p>
<p>
<input type="submit" value="注册" />
<input type="reset" value="重置" />
</p>
</form>
</body>
</html>
findall.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>showAllByPaging</title>
</head>
<body>
<p align="right"><a href="${pageContext.request.contextPath}/UserAction_logout">退出登录</a></p>
<h2 align="center"><font color="pink">${user.user_name}</font>的博客</h2>
<table align="center" border="1" width="80%">
<tr bgcolor="yellow">
<th width="5%">博客ID</th>
<th width="15%">博客标题</th>
<th width="12%">标签</th>
<th width="40%">博客内容</th>
<th width="8%" colspan="2">操作</th>
</tr>
<s:iterator value="blogList">
<tr>
<td align="center">
<s:property value="blog_id"/>
</td>
<td align="center">
《<s:property value="blog_title"/>》
</td>
<td align="center">
<s:property value="blog_label"/>
</td>
<td>
<s:property value="blog_context"/>
</td>
<td>
<a href="${pageContext.request.contextPath}/BlogAction_detail?blog.blog_id=${blog_id}">修改</a>
</td>
<td>
<a href="${pageContext.request.contextPath}/BlogAction_delete?blog.blog_id=${blog_id}">删除</a>
</td>
</tr>
</s:iterator>
</table>
<p align="center"><a href="${pageContext.request.contextPath}/BlogAction_toadd">再来一篇</a></p>
<p align="center">${bar}</p>
</body>
</html>
add.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>add</title>
</head>
<body>
<h2 align="center">写博客</h2>
<form action="${pageContext.request.contextPath}/BlogAction_add">
<table align="center">
<tr>
<th>博客标题:</th>
<td><input name="blog_title" type="text"></td>
</tr>
<tr>
<th>标签:</th>
<td><input name="blog_label" type="text"></td>
</tr>
<tr>
<th>博客内容:</th>
<td>
<!-- <input name="blog_context" type="text">-->
<textarea rows="5" cols="50" name="blog_context">在这里输入内容...</textarea>
</td>
</tr>
</table>
<p align="center">
<input type="submit" value="添加">
<input type="reset" value="重置">
</p>
</form>
</body>
</html>
update.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>update</title>
</head>
<body>
<h2 align="center">修改博客</h2>
<form action="${pageContext.request.contextPath}/BlogAction_update" method="post">
<table align="center">
<tr>
<th>博客ID:</th>
<td><input name="blog.blog_id" type="text" value="${blog.blog_id}" readonly="readonly"></td>
</tr>
<tr>
<th>博客标题:</th>
<td><input name="blog.blog_title" type="text" value="${blog.blog_title}"></td>
</tr>
<tr>
<th>标签:</th>
<td><input name="blog.blog_label" type="text" value="${blog.blog_label}"></td>
</tr>
<tr>
<th>博客内容:</th>
<td>
<!-- <input name="blog.blog_context" type="text" value="${blog.blog_context}">-->
<textarea rows="5" cols="50" name="blog.blog_context" >${blog.blog_context}</textarea>
</td>
</tr>
</table>
<p align="center">
<input type="submit" value="修 改">
<input type="reset" value="重 置">
</p>
</form>
</body>
</html>
数据库表:
sys_user
![](https://i-blog.csdnimg.cn/blog_migrate/7becd3ae34fb8c159cd4aafa0b250965.png)
sys_blog
![](https://i-blog.csdnimg.cn/blog_migrate/ce09331a76eb53e9df13d5bf2a1e321c.png)
最终功能截图:
Run on sever后到达主界面:
点击任意其中一个链接,发现没有登录,会到达登录界面:
用一个没有的账户登录会提示不存在该用户,此时用户可以点击登陆下方的注册链接:
当昵称没有注册过时,会在输入框失去焦点时显示可以注册:
当注册过会在输入框失去焦点时,显示注册过,且不能注册:
点击注册后会携带值到登录页面:
登陆后到了index页面选择“查看我的所有博客”,由于用户刚刚注册,所以没有博客:
点击“退出登录”,登录Rose的账户:
查看Rose所有博客,共两页:
删除Rose最后一篇博客:
给Rose添加博客:
将刚刚添加的博客标题改为“随便”
退出,再登录Gold的,看看他的博客,可以证明每个人的博客不一样了吧!
最终数据库表:
就上述这些,感觉最难的还是处理一对多的关系时的传值问题,就是登录后把user保存在session域中,需要用的时候就取出来,退出登录时就把session域保存的那个user对象置为空。想了好久才想明白!