文档章节

maven搭建jersey+Spring4+JPA+Druid+quartz

liuyuantao
 liuyuantao
发布于 2016/04/09 10:06
字数 4730
阅读 48
收藏 0

创建web项目

首先创建基于Maven的Web项目,这里不多说,我博客里就有自己找下学习就可以。

添加依赖包

具体主要jar包的版本如下所示:

<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<spring.version>4.2.4.RELEASE</spring.version>
		<hibernate.version>4.3.11.Final</hibernate.version>
		<slf4j.version>1.7.12</slf4j.version>
		<jersey.version>1.19</jersey.version>
		<aspectj.version>1.8.6</aspectj.version>
</properties>

这里说明下几个比较特殊的jar,其他的不进行说明了,后面会提供完成pom.xml进行下载:

阿里的数据源,可以进行监控

<dependency>
		<groupId>com.alibaba</groupId>
		<artifactId>druid</artifactId>
		<version>1.0.16</version>
</dependency>

<dependency>
		<groupId>com.alibaba</groupId>
		<artifactId>fastjson</artifactId>
		<version>1.2.7</version>
</dependency>

Jersey提供基于rest的服务

<dependency>
		<groupId>com.sun.jersey</groupId>
		<artifactId>jersey-server</artifactId>
		<version>${jersey.version}</version>
