小编acv*_*vcu的帖子

在Eclipse中更改Web项目的Tomcat上下文路径

我正在使用Tomcat 6并使用Eclipse中的Servers功能来管理它.我有一个名为foobar的项目,我想更改上下文路径,以便引用的URL是http:// localhost:8080/app而不是http:// localhost:8080/foobar.我尝试了一切我能想到的:

  • 更新了Context部分中的server.xml路径值

<Context docBase="foobar" path="/foobar" reloadable="true" source="org.eclipse.jst.j2ee.server:foobar"/></Host>
Run Code Online (Sandbox Code Playgroud)

<Context docBase="foobar" path="/app" reloadable="true" source="org.eclipse.jst.j2ee.server:foobar"/></Host>
Run Code Online (Sandbox Code Playgroud)

我知道我可以简单地重命名项目,但我不想这样做.

以下是Eclipse中的服务器设置.

编辑:

我还应该提一下,我在应用程序上下文中有一些数据库设置.我不确定是否应将其设置为foobar.xml或app.xml ..?Eclipse会自动在conf/Catalina/localhost中创建一个app.xml文件,但在进行更改后似乎会被忽略.

java eclipse tomcat

29
推荐指数
1
解决办法
7万
查看次数

applicationContext没有找到Servlet上下文的控制器

我有一个带有applicationContext.xml和dispatcher-servlet.xml配置的Spring Web应用程序.我<context:component-scan />在applicationContext.xml中定义了,但是当我运行我的应用程序时,除非我也添加<context:component-scan />到dispatcher-servlet.xml,否则找不到控制器.我在两者中使用相同的基础包,所以这不是问题.

我很困惑,因为我认为 applicationContext.xml是dispatcher-servlet.xml的父级.不会把<context:component-scan />applicationContext.xml放进去吗?

web.xml中

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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">


<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>

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

</web-app>
Run Code Online (Sandbox Code Playgroud)

编辑:我也在dispatcher-servlet.xml中使用mvc:annotation-driven,它应该选择控制器(我想?).

编辑2:这是配置文件.我从applicationContext.xml中删除了一堆Spring Security和OAuth设置(出于安全原因,他们可能无论如何都不相关).

applicationContext.xml中

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:sec="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context" xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
      http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd
      http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

<context:component-scan base-package="bar.foo"/>
<context:property-placeholder location="classpath:my.properties" />
<bean class="bar.foo.ServicesConfig" />

</beans>
Run Code Online (Sandbox Code Playgroud)

调度员servlet.xml中

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c" …
Run Code Online (Sandbox Code Playgroud)

spring spring-mvc spring-annotations

22
推荐指数
1
解决办法
3万
查看次数

使用hamcrest匹配Map包含不同类型的条目

假设我有一张地图:

Map<String,Object> map1 = new HashMap<String,Object>();
map1.put("foo1","foo1");
map1.put("foo2", Arrays.asList("foo2","bar2"));
Run Code Online (Sandbox Code Playgroud)

现在我想使用Hamcrest匹配器来验证Map的值.如果这是一个Map <String,String>我会做类似的事情:

assertThat(map1, hasEntry("foo1", "foo1"));
Run Code Online (Sandbox Code Playgroud)

但是,我试图在Map中使用它时遇到困难,Map中的条目可能是String或值列表.这适用于第一个条目:

assertThat(map1, hasEntry("foo1", (Object)"foo1"));
Run Code Online (Sandbox Code Playgroud)

对于第二个条目,我无法弄清楚如何设置Matchers.

编辑:

我也尝试了这个,但它会产生编译器警告.

assertThat(
            map1,
            hasEntry(
                    "foo2",
                    contains(hasProperty("name", is("foo2")),
                            hasProperty("name", is("bar2")))));
Run Code Online (Sandbox Code Playgroud)

"Assert类型中的方法assertThat(T,Matcher)不适用于参数(Map,Matcher >>>)"

(以上是解决方案:Hamcrest比较收藏)

java junit unit-testing hamcrest

9
推荐指数
1
解决办法
6352
查看次数

Spring术语中的命令,表单,业务和实体对象之间的区别?

