标签:jar enc 链接 http etc users getattr stc tin
SSM框架制作简易新闻系统
一、搭建环境(略)
二、创建mysql数据库webdb
1、创建数据表user
2、创建数据表news
三、创建maven项目myWeb,在pox.xml里加载项目所需依赖包
<!-- spring框架所需jar包10个 -->
<!-- https://mvnrepository.com/artifact/aopalliance/aopalliance -->
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-expression -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>
<!-- spring mvc所需jar包2个-->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>
<!--mybatis框架所需jar包13个-->
<!-- https://mvnrepository.com/artifact/org.apache.ant/ant -->
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.9.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.ant/ant-launcher -->
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant-launcher</artifactId>
<version>1.9.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.ow2.asm/asm -->
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>5.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/cglib/cglib -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.2.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.javassist/javassist -->
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.21.0-GA</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/ognl/ognl -->
<dependency>
<groupId>ognl</groupId>
<artifactId>ognl</artifactId>
<version>3.1.12</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.22</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.22</version>
<scope>test</scope>
</dependency>
<!-- mybatis与spring整合的中间jar包1个 -->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- mysql驱动包 -->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>
<!-- 数据源所需jar(dbcp,2个) -->
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.4.2</version>
</dependency>
<!-- jstl标签库jar两个 -->
<!-- https://mvnrepository.com/artifact/org.apache.taglibs/taglibs-standard-impl -->
<dependency>
<groupId>org.apache.taglibs</groupId>
<artifactId>taglibs-standard-impl</artifactId>
<version>1.2.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.taglibs/taglibs-standard-spec -->
<dependency>
<groupId>org.apache.taglibs</groupId>
<artifactId>taglibs-standard-spec</artifactId>
<version>1.2.5</version>
</dependency>
<!--jackson框架所需jar包3个-->
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.6</version>
</dependency>
<!-- java工具类jar包1个-->
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
四、配置spring,springmvc,mybatis,数据库,日志文件等
在main目录下创建resources资源包
1、在resources包里创建数据库配置文件db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/webdb?useSSL=false
jdbc.username=root
jdbc.password=root
jdbc.maxTotal=30
jdbc.maxIdle=10
jdbc.initialSize=5
2、创建log4j.properties
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.ssm.core=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
3、配置spring
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!--读取db.properties -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置数据源 -->
<bean id="dataSource"
class="org.apache.commons.dbcp2.BasicDataSource">
<!--数据库驱动 -->
<property name="driverClassName" value="${jdbc.driver}" />
<!--连接数据库的url -->
<property name="url" value="${jdbc.url}" />
<!--连接数据库的用户名 -->
<property name="username" value="${jdbc.username}" />
<!--连接数据库的密码 -->
<property name="password" value="${jdbc.password}" />
<!--最大连接数 -->
<property name="maxTotal" value="${jdbc.maxTotal}" />
<!--最大空闲连接 -->
<property name="maxIdle" value="${jdbc.maxIdle}" />
<!--初始化连接数 -->
<property name="initialSize" value="${jdbc.initialSize}" />
</bean>
<!-- 事务管理器 -->
<bean id="transactionManager" class=
"org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 传播行为 -->
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="create*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="find*" propagation="SUPPORTS"
read-only="true" />
<tx:method name="select*" propagation="SUPPORTS"
read-only="true" />
<tx:method name="get*" propagation="SUPPORTS"
read-only="true" />
</tx:attributes>
</tx:advice>
<!-- 切面 -->
<aop:config>
<aop:advisor advice-ref="txAdvice"
pointcut="execution(* com.ssm.core.service.*.*(..))" />
</aop:config>
<!-- 配置 MyBatis的工厂 -->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource" />
<!-- 配置MyBatis的核心配置文件所在位置 -->
<property name="configLocation"
value="classpath:mybatis-config.xml" />
</bean>
<!-- 接口开发,扫描 com.ssm.core.dao包 ,写在此包下的接口即可被扫描到 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ssm.core.dao" />
</bean>
<!-- 配置扫描@Service注解 -->
<context:component-scan base-package="com.ssm.core.service"/>
</beans>
4、配置mybatis
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 别名定义 -->
<typeAliases>
<package name="com.ssm.core.po" />
</typeAliases>
</configuration>
5、配置springmvc
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!--加载属性文件-->
<!-- <context:property-placeholder-->
<!-- location="classpath:resource.properties"/>-->
<!-- 配置包扫描器,扫描@Controller注解的类 -->
<context:component-scan base-package="com.ssm.core.web.controller" />
<!-- 加载注解驱动 -->
<mvc:annotation-driven />
<!--配置静态资源的访问映射,此配置中的文件不被前端控制器拦截-->
<mvc:resources mapping="/js/**" location="/js/"/>
<mvc:resources mapping="/css/**" location="/css/"/>
<mvc:resources mapping="/fonts/**" location="/fonts/"/>
<mvc:resources mapping="/images/**" location="/images/"/>
<!-- 配置视图解析器 -->
<bean id="jspViewResolver"
class=
"org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/admin/**"/>
<bean class="com.ssm.core.interceptor.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
</beans>
6、配置项目配置文件web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<!-- 配置加载Spring文件的监听器-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- 编码过滤器 -->
<filter>
<filter-name>encoding</filter-name>
<filter-class>
org.springframework.web.filter.CharacterEncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置Spring MVC前端核心控制器 -->
<servlet>
<servlet-name>crm</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-config.xml</param-value>
</init-param>
<!-- 配置服务器启动后立即加载Spring MVC配置文件 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>crm</servlet-name>
<!--/:拦截所有请求(除了jsp)-->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--系统默认页面-->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
五、创建项目目录结构及文件
在main目录下创建java文件夹,标注为source root
创建如下包结构
说明:controller负责接收jsp页面传递来的参数,调用service里方法进行业务逻辑,service方法调用dao层来操控数据库
(一)在po包里创建对应数据表的实体类
News和Admin
package com.ssm.core.po;
/**
* @Author: palapala
* @Description:新闻实体类
*/
public class News {
public int getNewsID() {
return NewsID;
}
public void setNewsID(int newsID) {
NewsID = newsID;
}
public String getNewsTitle() {
return NewsTitle;
}
public void setNewsTitle(String newsTitle) {
NewsTitle = newsTitle;
}
public String getNewsContent() {
return NewsContent;
}
public void setNewsContent(String newsContent) {
NewsContent = newsContent;
}
public String getNewsTime() {
return NewsTime;
}
public void setNewsTime(String newsTime) {
NewsTime = newsTime;
}
public String getAdminName() {
return AdminName;
}
public void setAdminName(String adminName) {
AdminName = adminName;
}
private Integer NewsID;
private String NewsTitle;
private String NewsContent;
private String NewsTime;
private String AdminName;
private Integer start;//起始行
public Integer getStart() {
return start;
}
public void setStart(Integer start) {
this.start = start;
}
public Integer getRows() {
return rows;
}
public void setRows(Integer rows) {
this.rows = rows;
}
private Integer rows;//所取行数
}
package com.ssm.core.po;
public class Admin {
private Integer AdminID;
public Integer getAdminID() {
return AdminID;
}
public void setAdminID(Integer adminID) {
AdminID = adminID;
}
public String getAdminName() {
return AdminName;
}
public void setAdminName(String adminName) {
AdminName = adminName;
}
public String getAdminPwd() {
return AdminPwd;
}
public void setAdminPwd(String adminPwd) {
AdminPwd = adminPwd;
}
public Integer getAdminType() {
return AdminType;
}
public void setAdminType(Integer adminType) {
AdminType = adminType;
}
public String getLastLoginTime() {
return LastLoginTime;
}
public void setLastLoginTime(String lastLoginTime) {
LastLoginTime = lastLoginTime;
}
private String AdminName;
private String AdminPwd;
private Integer AdminType;
private String LastLoginTime;
}
(二)在Dao层创建接口文件
Dao层两个接口文件
1、NewsDao
package com.ssm.core.dao;
import com.ssm.core.po.News;
import java.util.List;
/**
* @Author: palapala
* News接口
*/
public interface NewsDao {
//新闻列表
List<News> selectNews(News news);
//新闻数量
Integer selectNewsListCount(News news);
//增加新闻
int addNews(News news);
//更新新闻
int updateNews(News news);
//删除新闻
int delNews(Integer NewsId);
News getNewsByID(Integer NewsID);
}
2、UserDao
package com.ssm.core.dao;
import com.ssm.core.po.Admin;
import org.apache.ibatis.annotations.Param;
/**
* @Author: palapala
* 用户DAO层接口
*/
public interface UserDao {
public Admin findUser(@Param("AdminName") String AdminName,
@Param("AdminPwd") String AdminPwd);
}
这两个接口和resources目录下同路径xml文件共同构成mybatis的映射文件来操控数据库
NewsDao.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.ssm.core.dao.NewsDao">
<!-- 查询新闻列表 -->
<select id="selectNews" parameterType="news"
resultType="news">
SELECT
NewsID,
NewsTitle,
NewsContent,
NewsTime,
AdminName
FROM
news
<if test="start !=null and rows != null">
limit #{start},#{rows}
</if>
</select>
<!-- 查询客户总数 -->
<select id="selectNewsListCount" parameterType="news"
resultType="Integer">
select count(*) from news
</select>
<!-- 添加新闻 -->
<insert id="addNews" parameterType="news">
insert into news(
NewsID,
NewsTitle,
NewsContent,
NewsTime,
AdminName
)
values(#{NewsID},
#{NewsTitle},
#{NewsContent},
#{NewsTime},
#{AdminName}
)
</insert>
<!-- <!– 根据id获取客户信息 –>-->
<!-- <select id="getCustomerById" parameterType="Integer"-->
<!-- resultType="customer">-->
<!-- select * from customer where cust_id = #{id}-->
<!-- </select>-->
<!-- 更新客户 -->
<update id="updateNews" parameterType="news">
update news
<set>
<if test="NewsID!=null">
NewsId=#{NewsID},
</if>
<if test="NewsTitle!=null">
NewsTitle=#{NewsTitle},
</if>
<if test="NewsContent!=null">
NewsContent=#{NewsContent},
</if>
<if test="NewsTime!=null">
NewsTime=#{NewsTime},
</if>
<if test="AdminName!=null">
AdminName=#{AdminName},
</if>
</set>
where NewsID=#{NewsID}
</update>
<!-- 删除客户 -->
<delete id="delNews" parameterType="Integer">
delete from news where NewsID=#{NewsID}
</delete>
<!-- 新闻详情-->
<select id="getNewsByID" parameterType="Integer"
resultType="news">
SELECT
NewsID,
NewsTitle,
NewsContent,
NewsTime,
AdminName
FROM
news
where
NewsID=#{NewsID}
</select>
</mapper>
NewsDao.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.ssm.core.dao.UserDao">
<!-- 查询管理员 -->
<select id="findUser" parameterType="String"
resultType="Admin">
SELECT
*
FROM
admin
</select>
</mapper>
(三)在sevice层创建接口及实现类
1、NewsService接口
package com.ssm.core.service;
import com.ssm.common.utils.Page;
import com.ssm.core.po.News;
import java.util.List;
public interface NewsService {
// 查询新闻列表
Page<News> findNewsList(Integer page,Integer rows);
int createNews(News news);
// 更新新闻
int updateNews(News news);
// 删除新闻
int delNews(Integer id);
News getNewsByID(Integer NewsID);
}
实现类
package com.ssm.core.service.impl;
import com.ssm.common.utils.Page;
import com.ssm.core.dao.NewsDao;
import com.ssm.core.po.News;
import com.ssm.core.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional
public class NewsServiceImpl implements NewsService {
//声明dao属性并注入
@Autowired
private NewsDao newsDao;
//新闻列表
public Page<News> findNewsList(Integer page,Integer rows) {
News news=new News();
// 当前页
news.setStart((page-1) * rows);
news.setRows(rows);
//查询新闻列表
List<News> news1 = newsDao.selectNews(news);
//查询新闻列表总记录数
Integer count = newsDao.selectNewsListCount(news);
//创建page的返回对象
Page<News> result=new Page<>();
result.setPage(page);
result.setRows((news1));
result.setSize(rows);
result.setTotal(count);
return result;
}
public int createNews(News news) {
int i = newsDao.addNews(news);
return i;
}
public int updateNews(News news) {
return newsDao.updateNews(news);
}
public int delNews(Integer id) {
return newsDao.delNews(id);
}
public News getNewsByID(Integer NewsID){
News news=newsDao.getNewsByID(NewsID);
return news;
}
}
2、UserService接口及实现类
package com.ssm.core.service;
import com.ssm.core.po.Admin;
import org.springframework.stereotype.Service;
/**
* @Author: palapala
* @Description:
* @Date: Created in 21:08 2020/3/11
* @Modified By:
*/
@Service
public interface UserService {
Admin findUser(String AdminName,String AdminPwd);
}
package com.ssm.core.service.impl;
import com.ssm.core.dao.UserDao;
import com.ssm.core.po.Admin;
import com.ssm.core.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* @Author: palapala
* @Description:
* @Date: Created in 21:12 2020/3/11
* @Modified By:
*/
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public Admin findUser(String AdminName, String AdminPwd) {
return this.userDao.findUser(AdminName, AdminPwd);
}
}
(四)在web层创建俩个controller
1、NewsController
/**
* 新闻管理控制器类
*/
@Controller
public class NewsController {
// 依赖注入
@Autowired
private NewsService newsService;
private Admin admin;
@RequestMapping(value = "/newsFrontList")
public String list(@RequestParam(defaultValue="1")Integer page,
@RequestParam(defaultValue="10")Integer rows,
Model model) {
// 条件查询所有客户
Page<News> newsPage = newsService
.findNewsList(page, rows);
model.addAttribute("page", newsPage);
return "/front/newsFrontList";
}
@RequestMapping(value = "/about")
public String list1(){
return "front/about";
}
@RequestMapping(value = "/content")
public String list2(){
return "front/content";
}
@RequestMapping(value = "/contact")
public String list3(){
return "front/contact";
}
@RequestMapping(value = "/newsFrontDetail")
public String getNewsByID(Integer NewsID, Model model) {
// 根据ID查询新闻
News news = newsService.getNewsByID(NewsID);
model.addAttribute("News",news);
return "/front/newsFrontDetail";
}
@RequestMapping(value = "/admin/newsAdmin")
public String newsList(@RequestParam(defaultValue = "1")Integer page,
@RequestParam(defaultValue = "10")Integer rows,Model model,HttpSession session){
Page<News> newsList = newsService.findNewsList(page, rows);
model.addAttribute("page",newsList);
Admin user_session = (Admin) session.getAttribute("USER_SESSION");
if(user_session!=null)
session.setAttribute("user",admin);
return "/admin/news";
}
@RequestMapping(value = "/admin/newsAdd")
public String newsAdd(String NewsTitle,String NewsContent, Model model,HttpSession session){
News news=new News();
Admin user_session = (Admin) session.getAttribute("USER_SESSION");
news.setAdminName(user_session.getAdminName());
news.setNewsTitle(NewsTitle);
news.setNewsContent(NewsContent);
news.setNewsTime("2020-3-12");
int row= newsService.createNews(news);
Page<News> newsList = newsService.findNewsList(1, 10);
model.addAttribute("page",newsList);
if(row>0){
return "admin/news";
}
System.out.println("添加失败");
return "admin/news";
}
//修改新闻
@RequestMapping(value = "/admin/newsUpdate")
public String newsUpdate(News news, Model model){
int i = newsService.updateNews(news);
if(i>0){
return "redirect:/newsAdmin";
}
System.out.println("添加失败");
return "redirect:/newsAdmin";
}
@RequestMapping(value = "/admin/editNews")
public String edtiNews(News news,Model model){
Integer id=news.getNewsID();
News newsByID = newsService.getNewsByID(id);
model.addAttribute(newsByID);
return "admin/newsEdit";
}
@RequestMapping(value = "/admin/delNews/{NewsID}",method = RequestMethod.GET)
public String delNews(@PathVariable("NewsID") Integer NewsID) {
int i = newsService.delNews(NewsID);
if(i>0){
System.out.println("删除成功");
return "redirect:/newsAdmin";
}
System.out.println("删除失败");
return "redirect:/newsAdmin";
}
@RequestMapping(value = "/index")
public String index(HttpSession session){
session.invalidate();
return "/front/index";
}
}
2、UserController
/**
* @Author: palapala
* @Description:
* @Date: Created in 21:21 2020/3/11
* @Modified By:
*/
@Controller
public class UserController {
@RequestMapping(value = "/admin/login")
public String llist(){
return "/admin/login";
}
@Autowired
private UserService userService;
@RequestMapping(value = "/admin/login",method = RequestMethod.POST)
public String login(String AdminName,String AdminPwd,Model model,HttpSession session){
Admin admin=userService.findUser(AdminName,AdminPwd);
if(admin != null){
// 将用户对象添加到Session
session.setAttribute("USER_SESSION", admin);
// 跳转到主页面
model.addAttribute("Admin",admin);
return "/admin/adminUser";
// return "redirect:customer/list.action";
}
model.addAttribute("msg", "账号或密码错误,请重新输入!");
// 返回到登录页面
return "admin";
}
}
(五)在interceptor里创建拦截器
package com.ssm.core.interceptor;
import com.ssm.core.po.Admin;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* @Author: palapala
* @Description:
* @Date: Created in 1:13 2020/3/10
* @Modified By:
*/
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//获取请求的Url
StringBuffer requestURL = request.getRequestURL();
//URL:除了登录请求外,其他的url都进行拦截
if(requestURL.indexOf("/login")>=0){
return true;
}
//获取session
HttpSession session = request.getSession();
Admin user_session = (Admin)session.getAttribute("USER_SESSION");
//判断session中是否有用户数据,如果有,则返回true继续向下执行
if(user_session != null){
return true;
}
//不符合条件的给出提示信息,并转发到登录页面
request.setAttribute("msg","您还没有登录,请先登录");
request.getRequestDispatcher("/admin/login").forward(request,response);
return false;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
(六)在common.utils下创建翻页类
1、翻页效果NavigationTag
package com.ssm.common.utils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;
import java.util.Map;
/**
* 显示格式:首页 上一页 1 2 3 4 5下一页 尾页
*/
public class NavigationTag extends TagSupport {
static final long serialVersionUID = 2372405317744358833L;
/**
* request 中用于保存Page<E> 对象的变量名,默认为“page”
*/
private String bean = "page";
/**
* 分页跳转的url地址,此属性必须
*/
private String url = null;
/**
* 显示页码数量
*/
private int number = 5;
@Override
public int doStartTag() throws JspException {
JspWriter writer = pageContext.getOut();
HttpServletRequest request =
(HttpServletRequest) pageContext.getRequest();
Page page = (Page) request.getAttribute(bean);
if (page == null)
return SKIP_BODY;
url = resolveUrl(url, pageContext);
try {
// 计算总页数
int pageCount = page.getTotal() / page.getSize();
if (page.getTotal() % page.getSize() > 0) {
pageCount++;
}
writer.print("<nav><ul class=\"pagination\">");
//首页链接路径
String homeUrl = append(url, "page", 1);
//末页链接路径
String backUrl = append(url, "page", pageCount);
// 显示“上一页”按钮
if (page.getPage() > 1) {
String preUrl = append(url, "page", page.getPage() - 1);
preUrl = append(preUrl, "rows", page.getSize());
writer.print("<li><a href=\"" + homeUrl + "\">" + "首页</a></li>");
writer.print("<li><a href=\"" + preUrl + "\">" + "上一页</a></li>");
} else {
writer.print("<li class=\"disabled\"><a href=\"#\">" + "首页 </a></li>");
writer.print("<li class=\"disabled\"><a href=\"#\">" + "上一页 </a></li>");
}
// 显示当前页码的前2页码和后两页码
// 若1 则 1 2 3 4 5, 若2 则 1 2 3 4 5, 若3 则1 2 3 4 5,
// 若4 则 2 3 4 5 6 ,若10 则 8 9 10 11 12
int indexPage =1;
if(page.getPage() - 2 <=0){
indexPage=1;
}else if(pageCount-page.getPage() <=2){
indexPage=pageCount-4;
}else{
indexPage= page.getPage() - 2;
}
for (int i= 1;i <= number && indexPage <= pageCount;indexPage++,i++){
if (indexPage == page.getPage()) {
writer.print("<li class=\"active\"><a href=\"#\">" + indexPage
+"<spanclass=\"sr-only\"></span></a></li>");
continue;
}
String pageUrl = append(url, "page", indexPage);
pageUrl = append(pageUrl, "rows", page.getSize());
writer.print("<li><a href=\"" + pageUrl + "\">" + indexPage + "</a></li>");
}
// 显示“下一页”按钮
if (page.getPage() < pageCount) {
String nextUrl = append(url, "page", page.getPage() + 1);
nextUrl = append(nextUrl, "rows", page.getSize());
writer.print("<li><a href=\"" + nextUrl + "\">" + "下一页</a></li>");
writer.print("<li><a href=\"" + backUrl + "\">" + "尾页</a></li>");
} else {
writer.print("<li class=\"disabled\"><a href=\"#\">" + "下一页</a></li>");
writer.print("<li class=\"disabled\"><a href=\"#\">" + "尾页</a></li>");
}
writer.print("</nav>");
} catch (IOException e) {
e.printStackTrace();
}
return SKIP_BODY;
}
private String append(String url, String key, int value) {
return append(url, key, String.valueOf(value));
}
/**
* 为url 参加参数对儿
*/
private String append(String url, String key, String value) {
if (url == null || url.trim().length() == 0) {
return "";
}
if (url.indexOf("?") == -1) {
url = url + "?" + key + "=" + value;
} else {
if (url.endsWith("?")) {
url = url + key + "=" + value;
} else {
url = url + "&" + key + "=" + value;
}
}
return url;
}
/**
* 为url 添加翻页请求参数
*/
private String resolveUrl(String url,
javax.servlet.jsp.PageContext pageContext) throws JspException {
Map params = pageContext.getRequest().getParameterMap();
for (Object key : params.keySet()) {
if ("page".equals(key) || "rows".equals(key)){
continue;
}
Object value = params.get(key);
if (value == null){
continue;
}
if (value.getClass().isArray()) {
url = append(url, key.toString(), ((String[]) value)[0]);
} else if (value instanceof String) {
url = append(url, key.toString(), value.toString());
}
}
return url;
}
public String getBean() {
return bean;
}
public void setBean(String bean) {
this.bean = bean;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public void setNumber(int number) {
this.number = number;
}
}
2、Page类
package com.ssm.common.utils;
import java.util.List;
public class Page<T> {
private int total; // 总条数
private int page; // 当前页
private int size; // 每页数
private List<T> rows; // 结果集
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public List<T> getRows() {
return rows;
}
public void setRows(List<T> rows) {
this.rows = rows;
}
}
上面完成了后台程序的基本开发,剩下的只需把jsp页面放到WEB-INF下即可,css,js,img等资源文件放在webapp根目录下即可
这个项目只是个简单的项目,里面还有很多需要优化及解决的问题,等过一阵我再进行细节的优化。
我也是在学习中,所以会有很多的不合适的地方希望大家批评指正。
标签:jar enc 链接 http etc users getattr stc tin
原文地址:https://www.cnblogs.com/palapala/p/12521108.html