</dependency>

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_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>lyt-jersey-sjpa</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-list>
	<!-- 400 404 500 处理 -->
	<!-- 出错页面定义 -->
	<error-page>
		<error-code>400</error-code>
		<location>/errors/400.html</location>
	</error-page>
	<error-page>
		<error-code>404</error-code>
		<location>/errors/404.jsp</location>
	</error-page>
	<error-page>
		<error-code>500</error-code>
		<location>/errors/500.jsp</location>
	</error-page>
	<!-- 监听器 任务定时调度 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext-quartz.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- spring mvc配置 -->
	<servlet>
		<servlet-name>dispatcher-servlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:applicationContext-*.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>dispatcher-servlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	<!-- 中文乱码问题 -->
	<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>
	<!-- 数据监控 http://localhost:8080/project/druid/ 地址,会看到监控界面 -->
	<servlet>
		<servlet-name>DruidStatusView</servlet-name>
		<servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>DruidStatusView</servlet-name>
		<url-pattern>/druid/*</url-pattern>
	</servlet-mapping>
	<!-- 使用jersey 达到rest风格 -->
	<servlet>
		<description>Do not modify</description>
		<servlet-name>jersey-servlet</servlet-name>
		<servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
		<init-param>
			<param-name>com.sun.jersey.config.property.packages</param-name>
			<param-value>org.lyt.edu.webservice</param-value>
		</init-param>
		<init-param>
			<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
			<param-value>true</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>jersey-servlet</servlet-name>
		<url-pattern>/rest/*</url-pattern>
	</servlet-mapping>
	<!-- 配置session超时时间,单位分钟 -->
	<session-config>
		<session-timeout>120</session-timeout>
	</session-config>
</web-app>

数据连接的配置

在persistence.xml进行相关数据源的配置

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
	xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
	<persistence-unit name="spring.data.jpa"
		transaction-type="RESOURCE_LOCAL">
		<provider>org.hibernate.ejb.HibernatePersistence</provider>
		<properties>
			<property name="hibernate.connection.url"
				value="jdbc:mysql://localhost:3306/lyt-jersey-sjpa?useUnicode=true&characterEncoding=utf8" />
			<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
			<property name="hibernate.connection.username" value="root" />
			<property name="hibernate.connection.password" value="root" />
			<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
			<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider" />
			<property name="hibernate.show_sql" value="true" />
			<property name="hibernate.format_sql" value="true" />
			<property name="hibernate.hbm2ddl.auto" value="update"/>
			<!-- 配置初始化大小、最小、最大 -->
			<property name="initialSize" value="1" />
			<property name="minIdle" value="1" />
			<property name="maxActive" value="20" />
			<!-- 配置获取连接等待超时的时间 -->
			<property name="maxWait" value="60000" />
			<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
			<property name="timeBetweenEvictionRunsMillis" value="60000" />
			<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
			<property name="minEvictableIdleTimeMillis" value="300000" />
			<property name="validationQuery" value="SELECT 'x'" />
			<property name="testWhileIdle" value="true" />
			<property name="testOnBorrow" value="false" />
			<property name="testOnReturn" value="false" />
			<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
			<property name="poolPreparedStatements" value="true" />
			<property name="maxPoolPreparedStatementPerConnectionSize"
				value="20" />
			<!-- 配置监控统计拦截的filters,去掉后监控界面sql无法统计 -->
			<property name="filters" value="stat" />
		</properties>
	</persistence-unit>
</persistence>

基于Spring事务的配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:util="http://www.springframework.org/schema/util" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd">

	<!-- 配置文件 -->
	<util:properties id="jdbc" location="classpath:db.properties"></util:properties>
	<bean id="entityManagerFactory"
		class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="persistenceUnitName" value="spring.data.jpa"></property>
		<property name="persistenceXmlLocation" value="classpath:persistence.xml"></property>
	</bean>
	<!-- 自动扫描并注入Spring Data JPA -->
	<jpa:repositories base-package="org.lyt.edu.dao"
		entity-manager-factory-ref="entityManagerFactory"
		transaction-manager-ref="txManager">
	</jpa:repositories>
	<!-- 定义事务管理Bean -->
	<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory">
		</property>
	</bean>
	<!-- 开启@Transactional注解事务控制 -->
	<tx:annotation-driven transaction-manager="txManager" />
</beans>

SpringMVC的相关配置

springmvc的配置文件需要在web.xml文件中进行配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="
			http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
			http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
			http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
			http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
			http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">

	<!-- 组件扫描 -->
	<context:component-scan base-package="org.lyt.edu"></context:component-scan>
	<mvc:annotation-driven>
		<!-- 返回json数据,IE浏览器返回json会下载文件 -->
		<mvc:message-converters register-defaults="true">
			<bean
				class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
				<property name="supportedMediaTypes">
					<list>
						<value>text/html;charset=UTF-8</value>
						<value>application/json;charset=UTF-8</value>
					</list>
				</property>
			</bean>
		</mvc:message-converters>
	</mvc:annotation-driven>
	<context:annotation-config />
	<!-- 定义视图组件 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/mainView/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
</beans>

基于Spring异常处理的配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="
			http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
			http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
	<bean
		class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
		<!-- 定义默认的异常处理页面,当该异常类型的注册时使用 -->
		<property name="defaultErrorView" value="error"></property>
		<!-- 定义异常处理页面用来获取异常信息的变量名,默认名为exception -->
		<property name="exceptionAttribute" value="ex"></property>
		<!-- 定义需要特殊处理的异常,用类名或完全路径名作为key,异常也页名作为值 -->
		<property name="exceptionMappings">
			<props>
				<prop key="IOException">error/ioexp</prop>
				<prop key="java.lang.NullPointerException">error</prop>
			</props>
		</property>
	</bean>

</beans>

基于SpringMVC拦截器的配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="	     
			http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
			http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
			http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
			http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
			http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">

	<!--拦截器 -->
	<mvc:interceptors>
		<mvc:interceptor>
			<mvc:mapping path="/*/*" />
			<!--不拦截用户登录组件 -->
			<mvc:exclude-mapping path="/user/*" />
			<!--指定拦截器实现的组件:权限检查 -->
			<bean class="org.lyt.edu.interceptor.AdminPrivilegeInterceptor"></bean>
		</mvc:interceptor>
	</mvc:interceptors>

</beans>

基于quartz的任务调度的配置