我试图在松耦合系统方面围绕这些对象之间的差异.业务对象是否与实体对象相同?我可以在MVC中使用业务或实体对象作为我的命令对象吗?命令对象与表单对象相同吗?只是在寻找Spring术语和用法中对象类型的说明.

我在stackoverflow上发现了一些问题,但没有任何问题可以解释我的喜好.

Spring Web MVC文档似乎说你可以使用你的业务(实体?)对象作为你的命令/表单对象,但这不会违背关注点的分离吗?

来自Spring Docs:

可重复使用的业务代码,无需重复.将现有业务对象用作命令或表单对象,而不是镜像它们以扩展特定的框架基类.

java spring spring-mvc

7
推荐指数
1
解决办法
3916
查看次数

将联结表中的值映射到实体

我有一个USER表和一个COURSE表.用户可以拥有许多课程,而且很多用户都可以参加课程.联结表包含一个ROLE值,用于确定用户在COURSE(即讲师,学生等)中的角色.我需要知道如何将此角色与每个USER的COURSE相关联.

如果我将该角色放在Course类中,它就无法工作,因为一个Course有很多用户,反之亦然.

这是我到目前为止所拥有的:

@Entity
@Table(name = "USERS")
public class User {

@Id
@Column(name = "PK1")
private Long id;

@Column(name = "USER_ID")
private String userId;

@ManyToMany
@JoinTable(name = "COURSE_USERS", 
    joinColumns = @JoinColumn(name = "USERS_PK1", referencedColumnName = "PK1"), 
    inverseJoinColumns = @JoinColumn(name = "CRSMAIN_PK1", referencedColumnName = "PK1"))
private Collection<Course> courses;

...

@Entity
@Table(name = "COURSE")
@SecondaryTable(name = "COURSE_USERS", 
pkJoinColumns = @PrimaryKeyJoinColumn(name = "CRSMAIN_PK1"))
public class Course {

@Id
@Column(name = "PK1")
private Long id;