任务调度的配置文件配置之后还需要在web.xml进行配置,使项目启动之后就开启任务调度
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"

	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="	     
			http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
			http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
			http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
			http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
			http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">

	<!-- 计划调度管理工厂 -->
	<bean id="schedulerFactoryBean"
		class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
		<property name="triggers">
			<list>
				<ref bean="cornTrigger" />
			</list>
		</property>
	</bean>
	<!-- 定义任务调度组件调用的对象和方法 -->
	<bean id="jobTask"
		class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
		<property name="targetObject" ref="job">
		</property>
		<property name="targetMethod" value="execute">
		</property>
	</bean>
	<!-- 定义任务组件触发的时间 -->
	<bean id="cornTrigger"
		class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
		<property name="jobDetail">
			<ref bean="jobTask" />
		</property>
		<property name="cronExpression">
			<value>0 15 10 15 * ?</value>
		</property>
	</bean>
	<!-- 要调用的工作Bean组件 -->
	<bean id="job" class="org.lyt.edu.procedure.TimePlan"></bean>
	<!-- 
	【字符说明】
		字段名                   允许的值                                     允许的特殊字符  
	               秒                                 0-59                  , - * /  
	               分                                 0-59                  , - * /  
	               小时                             0-23                  , - * /  
	               日                                 1-31                  , - * ? / L W C  
	               月                                  1-12 or JAN-DEC       , - * /  
	               周几                              1-7 or SUN-SAT        , - * ? / L C #  
	               年 (可选字段)     empty, 1970-2099      , - * /
	      * 表示所有值. 例如:在分的字段上设置 "*",表示每一分钟都会触发。 
	      ? 表示不确定的值
	      , 指定数个值
	      - 指定一个值的范围
	      / 指定一个值的增加幅度。n/m表示从n开始,每次增加m
	      L 用在日表示一个月中的最后一天,用在周表示该月最后一个星期X
	      W 指定离给定日期最近的工作日(周一到周五)
	      # 表示该月第几个周X。6#3表示该月第3个周五
               【常用示例】
		0 15 10 15 * ? 每月15号上午10点15分触发 
		0 15 10 L * ? 每月最后一天的10点15分触发
		0 * 14 * * ? 每天下午的 2点到2点59分每分触发 
		0 0/5 14,18 * * ? 每天下午的 2点到2点59分(整点开始,每隔5分触发) 
		0 11 11 11 11 ? 每年的11月11号 11点11分触发(光棍节)
	 -->
</beans>

基于aspectj的aop的配置

要想实现aop编程,只要将对应的类配置成bean即可
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="	     
			http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
			http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
			http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
			http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
			http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
	<!-- 组件 -->
	<bean id="loggerBean" class="org.lyt.edu.aspect.LoggerBean"></bean>
	<!-- 开启aop扫描 -->
	<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>

log4j的配置

### set log levels ###
log4j.rootLogger = INFO , C , D , E 

### console ###
log4j.appender.C = org.apache.log4j.ConsoleAppender
log4j.appender.C.Target = System.out
log4j.appender.C.layout = org.apache.log4j.PatternLayout
log4j.appender.C.layout.ConversionPattern = [lyt-jersey-sjpa][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n

### log file ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = logs/lyt-jersey-sjpa.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = INFO 
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = [lyt-jersey-sjpa][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n

### exception ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File = logs/lyt-jersey-sjpa_error.log 
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR 
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = [lyt-jersey-sjpa][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n

基于aop的log的代码详解

如果需要进行自己的定制说明的话可以在此进行修改,并在aop的配置文件进行配置

package org.lyt.edu.aspect;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * 
 * @author liuyuantao
 * @Desc方面组件[基于注解方式]
 * @version 1.0
 */
@Component
@Aspect
public class LoggerBean {

	@Before("within(org.lyt.edu.controller..*)")
	public void before() {

		// System.out.println(new java.util.Date()+" ...前面执行了");
	}

	@After("within(org.lyt.edu.controller..*)")
	public void end() {

		// System.out.println("后面调用");
	}

	// 异常通知
	@AfterThrowing(throwing = "ex", pointcut = "within(org.lyt.edu.controller..*)")
	public void exception(Exception ex) {

		// System.out.println("出问题了"+ex);
	}

}

权限检查拦截器的代码

这里的权限拦截的代码要想生效,需要在权限拦截的配置文件中进行配置,将全类名org.lyt.edu.interceptor.AdminPrivilegeInterceptor配置进配置文件中
package org.lyt.edu.interceptor;

import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.lyt.edu.entity.Admin;
import org.lyt.edu.util.Constant;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 权限检查拦截器
 * 
 * @author liuyuantao
 *
 */
public class AdminPrivilegeInterceptor implements HandlerInterceptor {

	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {

		System.out.println("最后执行...");

	}

	/**
	 * 这个部分实现页面的凹凸效果
	 */
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object arg2, ModelAndView arg3)
			throws Exception {

		// 当前页效果
		int current = 1;
		// 获得用户的访问地址 /xxx/xxx
		String url = request.getServletPath();
		// 获得访问前缀
		url = url.substring(1, url.indexOf("/", 1));
		if ("role".equals(url)) {
			current = 1;
		} else if ("admin".equals(url)) {
			current = 2;
		} else if ("fee".equals(url)) {
			current = 3;
		} else if ("account".equals(url)) {
			current = 4;
		} else if ("service".equals(url)) {
			current = 5;
		} else if ("bill".equals(url)) {
			current = 6;
		} else if ("report".equals(url)) {
			current = 7;
		} else {
			current = 0;
		}

		request.getSession().setAttribute("current", current);

		System.out.println("中间执行....");

	}

	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object arg2) throws Exception {
		System.out.println("开始执行....");

		// 获得项目名
		String path = request.getContextPath();

		HttpSession session = request.getSession();
		// 从session中获得用户,查看用户是否登录
		Admin admin = (Admin) session.getAttribute(Constant.USERNAME);

		// 没有登录
		if (admin == null) {
			response.sendRedirect(path + "/user/login");
			// 跳转到登录界面
			return false;
		}
		// 获得用户的访问地址/xxx/xxx
		String url = request.getServletPath();

		// 用户登录后检查权限
		@SuppressWarnings("unchecked")
		Set<String> urls = (Set<String>) session.getAttribute(path + "urls");
		// 如果用户有权限访问就跳转到对应页面
		if (urls.contains(url)) {
			return true;
		}
		// 跳转到没有权限页面
		response.sendRedirect(path + "/nopower.jsp");
		return true;
	}

}

基于quartz的任务调度的代码

此处的execute方法需要和quartz配置文件的方法一致

package org.lyt.edu.procedure;

public class TimePlan {

	public void execute() {
		System.out.println("定时任务执行!");
	}

}


基于jersey实现的rest的代码

类和方法都要按照jersey规范进行相应的注解
package org.lyt.edu.webservice;

import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.lyt.edu.entity.Admin;

/**
 * 
 * @author liuyuantao
 *
 */
@Path("/helloService")
public class HelloService {
	/**
	 * 
	 * @param id
	 * @return
	 */
	@GET
	@Path("getAdmin")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Admin getPaperById(@DefaultValue("") @QueryParam("id") Integer id) {
		Admin admin = new Admin();
		admin.setId(id);
		admin.setName("Administrator");
		return admin;
	}
}

运行项目

在项目上右键Run As  选择Maven Build...输入jetty:run



控制台输出

[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building lyt-jersey-sjpa Maven Webapp 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] >>> maven-jetty-plugin:6.1.26:run (default-cli) > test-compile @ lyt-jersey-sjpa >>>
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ lyt-jersey-sjpa ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 9 resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ lyt-jersey-sjpa ---
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ lyt-jersey-sjpa ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory E:\OneDrive\DevelopCode\j2ee\practice\lyt-jersey-sjpa\src\test\resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ lyt-jersey-sjpa ---
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] <<< maven-jetty-plugin:6.1.26:run (default-cli) < test-compile @ lyt-jersey-sjpa <<<
[INFO] 
[INFO] --- maven-jetty-plugin:6.1.26:run (default-cli) @ lyt-jersey-sjpa ---
[INFO] Configuring Jetty for project: lyt-jersey-sjpa Maven Webapp
[INFO] Webapp source directory = E:\OneDrive\DevelopCode\j2ee\practice\lyt-jersey-sjpa\src\main\webapp
[INFO] Reload Mechanic: automatic
[INFO] Classes = E:\OneDrive\DevelopCode\j2ee\practice\lyt-jersey-sjpa\target\classes
[INFO] Logging to org.slf4j.impl.SimpleLogger(org.mortbay.log) via org.mortbay.log.Slf4jLog
[INFO] Context path = /lyt-jersey-sjpa
[INFO] Tmp directory =  determined at runtime
[INFO] Web defaults = org/mortbay/jetty/webapp/webdefault.xml
[INFO] Web overrides =  none
[INFO] web.xml file = E:\OneDrive\DevelopCode\j2ee\practice\lyt-jersey-sjpa\src\main\webapp\WEB-INF\web.xml
[INFO] Webapp directory = E:\OneDrive\DevelopCode\j2ee\practice\lyt-jersey-sjpa\src\main\webapp
[INFO] Starting jetty 6.1.26 ...
[INFO] jetty-6.1.26
[INFO] No Transaction manager found - if your webapp requires one, please configure one.
[INFO] Initializing Spring root WebApplicationContext
一月 13, 2016 7:07:48 下午 org.springframework.web.context.ContextLoader initWebApplicationContext
信息: Root WebApplicationContext: initialization started
一月 13, 2016 7:07:48 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing Root WebApplicationContext: startup date [Wed Jan 13 19:07:48 CST 2016]; root of context hierarchy
一月 13, 2016 7:07:48 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [applicationContext-quartz.xml]
一月 13, 2016 7:07:49 下午 org.quartz.impl.StdSchedulerFactory instantiate
信息: Using default implementation for ThreadExecutor
一月 13, 2016 7:07:49 下午 org.quartz.core.SchedulerSignalerImpl <init>
信息: Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
一月 13, 2016 7:07:49 下午 org.quartz.core.QuartzScheduler <init>
信息: Quartz Scheduler v.2.2.2 created.
一月 13, 2016 7:07:49 下午 org.quartz.simpl.RAMJobStore initialize
信息: RAMJobStore initialized.
一月 13, 2016 7:07:49 下午 org.quartz.core.QuartzScheduler initialize
信息: Scheduler meta-data: Quartz Scheduler (v2.2.2) 'schedulerFactoryBean' with instanceId 'NON_CLUSTERED'
  Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.
  NOT STARTED.
  Currently in standby mode.
  Number of jobs executed: 0
  Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 10 threads.
  Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered.