    // THIS PROBABLY WON'T WORK //
@Column(name = "ROLE", …
Run Code Online (Sandbox Code Playgroud)

jpa

6
推荐指数
1
解决办法
4664
查看次数

以编程方式为Spring创建JNDI DataSource

我有一个基于Spring的基于Web的应用程序,它具有使用JNDI定义的数据源,我正在尝试创建一个独立的应用程序来使用bean.如何在独立应用程序中以编程方式创建JNDI条目和数据库属性?

<bean id="myDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:comp/env/jdbc/MyDS" />
</bean>

    public static void main(String[] args) {

      // this throws an error since the JNDI lookup fails - can I programmatically define the database properties here?

    ClassPathXmlApplicationContext ctx = new  ClassPathXmlApplicationContext("applicationContext.xml");

    UserService userService = ctx.getBean(UserService.class);
    User user = userService.findUserById("jdoe");

    System.out.println("display name: " + user.getDisplayName());
}
Run Code Online (Sandbox Code Playgroud)

编辑:

我尝试过类似的东西,但现在收到错误"javax.naming.NoInitialContextException:需要在环境或系统属性中指定类名"

public static void main(String[] args) {
    setupJNDI();

    ClassPathXmlApplicationContext ctx = new  ClassPathXmlApplicationContext("applicationContext.xml");

    UserService userService = ctx.getBean(UserService.class);
    User user = userService.findUserById("jdoe");

    System.out.println("display name: " + user.getDisplayName()); …
Run Code Online (Sandbox Code Playgroud)

java spring jndi mocking initial-context

6
推荐指数
1
解决办法
1万
查看次数

在 Spring 数据休息中自定义分页和排序的查询

我正在使用 Spring 数据休息,并尝试findAll使用@Query. 但是,当我尝试这样做时,我收到此错误:

java.lang.IllegalStateException:检测到不明确的搜索映射。公共抽象 org.springframework.data.domain.Pagecourses.CourseRepository.findAll(org.springframework.data.domain.Pageable) 和公共抽象 java.lang.Iterablecourses.CourseRepository.findAll(org.springframework.data.domain. Sort) 映射到 /findAll! 调整配置以获得明确的路径!

当调用这些方法时,URL/findAll按照惯例不包含。检索未分类课程(但使用分页)的 URL 是

http://localhost:8080/v1/courses

和排序是

http://localhost:8080/v1/courses?sort=title

这是相关的代码,它相当简单:

public interface CourseRepository extends PagingAndSortingRepository<Course, Long> {

  @Override
  @Query("SELECT c FROM Course c WHERE c.visible = 'Yes'")
  Page<Course> findAll(Pageable pageable);

  @Override
  @Query("SELECT c FROM Course c WHERE c.visible = 'Yes'")
  Iterable<Course> findAll(Sort sort);
}
Run Code Online (Sandbox Code Playgroud)

我还尝试@NamedQuery在 Course 实体上使用具有相同错误消息的 。

编辑:

我发现该findAll(Pageable pageable)方法具有“内置”排序功能,但它不会对结果进行排序。当我点击以下 URL 并尝试按标题排序时,结果显然不是按标题排序的。但是,如果没有自定义@Query,结果将被排序。

http://localhost:8080/v1/courses?sort=title

java spring spring-data spring-data-rest

6
推荐指数
1
解决办法
5539
查看次数

将单个表映射到JPA中的可嵌入集合

我有一个相当独特的情况,试图将单个表映射到JPA中的多个实体.我已经阅读了@Embeddable和@ElementCollection,但我不确定如何在我的情况下使用它们(或者如果可以的话).一个数据库表包含课程信息.表格中可以有行,除了一些值(例如房间号和日期)外,课程中的所有内容都相同.例如:

TERM_CODE   SUBJECT_CODE    ROOM    DAY    INSTRUCTOR_ID
201220      EGRE            0101    TR     123
201220      EGRE            0103    W      124
Run Code Online (Sandbox Code Playgroud)

有没有办法可以从上面的两行中提取数据,并将公共数据放在一个对象中,将不同的值放在单独对象的集合中?这是我希望如何定义类的示例:

@Entity
public class Course implements Serializable {

    @Id
    @Column(name = "TERM_CODE")
    private Long termCode;

    @Column(name = "SUBJECT_CODE")
    private String subjectCode;

    @Embedded
    Collection<CourseSchedule> schedule;

    public Long getTermCode() {
     return termCode;
    }

    public void setTermCode(Long termCode) {
     this.termCode = termCode;
    }

    public String getSubjectCode() {
     return subjectCode;
    }

    public void setSubjectCode(String subjectCode) {
     this.subjectCode = subjectCode;
    }
}
Run Code Online (Sandbox Code Playgroud)

CourseSchedule:

@Embeddable
public class CourseSchedule {
     private …
Run Code Online (Sandbox Code Playgroud)

java hibernate jpa

5
推荐指数
1
解决办法
1万
查看次数

在Spring 3.1 Java Config中引用Spring Security配置

我最近切换了大部分Spring配置,在Spring 3.1中使用基于代码的配置.但是,现在我已经切换,我的Spring Security无法正常工作,并在Tomcat启动时抛出以下错误:

SEVERE: Exception starting filter springSecurityFilterChain
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named     'springSecurityFilterChain' is defined
Run Code Online (Sandbox Code Playgroud)

我仍然在XML文件中有Spring Security,并且知道这不能在Spring中转换为Java配置,因为它是一个自定义命名空间,但是,我在我的Java配置文件中引用它.我也尝试将applicationContext-security.xml配置引用从Java配置移动到我的web.xml,没有任何运气.

@Configuration
@EnableWebMvc
@Import(ServicesConfig.class)
@ImportResource({ "classpath:applicationContext-security.xml",
"classpath:dataSources.xml" })
@ComponentScan(basePackages = "com.foobar")
public class WebConfig {
   // left out Beans for clarity
}
Run Code Online (Sandbox Code Playgroud)

的applicationContext-security.xml文件:

<b:beans xmlns="http://www.springframework.org/schema/security"
xmlns:b="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c"
xmlns:oauth2="http://www.springframework.org/schema/security/oauth2"
xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
      http://www.springframework.org/schema/security
      http://www.springframework.org/schema/security/spring-security-3.1.xsd
      http://www.springframework.org/schema/security/oauth2
      http://www.springframework.org/schema/security/spring-security-oauth2.xsd">

<!-- Security configuration -->

<global-method-security pre-post-annotations="enabled" />

<http use-expressions="true" access-denied-page="/error/accessDenied" 
        entry-point-ref="casEntryPoint">
    <intercept-url pattern="/**" access="isAuthenticated()" />
    <custom-filter position="CAS_FILTER" ref="casFilter" />
</http>

<authentication-manager alias="authenticationManager">
    <authentication-provider ref="casAuthenticationProvider" />
</authentication-manager>

<!-- Bean …
Run Code Online (Sandbox Code Playgroud)

java spring spring-security

4
推荐指数
2
解决办法
2万
查看次数

通过HttpGet对象检索数据时设置超时值

我有一些我从以前的同事那里继承的Java代码.它的一部分使用方法GET连接到外部URL,并检索少量XML以进行解析.由于供应商网站挂起并耗尽了我们这方面的资源,我们最近因为此连接导致网站崩溃而遇到问题.一个问题是由于我们的代码使用HttpGet对象时没有设置超时.有没有办法使用这个对象微调超时,还是有更好的方法来撤回这个XML?

我会更好地使用其他API吗?

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("param1","foobar"));
URI uri = URIUtils.createURI("http", "myhost.com", -1, "mypath",
URLEncodedUtils.format(params, "UTF-8"), null);

// there is no timeout here??
HttpGet httpGet = new HttpGet(uri);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpGet);
String result = IOUtils.toString(httpResponse.getEntity()
    .getContent(), "UTF-8");
Run Code Online (Sandbox Code Playgroud)

谢谢!

java http

3
推荐指数
1
解决办法
1万
查看次数

在 Spring 中缓存带有数组参数的方法

我有一个具有多种方法的服务,并尝试使用 Spring@Cacheable注释来缓存它们。一切正常,除非我发现带有数组作为方法参数的方法没有被缓存。考虑到数组可以保存不同的值,这有点有意义,但我仍然认为这是可能的。

缓存了以下方法:

@Cacheable("myCache")
public Collection<Building> findBuildingByCode(String buildingCode) {...}

@Cacheable("myCache")
public Collection<Building> getBuildings() {...}
Run Code Online (Sandbox Code Playgroud)

但是,如果我将findBuildingByCode方法更改为以下任一方法,则不会缓存它:

@Cacheable("myCache") 
public Collection<Building> findBuildingByCode(String[] buildingCode) {...}

@Cacheable("myCache")
public Collection<Building> findBuildingByCode(String... buildingCode) {...}
Run Code Online (Sandbox Code Playgroud)

这是相关的Spring xml配置:

<!-- Cache beans -->
<cache:annotation-driven/>

<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
    p:cache-manager-ref="ehcache" />

<!-- EhCache library setup -->
<bean id="ehcache"
    class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" />
Run Code Online (Sandbox Code Playgroud)

ehcache配置:

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">

<diskStore path="java.io.tmpdir/ehcache" />

<!-- Default settings -->
<defaultCache eternal="false" maxElementsInMemory="1"
    overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"
    timeToLiveSeconds="100" memoryStoreEvictionPolicy="LRU" />

<!-- …
Run Code Online (Sandbox Code Playgroud)

java spring ehcache spring-annotations

3
推荐指数
1
解决办法
8288
查看次数

在Spring中使用REST调用来公开服务层

我有一个现有的Java代码服务层,我想在一些REST调用中使用它.我想这样做的方法是让用户传入URL中的服务ID,然后在后端查找服务和方法(在DB或配置文件中)并调用它.例如:

http://foobar.com/rest/car

调用此URL时,我将使用"car"的serviceId并调用CarService.我想我会有一个简单的配置:

car=com.foobar.services.CarService
house=com.foobar.services.HouseService
etc..
Run Code Online (Sandbox Code Playgroud)

有没有办法用Spring做到这一点?我所关注的一个问题是没有调用该服务,而是要确定要调用哪种方法.如果我打电话给http://foobar.com/services/car/red - 我如何传递'red'的方法参数并决定调用哪种方法?

以下是Java中的示例:

@RequestMapping(value = "{serviceId}")
@ResponseBody
public Object getMarshalledObject(@PathVariable String serviceId) {

    if ("car".equals(serviceId)) {
        return getCar();
    }
    throw new ServiceNotFoundException("Service ID not found.");
}
Run Code Online (Sandbox Code Playgroud)

java spring spring-mvc

2
推荐指数
1
解决办法
2654
查看次数