一月 13, 2016 7:07:49 下午 org.quartz.impl.StdSchedulerFactory instantiate
信息: Quartz scheduler 'schedulerFactoryBean' initialized from an externally provided properties instance.
一月 13, 2016 7:07:49 下午 org.quartz.impl.StdSchedulerFactory instantiate
信息: Quartz scheduler version: 2.2.2
一月 13, 2016 7:07:49 下午 org.quartz.core.QuartzScheduler setJobFactory
信息: JobFactory set to: org.springframework.scheduling.quartz.AdaptableJobFactory@50ca11b3
一月 13, 2016 7:07:49 下午 org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup start
信息: Starting beans in phase 2147483647
一月 13, 2016 7:07:49 下午 org.springframework.scheduling.quartz.SchedulerFactoryBean startScheduler
信息: Starting Quartz Scheduler now
一月 13, 2016 7:07:49 下午 org.quartz.core.QuartzScheduler start
信息: Scheduler schedulerFactoryBean_$_NON_CLUSTERED started.
一月 13, 2016 7:07:49 下午 org.springframework.web.context.ContextLoader initWebApplicationContext
信息: Root WebApplicationContext: initialization completed in 1128 ms
一月 13, 2016 7:07:49 下午 com.sun.jersey.api.core.PackagesResourceConfig init
信息: Scanning for root resource and provider classes in the packages:
  org.lyt.edu.webservice
一月 13, 2016 7:07:49 下午 com.sun.jersey.api.core.ScanningResourceConfig logClasses
信息: Root resource classes found:
  class org.lyt.edu.webservice.HelloService
一月 13, 2016 7:07:49 下午 com.sun.jersey.api.core.ScanningResourceConfig init
信息: No provider classes found.
一月 13, 2016 7:07:49 下午 com.sun.jersey.spi.spring.container.servlet.SpringServlet getContext
信息: Using default applicationContext
一月 13, 2016 7:07:49 下午 com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
信息: Initiating Jersey application, version 'Jersey: 1.19 02/11/2015 03:25 AM'
[INFO] Initializing Spring FrameworkServlet 'dispatcher-servlet'
一月 13, 2016 7:07:50 下午 org.springframework.web.servlet.FrameworkServlet initServletBean
信息: FrameworkServlet 'dispatcher-servlet': initialization started
一月 13, 2016 7:07:50 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing WebApplicationContext for namespace 'dispatcher-servlet-servlet': startup date [Wed Jan 13 19:07:50 CST 2016]; parent: Root WebApplicationContext
一月 13, 2016 7:07:50 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from file [E:\OneDrive\DevelopCode\j2ee\practice\lyt-jersey-sjpa\target\classes\applicationContext-aop.xml]
一月 13, 2016 7:07:50 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from file [E:\OneDrive\DevelopCode\j2ee\practice\lyt-jersey-sjpa\target\classes\applicationContext-datasource.xml]
一月 13, 2016 7:07:51 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from file [E:\OneDrive\DevelopCode\j2ee\practice\lyt-jersey-sjpa\target\classes\applicationContext-exception.xml]
一月 13, 2016 7:07:51 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from file [E:\OneDrive\DevelopCode\j2ee\practice\lyt-jersey-sjpa\target\classes\applicationContext-interceptor.xml]
一月 13, 2016 7:07:51 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from file [E:\OneDrive\DevelopCode\j2ee\practice\lyt-jersey-sjpa\target\classes\applicationContext-quartz.xml]
一月 13, 2016 7:07:51 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from file [E:\OneDrive\DevelopCode\j2ee\practice\lyt-jersey-sjpa\target\classes\applicationContext-webmvc.xml]
一月 13, 2016 7:07:51 下午 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
信息: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
一月 13, 2016 7:07:52 下午 org.springframework.orm.jpa.persistenceunit.PersistenceUnitReader determinePersistenceUnitRootUrl
信息: persistence.xml should be located inside META-INF directory; cannot determine persistence unit root URL for class path resource [persistence.xml]
一月 13, 2016 7:07:52 下午 org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean createNativeEntityManagerFactory
信息: Building JPA container EntityManagerFactory for persistence unit 'spring.data.jpa'
一月 13, 2016 7:07:52 下午 org.hibernate.ejb.HibernatePersistence logDeprecation
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
一月 13, 2016 7:07:52 下午 org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
	name: spring.data.jpa
	...]
一月 13, 2016 7:07:52 下午 org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.11.Final}
一月 13, 2016 7:07:52 下午 org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
一月 13, 2016 7:07:52 下午 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
一月 13, 2016 7:07:52 下午 org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
一月 13, 2016 7:07:52 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
一月 13, 2016 7:07:53 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/lyt-jersey-sjpa?useUnicode=true&characterEncoding=utf8]
一月 13, 2016 7:07:53 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=root, password=****}
一月 13, 2016 7:07:53 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
一月 13, 2016 7:07:53 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
一月 13, 2016 7:07:53 下午 org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
一月 13, 2016 7:07:54 下午 org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
一月 13, 2016 7:07:54 下午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
一月 13, 2016 7:07:54 下午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
一月 13, 2016 7:07:54 下午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
一月 13, 2016 7:07:54 下午 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: lyt-jersey-sjpa.admin_info
一月 13, 2016 7:07:54 下午 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [id, email, name, admin_code, enrolldate, telephone, password]
一月 13, 2016 7:07:54 下午 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: []
一月 13, 2016 7:07:54 下午 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [primary]
一月 13, 2016 7:07:54 下午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
一月 13, 2016 7:07:54 下午 org.springframework.core.io.support.PropertiesLoaderSupport loadProperties
信息: Loading properties file from class path resource [db.properties]
一月 13, 2016 7:07:55 下午 org.quartz.impl.StdSchedulerFactory instantiate
信息: Using default implementation for ThreadExecutor
一月 13, 2016 7:07:55 下午 org.quartz.core.SchedulerSignalerImpl <init>
信息: Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
一月 13, 2016 7:07:55 下午 org.quartz.core.QuartzScheduler <init>
信息: Quartz Scheduler v.2.2.2 created.
一月 13, 2016 7:07:55 下午 org.quartz.simpl.RAMJobStore initialize
信息: RAMJobStore initialized.
一月 13, 2016 7:07:55 下午 org.quartz.core.QuartzScheduler initialize
信息: Scheduler meta-data: Quartz Scheduler (v2.2.2) 'schedulerFactoryBean' with instanceId 'NON_CLUSTERED'
  Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.
  NOT STARTED.
  Currently in standby mode.
  Number of jobs executed: 0
  Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 10 threads.
  Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered.

一月 13, 2016 7:07:55 下午 org.quartz.impl.StdSchedulerFactory instantiate
信息: Quartz scheduler 'schedulerFactoryBean' initialized from an externally provided properties instance.
一月 13, 2016 7:07:55 下午 org.quartz.impl.StdSchedulerFactory instantiate
信息: Quartz scheduler version: 2.2.2
一月 13, 2016 7:07:55 下午 org.quartz.core.QuartzScheduler setJobFactory
信息: JobFactory set to: org.springframework.scheduling.quartz.AdaptableJobFactory@159b572b
一月 13, 2016 7:07:55 下午 org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
信息: Mapped "{[/admin/getAdmin2Json/{id}]}" onto public org.lyt.edu.entity.Admin org.lyt.edu.controller.AdminController.getAdmin2Json(java.lang.Integer)
一月 13, 2016 7:07:55 下午 org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
信息: Mapped "{[/admin/toadmin]}" onto public java.lang.String org.lyt.edu.controller.AdminController.toadmin()
一月 13, 2016 7:07:56 下午 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
信息: Looking for @ControllerAdvice: WebApplicationContext for namespace 'dispatcher-servlet-servlet': startup date [Wed Jan 13 19:07:50 CST 2016]; parent: Root WebApplicationContext
一月 13, 2016 7:07:56 下午 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
信息: Looking for @ControllerAdvice: WebApplicationContext for namespace 'dispatcher-servlet-servlet': startup date [Wed Jan 13 19:07:50 CST 2016]; parent: Root WebApplicationContext
一月 13, 2016 7:07:56 下午 org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup start
信息: Starting beans in phase 2147483647
一月 13, 2016 7:07:56 下午 org.springframework.scheduling.quartz.SchedulerFactoryBean startScheduler
信息: Starting Quartz Scheduler now
一月 13, 2016 7:07:56 下午 org.quartz.core.QuartzScheduler start
信息: Scheduler schedulerFactoryBean_$_NON_CLUSTERED started.
一月 13, 2016 7:07:56 下午 org.springframework.web.servlet.FrameworkServlet initServletBean
信息: FrameworkServlet 'dispatcher-servlet': initialization completed in 6171 ms
[INFO] Started SelectChannelConnector@0.0.0.0:8080
[INFO] Started Jetty Server
[INFO] Starting scanner at interval of 1 seconds.
至此整个项目的搭建完成










本文转载自:http://blog.csdn.net/u013510614/article/details/50512593

liuyuantao
粉丝 5
博文 134
码字总数 27666
作品 0
武汉
高级程序员
私信 提问
Spring Cloud搭建开发环境

1 开发环境搭建 工欲善其事,必先利其器。在讲述本书的技术内容前,先将开发环境搭建好,本书所涉及基础环境将在本章准备,包括Eclipse、Maven等。 笔者建议读者在查阅本书过程中,使用与本书...

Jokey2017
2017/11/13
0
0
Maven私有库Nexus的安装和使用

Maven私有库Nexus的安装和使用 曾静的技术博客2017-07-2141 阅读 Mavennexus安装 在进行Java开发的时候,通常会使用 Maven 进行第三方库的管理,类似于iOS中的Cocoapods。我们在使用Cocoapo...

曾静的技术博客
2017/07/21
0
0
Linux 下使用 Nexus

为什么要搭建私服? 在开发过程中,有时候会使用到公司内部的一些开发包,显然把这些包放在外部是不合适的。另外,由于项目一直在开发中,这些内部的依赖可能也在不断的更新。可以通过搭建公...

devin223
2017/06/05
0
0
使用Eclipse-Maven-git做Java开发(7)--maven概览

前面一篇博客用自己的口水话啰里啰嗦地说了一下maven,这里将里面需要知道的东西提出来一下,为后面的博客做准备。 0、资料 学习maven最好的资料就是官方网站了,其次搜索构件自然是中央仓库...

阿信sxq
2015/09/14
376
0
maven springboot项目搭建

1.maven继承、聚合项目搭建 类似目录: app-parent --父工程,创建maven project项目,pom类型 app-manager --继承父工程,创建maven project项目,pom类型 --app-manager-pojo --聚合工程,...

樱木花道VS康
2018/04/27
723
3

没有更多内容

加载失败,请刷新页面

加载更多

DDD(五)

1、引言 之前学习了解了DDD中实体这一概念,那么接下来需要了解的就是值对象、唯一标识。值对象,值就是数字1、2、3,字符串“1”,“2”,“3”,值时对象的特征,对象是一个事物的具体描述...

MrYuZixian
46分钟前
3
0
数据库中间件MyCat

什么是MyCat? 查看官网的介绍是这样说的 一个彻底开源的,面向企业应用开发的大数据库集群 支持事务、ACID、可以替代MySQL的加强版数据库 一个可以视为MySQL集群的企业级数据库,用来替代昂贵...

沉浮_
今天
4
0
解决Mac下VSCode打开zsh乱码

1.乱码问题 iTerm2终端使用Zsh,并且配置Zsh主题,该主题主题需要安装字体来支持箭头效果,在iTerm2中设置这个字体,但是VSCode里这个箭头还是显示乱码。 iTerm2展示如下: VSCode展示如下: 2...

HelloDeveloper
今天
6
0
常用物流快递单号查询接口种类及对接方法

目前快递查询接口有两种方式可以对接,一是和顺丰、圆通、中通、天天、韵达、德邦这些快递公司一一对接接口,二是和快递鸟这样第三方集成接口一次性对接多家常用快递。第一种耗费时间长,但是...

程序的小猿
今天
4
0
Python机器学习之数据探索可视化库yellowbrick

背景介绍 从学sklearn时,除了算法的坎要过,还得学习matplotlib可视化,对我的实践应用而言,可视化更重要一些,然而matplotlib的易用性和美观性确实不敢恭维。陆续使用过plotly、seaborn,...

yeayee
今天
8
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部