我有一个对象Recipe
实现了getRecipesSort()
:
public int compareTo(Recipe otherRecipe) {
return this.inputRecipeName.compareTo(otherRecipe.inputRecipeName);
}
我这样做是为了能够按以下方法按字母顺序对3007478579572762769792进行排序:
public static Collection<Recipe> getRecipes(){
List<Recipe> recipes = new ArrayList<Recipe>(RECIPE_MAP.values());
Collections.sort(recipes);
return recipes;
}
但是现在,以另一种方法命名为3007478579572762769792,我想对同一列表进行排序,但以数字方式比较包含ID的变量。 更糟的是,ID字段的类型为String
。
如何使用Collections.sort()在Java中执行排序?
我有类似的JSP代码:
<div class="formRow">
<form:input id="email_email" name="email_email" title="XXXXX"/>" path="email" cssClass="input required email" />
<form:errors path="email" cssClass="error" />
</div>
我想用一些工具提示文本设置title
属性,以支持i18n。 我该怎么做?
我正在寻找做这样的事情:
<div class="formRow">
<form:input id="email_email" name="email_email" title="<spring:message code="tooltip.text" />"/>" path="email" cssClass="input required email" />
<form:errors path="email" cssClass="error" />
</div>
我希望我的Spring MVC应用程序重定向到动态URL(由用户提交)。 所以如果我有这样的代码,
@RequestMapping("/redirectToSite")
protected ModelAndView redirect(
@RequestParam("redir_url") String redirectUrl,
HttpServletRequest request,
HttpServletResponse response)
{
// redirect to redirectUrl here
return ?
}
我应该写些什么来重定向到提交的URL? 例如http://mySpringMvcApp/redirectToSite?redir_url=http://www.google.com
应该重定向到Google。
我正在使用Spring MVC和Spring Security版本3.0.6.RELEASE。 在我的JSP中获取用户名的最简单方法是什么? 甚至只是用户是否已登录? 我可以想到几种方法:
使用如下脚本来确定用户是否已登录:
<%=org.springframework.security.core.context.SecurityContextHolder.getContext()
.getAuthentication().getPrincipal().equals("anonymousUser")
? "false":"true"%>
不过,我不喜欢使用scriptlet,我想在一些@Controller
标签中使用它,这需要将其作为页面属性放回去。
我可以再次使用@Controller
中的SecurityContextHolder并将其放在模型上。 不过,我在每个页面上都需要此逻辑,因此我宁愿不必在每个Controller中都添加此逻辑。
我怀疑有更干净的方法可以做到这一点...
我正在使用Spring 4.0.7
我进行了有关通过JavaConfig配置Spring MVC的研究。
几乎直到昨天,我已经看到了使用这两个选项的两种配置
注意:(2)是两个类,一个用于扩展,另一个用于实现
我之所以使用(2),是因为我发现了许多可以配置转换器,格式化程序,资源处理程序等的示例。
但是在最近的日子里,我试图帮助解决有关StackOverflow的问题,但我确实意识到(1)存在。
我的问题是这篇文章的标题如何描述。
谢谢
SpringSource.org将其站点更改为[http://spring.io]
有人知道如何在没有Maven / github的情况下获取最新版本吗? 来自[http://spring.io/projects]
我对春季诊所的应用程序进行了许多更改。 目前,当我使用eclipse as as ...在服务器上运行时,在tomcat服务器的新实例中启动应用程序时,收到以下错误消息:
SEVERE: Exception loading sessions from persistent storage
服务器和应用程序随后可以成功启动,但是我想修复导致错误消息的所有内容。 谁能告诉我如何克服此错误消息?
堆栈跟踪不会列出应用程序中的任何文件,因此我不知道在应用程序代码中可以查找该位置的问题。 您可以查看github上的petclinic代码,以查看应用程序的结构,如果这有助于您了解应该在哪里找到问题的话。 这是堆栈跟踪:
INFO EhCacheManagerFactoryBean - Initializing EhCache CacheManager
INFO ContextLoader - Root WebApplicationContext: initialization completed in 4376 ms
Dec 16, 2013 2:51:56 PM org.apache.catalina.session.StandardManager doLoad
SEVERE: IOException while loading persisted sessions: java.io.EOFException
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2280)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2749)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:779)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:279)
at org.apache.catalina.util.CustomObjectInputStream.<init>(CustomObjectInputStream.java:58)
at org.apache.catalina.session.StandardManager.doLoad(StandardManager.java:246)
at org.apache.catalina.session.StandardManager.load(StandardManager.java:204)
at org.apache.catalina.session.StandardManager.startInternal(StandardManager.java:491)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5443)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Dec 16, 2013 2:51:56 PM org.apache.catalina.session.StandardManager startInternal
SEVERE: Exception loading sessions from persistent storage
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2280)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2749)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:779)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:279)
at org.apache.catalina.util.CustomObjectInputStream.<init>(CustomObjectInputStream.java:58)
at org.apache.catalina.session.StandardManager.doLoad(StandardManager.java:246)
at org.apache.catalina.session.StandardManager.load(StandardManager.java:204)
at org.apache.catalina.session.StandardManager.startInternal(StandardManager.java:491)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5443)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Dec 16, 2013 2:51:56 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'petclinic'
该项目的结构为:
在Tomcat 7中启动项目B后,出现错误:
错误:java:模块周期不支持注释处理。 请确保注释处理中不包含周期[A,B]中的所有模块
如何避免这个问题?
我使用Java 8,Tomcat 7和想法14。
我的文凭项目有一个大问题,如果你们能帮助我,我将非常高兴!我做了一个Maven多模块项目,有3个“核心项目”
NaviCleanServer
:(父母)NaviCleanServer
:包含我所有实体的域模型,并且NaviCleanServer
需要的接口einRemoteDienst
30003000766766484190212和NaviCleanClient
NaviCleanServer
:包含GUI和与之的Hessian连接einRemoteDienst
NaviCleanServer
:这是我的存储库,与数据库的连接和接口的实现einRemoteDienst
NaviCleanServer
和NaviCleanClient
在Maven中具有NaviCleanDomain
依赖关系。现在,每次尝试在Tomcat上启动服务器时,都会出现以下错误:
ERROR: org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'transaktionsRepository':
Injection of persistence dependencies failed;
nested exception is org.springframework.beans.factory.CannotLoadBeanClassException:
Error loading class [at.naviclean.service.impl.MeinRemoteDienstImpl] for bean with name 'meinRemoteDienstImpl' defined in file [C:\Users\Fredy\Documents\workspace-sts-3.1.0.RELEASE\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\NaviCleanServer\WEB-INF\classes\at\naviclean\service\impl\MeinRemoteDienstImpl.class]:
problem with class file or dependent class;
nested exception is java.lang.NoClassDefFoundError: at/naviclean/service/MeinRemoteDienst
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:342)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
……………….
模型库:
package at.naviclean.domain;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Version;
@SuppressWarnings("serial")
@MappedSuperclass
public class ModelBase implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
@Version
@Column(name = "ts")
private Date timestamp;
public Long getId() {
return id;
}
public Date getTimestamp() {
return timestamp;
}
public void setId(Long id) {
this.id = id;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
}
收银台:
package at.naviclean.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
@SuppressWarnings("serial")
@Entity
public class Kassa extends ModelBase {
@Column(name = "name", unique = true)
private String name;
@Column(name = "geld")
private int geld;
public Kassa(String name, int geld) {
this.name = name;
this.geld = geld;
}
public Kassa() {
}
public String getName() {
return name;
}
public int getGeld() {
return geld;
}
public void setName(String name) {
this.name = name;
}
public void setGeld(int geld) {
this.geld = geld;
}
}
主要远程:
package at.naviclean.service;
import at.naviclean.domain.Kassa;
public interface MeinRemoteDienst {
int getKassaCount(int plus);
String getNameFromKassa(int id);
Kassa findById(int id);
}
基本资料库
package at.naviclean.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import at.naviclean.domain.ModelBase;
public interface BaseRepository<T extends ModelBase> extends
JpaRepository<T, Long> {
T findById(long id);
}
Kassa存储库:
package at.naviclean.repositories;
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import at.naviclean.domain.Kassa;
public interface KassaRepository extends BaseRepository<Kassa> {
List<Kassa> findByGeld(int geld);
Kassa findByName(String name);
@Query("select k from Kassa k where k.geld = ?1")
Kassa findByGeld1(int geld);
}
Main Remotenji schi mpl:
package at.naviclean.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import at.naviclean.domain.Kassa;
import at.naviclean.repositories.KassaRepository;
import at.naviclean.service.MeinRemoteDienst;
@Service
public class MeinRemoteDienstImpl implements MeinRemoteDienst {
@Autowired(required = true)
public KassaRepository kassaR;
public int getKassaCount(int plus) {
return 2;
}
public String getNameFromKassa(int id) {
return kassaR.findById(id + 0l).getName();
}
@Override
public Kassa findById(int id) {
return = kassaR.findById(id + 0l);
}
}
application-context.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:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:repository="http://www.springframework.org/schema/data/repository"
xsi:schemaLocation="http://www.springframework.org/schema/data/repository http://www.springframework.org/schema/data/repository/spring-repository.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<import resource="infrastructures.xml" />
<jpa:repositories base-package="at.naviclean.repositories">
<repository:exclude-filter type="regex"
expression="at.naviclean.repositories.BaseRepository" />
</jpa:repositories>
<context:component-scan base-package="at.naviclean.service.impl" />
</beans>
Infrastructures.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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
</bean>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/kassatest" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
</beans>
servlet-context.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:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<import resource="../root-context.xml" />
<bean id="idMeinRemoteDienst" class="at.naviclean.service.impl.MeinRemoteDienstImpl" />
<bean name="/MeinRemoteDienstHessian"
class="org.springframework.remoting.caucho.HessianServiceExporter"
p:serviceInterface="at.naviclean.service.MeinRemoteDienst"
p:service-ref="idMeinRemoteDienst" />
</beans>
root-context.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:META-INF/spring/application-context.xml" />
</beans>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets
and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>/MeinRemoteDienstHessian</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>/MeinRemoteDienstHessian</servlet-name>
<url-pattern>/remoting/*</url-pattern>
</servlet-mapping>
</web-app>
这是我已经尝试过的:1.我写了这个测试“变成红色”:
package at.spengergasse.kassa;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import at.naviclean.domain.Kassa;
import at.naviclean.repositories.KassaRepository;
@ContextConfiguration("classpath:META-INF/spring/application-context.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class KassaTest {
@Autowired(required = true)
private KassaRepository kassaR;
@Before
public void setUp() throws Exception {
}
@Test
public void findByIdTest() {
Kassa k = kassaR.findById(2);
assertThat(k, is(not(nullValue())));
}
@Test
public void findByGeld() {
Kassa k = kassaR.findByGeld1(1200);
assertThat(k, is(not(nullValue())));
}
@Test
public void test() {
Kassa vorher = new Kassa("ssf", 222);
kassaR.save(vorher);
Kassa nachher = kassaR.findById(vorher.getId());
kassaR.delete(nachher);
assertThat(vorher.getId(), is(equalTo(nachher.getId())));
}
}
错误:
ERROR: org.springframework.test.context.TestContextManager -
Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@41e22632] to prepare test instance [at.spengergasse.kassa.KassaTest@6639be68]
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:157)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:321)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:290)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'meinRemoteDienstImpl':
**Injection of autowired dependencies failed**;
nested exception is org.springframework.beans.factory.BeanCreationException:
Could not autowire field: public at.naviclean.repositories.KassaRepository at.naviclean.service.impl.MeinRemoteDienstImpl.kassaR;
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'kassaRepository': FactoryBean threw exception on object creation;
nested exception is java.lang.IllegalArgumentException: **Not an managed type: class at.naviclean.domain.Kassa**
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
………..
2.我在域模型的persistence.xml中手动插入了一个存储库。 结果是“绿色”测试,但我仍然无法启动服务器...
在此先感谢!!! 我无法想象没有你会是什么:)
我一直在为Spring应用程序中的服务层找出一个好的命名约定。 对于服务层中的每个类,我首先编写它应实现的接口,然后再编写实际的类。 因此,例如,我有以下界面:
public interface UserAccountManager{
public void registerUser(UserAccount newUserAccount);
public void resetPassword(UserAccount userAccount);
...
}
然后是实现类...
这里让我感到困扰的是UserAccountManager是实现类的好名字,因此我被迫给它一个愚蠢的名字,例如SimpleUserAccountManager或UserAccountDbManager。到目前为止,您使用了哪些约定? 将实现类放在不同的包中并为它们提供与接口相同的名称是个好主意吗?另外,对于使用以Manager结尾的名称而不是以Service结尾的名称,您有何想法?
我已经使用spring mvc框架构建了一个Web应用程序以发布REST服务。例如:
@Controller
@RequestMapping("/movie")
public class MovieController {
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public @ResponseBody Movie getMovie(@PathVariable String id, @RequestBody user) {
return dataProvider.getMovieById(user,id);
}
现在,我需要部署应用程序,但存在以下问题:客户端无法直接访问应用程序所在的计算机(有防火墙)。 因此,我需要在代理计算机(客户端可访问)上的重定向层来调用实际的REST服务。
我尝试使用RestTemplate拨打新电话:例如:
@Controller
@RequestMapping("/movieProxy")
public class MovieProxyController {
private String address= "http://xxx.xxx.xxx.xxx:xx/MyApp";
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public @ResponseBody Movie getMovie(@PathVariable String id,@RequestBody user,final HttpServletResponse response,final HttpServletRequest request) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
RestTemplate restTemplate = new RestTemplate();
return restTemplate.exchange( address+ request.getPathInfo(), request.getMethod(), new HttpEntity<T>(user, headers), Movie.class);
}
可以,但是我需要重写控制器中的每个方法才能使用resttemplate。 同样,这会导致代理计算机上的冗余序列化/反序列化。
我尝试使用resttemplate编写泛型函数,但没有成功:
@Controller
@RequestMapping("/movieProxy")
public class MovieProxyController {
private String address= "http://xxx.xxx.xxx.xxx:xx/MyApp";
@RequestMapping(value = "/**")
public ? redirect(final HttpServletResponse response,final HttpServletRequest request) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
RestTemplate restTemplate = new RestTemplate();
return restTemplate.exchange( address+ request.getPathInfo(), request.getMethod(), ? , ?);
}
我找不到与请求和响应对象一起使用的resttemplate方法。
我还尝试了春季重定向和转发。 但是重定向不会更改请求的客户端IP地址,因此我认为在这种情况下它是无用的。 我也无法转发到另一个URL。
有没有更合适的方法来实现这一目标?提前致谢。
Spring 4.1实例化了Jackson ObjectMapper
实例。 我有理由想要将该实例@Autowire
放入我的一个控制器中:控制器使用Jackson对其自身进行一些较小的JSON解析,但是它使用的ObjectMapper
应该是Spring本身使用的一个实例。 我该如何去实现?
请注意,我并不是在问如何自定义配置Spring使用的ObjectMapper
。 我对默认设置感到满意。 我只想获取Spring所使用的实例,以便可以在自己的代码中重用现有实例。
尝试使用AJAX
在Javascript
中获得我的响应时,我得到application/JSON
“此请求所标识的资源仅能够根据request
“接受”标头()生成特性不可接受的响应。”
这是我的环境
* Spring 3.2.0.RELEASE
* included jackson-mapper-asl-1.7.9.jar, jackson-core-asl-1.7.9.jar
* Tomcat 6.x
* mvc:annotation-driven in Spring configuration XML file
我的控制器:
@RequestMapping("/contest")
public class ContestController {
@RequestMapping(value="{name}", headers="Accept=*/*", method = RequestMethod.GET)
public @ResponseBody Contest getContestInJSON(@PathVariable String name) {
Contest contest = new Contest();
contest.setName(name);
contest.setStaffName(new String("contestitem1"));
return contest;
}
}
我的Spring配置文件
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.contestframework.controllers" />
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="atom" value="application/atom+xml"/>
<entry key="html" value="text/html"/>
<entry key="json" value="application/json"/>
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
</list>
</property>
</bean>
<mvc:annotation-driven />
</beans>
在此之后,我只需使用以下命令访问控制器:
http://domain/SpringWebProject/json/contest/abcd
并且我得到的响应是状态406:“此请求标识的资源只能根据请求“接受”标头()生成特性不可接受的响应。”
我还尝试了一种备用机制,方法是使用Javascript
AJAX
访问此机制,以确保我的请求标头具有application/JSON
,但这导致相同的状态406结果
$.getJSON('contest/abcd', function(data) {
console.log(data) }
这是从浏览器捕获的我的请求头:
Request URL:http://localhost:8080/SpringWebProject/json/contest/abcd
Request Method:GET
Status Code:406 Not Acceptable
Accept:application/json, text/javascript, */*; q=0.01
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Cookie:JSESSIONID=59689C95B0B9C21494EB0AB9D9F7BCCD
Host:localhost:8080
Referer:http://localhost:8080/SpringWebProject/json/welcome
User-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4
X-Requested-With:XMLHttpRequest
Response Headersview source
Content-Length:1070
Content-Type:text/html;charset=utf-8
Date:Fri, 12 Oct 2012 18:23:40 GMT
Server:Apache-Coyote/1.1
感谢这方面的帮助。
好的,我是第500位用户问这个问题,我读了很多答案,但仍然没有运气。
父模块pom包含:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.framework.version}</version>
</dependency>
子模块有applicationContext.xml
,我用WEB-INF
运行我的webapp模块。
applicationContext.xml
定义了标准调度程序模块:
<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>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
我的文件在WEB-INF
下有applicationContext.xml
,但是启动失败并显示:
FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext.xml]
怎么了? 文档和所有人都说Spring MVC将搜索XX-servlet.xml,其中XX是servlet的名称。 为什么搜索applicationContext.xml
?
我正在评估用于构建Web应用程序的Spring MVC&Boot和AngularJs。 我遇到了一个问题,当我修改静态内容(html,js,css)时,每次都必须重新启动应用程序。 我希望有某种解决方法,因为重新启动整个应用程序以进行静态内容更改效率不高。 我尝试过的所有其他Web应用程序框架都允许即时更新静态内容文件(即使只是Spring MVC和普通的旧WAR应用程序)。
我已经从“使用Spring Boot Actuator构建RESTful Web服务”指南([http://spring.io/guides/gs/actuator-service/)中设置了项目。]基本上,它使用Spring Boot和MVC控制器来创建 REST服务。 另外,我使用了“使用AngularJS消费RESTful Web服务”指南([http://spring.io/guides/gs/consumption-rest-angularjs/)]来构建AngularJS的前端。 它创建一个网页,显示来自REST服务的响应。 我所做的唯一更改是,请求是对我的应用程序发出的,而不是“ [http://rest-service.guides.spring.io/greeting”。]我的静态内容存储在“ src / main / resources”中 / public”文件夹。 此设置正常运行,除非它不会重新加载静态内容。
我正在尝试使用Spring为webapp自动装配一些bean(用于依赖注入)。 一个控制器bean包含另一个bean,后者又保存另一组bean的哈希图。 目前,该地图只有一个条目。 当我在tomcat中运行并调用服务时,我收到一条错误消息,说第二个bean(保存在控制器中)不是唯一的
No unique bean of type [com.hp.it.km.search.web.suggestion.SuggestionService] is defined: expected single matching bean but found 2: [suggestionService, SuggestionService]
我看不到我在两次定义bean的地方,但是对于Spring和自动装配来说是新的,所以我可能缺少一些基本知识。 xml和以下2类的源代码...
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.hp.it.km.search.web.suggestion" />
<mvc:annotation-driven />
<context:annotation-config />
<bean id="SuggestionController" class="com.hp.it.km.search.web.suggestion.SuggestionController">
<property name="service">
<ref bean="SuggestionService" />
</property>
</bean>
<bean id="SuggestionService" class="com.hp.it.km.search.web.suggestion.SuggestionService">
<property name="indexSearchers">
<map>
<entry key="KMSearcher"> <ref bean="KMSearcherBean"></ref></entry>
</map>
</property>
</bean>
<bean id="KMSearcherBean" class="com.hp.it.km.search.web.suggestion.SuggestionIndexSearcher">
<constructor-arg index="0" value="KMSearcher" />
<constructor-arg index="1" value="C://dev//workspace//search-restful-webapp//src//main//resources//indexes//keyword" />
</bean>
与自动接线的控制器和服务Bean相关的类在这里...
@Controller
public class SuggestionController {
private SuggestionService service;
@Autowired
public void setService(SuggestionService service) {
this.service = service;
}
public SuggestionService getService() {
return service;
}
和...
@Component
public class SuggestionService {
private Map<String, IndexSearcher> indexSearchers = new HashMap<String, IndexSearcher>();
@Autowired
public void setIndexSearchers(Map<String, IndexSearcher> indexSearchers) {
this.indexSearchers = indexSearchers;
}
public SuggestionService() {
super(); }
请帮忙!
我正在尝试创建一个主要使用Spring提供REST API的webapp,并试图配置安全性。
我正在尝试实现这种模式:[https://developers.google.com/accounts/docs/MobileApps](Google完全更改了该页面,因此不再有意义-请参阅我在此处引用的页面: [http://web.archive.org/web/20130822184827/https://developers.google.com/accounts/docs/MobileApps)]
这是我需要完成的工作:
(例如,用户使用常规形式登录/注册,webapp提供带有令牌的安全cookie,然后可在随后的API请求中使用该令牌)
我有一个正常的身份验证设置,如下所示:
@Override protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.antMatchers("/mobile/app/sign-up").permitAll()
.antMatchers("/v1/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/")
.loginProcessingUrl("/loginprocess")
.failureUrl("/?loginFailure=true")
.permitAll();
}
我当时正在考虑添加一个预身份验证过滤器,该过滤器会检查请求中的令牌,然后设置安全上下文(这是否意味着将跳过正常的后续身份验证?),但是,我所拥有的权限超出了普通用户/密码 基于令牌的安全性并没有做太多,但是基于其他一些示例,我想到了以下内容:
安全配置:
@Override protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.addFilter(restAuthenticationFilter())
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.exceptionHandling().authenticationEntryPoint(new Http403ForbiddenEntryPoint()).and()
.antMatcher("/v1/**")
.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.antMatchers("/mobile/app/sign-up").permitAll()
.antMatchers("/v1/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/")
.loginProcessingUrl("/loginprocess")
.failureUrl("/?loginFailure=true")
.permitAll();
}
我的自定义休息过滤器:
public class RestAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
public RestAuthenticationFilter(String defaultFilterProcessesUrl) {
super(defaultFilterProcessesUrl);
}
private final String HEADER_SECURITY_TOKEN = "X-Token";
private String token = "";
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
this.token = request.getHeader(HEADER_SECURITY_TOKEN);
//If we have already applied this filter - not sure how that would happen? - then just continue chain
if (request.getAttribute(FILTER_APPLIED) != null) {
chain.doFilter(request, response);
return;
}
//Now mark request as completing this filter
request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
//Attempt to authenticate
Authentication authResult;
authResult = attemptAuthentication(request, response);
if (authResult == null) {
unsuccessfulAuthentication(request, response, new LockedException("Forbidden"));
} else {
successfulAuthentication(request, response, chain, authResult);
}
}
/**
* Attempt to authenticate request - basically just pass over to another method to authenticate request headers
*/
@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
AbstractAuthenticationToken userAuthenticationToken = authUserByToken();
if(userAuthenticationToken == null) throw new AuthenticationServiceException(MessageFormat.format("Error | {0}", "Bad Token"));
return userAuthenticationToken;
}
/**
* authenticate the user based on token, mobile app secret & user agent
* @return
*/
private AbstractAuthenticationToken authUserByToken() {
AbstractAuthenticationToken authToken = null;
try {
// TODO - just return null - always fail auth just to test spring setup ok
return null;
} catch (Exception e) {
logger.error("Authenticate user by token error: ", e);
}
return authToken;
}
上面的结果实际上导致应用启动时出错:authenticationManager must be specified
谁能告诉我最好的方法-pre_auth过滤器是执行此操作的最佳方法吗?
编辑
我写下了发现的内容以及如何使用Spring-security(包括代码)来实现标准令牌实现(不是OAuth)
问题和方法/解决方案概述
使用Spring-security实施解决方案
希望对其他人有所帮助。
Spring-MVC中的所有控制器是否都是单例的,并且在不同的会话和请求之间共享?
如果是这样,我假设一个类变量像
public String name;
所有请求和会话都一样吗? 这样,如果用户X发出请求并且将session.getAttribute()
设置为Paul,那么用户Z也具有Paul作为属性?
就我而言,我不希望这种行为,但想知道是否有比session.getAttribute()
/request.getAttribute()
更简单或更干净的OOP方式来拥有会话/请求变量
我想使用Spring Security JSP标签库根据角色有条件地显示一些内容。但是在Spring Security 3.1.x中,仅检查一个角色。
我可以使用,但是ifAllGranted已弃用。
有什么帮助吗?
我有一个Spring MVC方法,该方法返回2981932561661953030。根据检索到的特定数据,有时需要将数据流返回给用户。 其他时候,它将返回除流之外的其他内容,有时还会返回重定向。 我绝对希望这是一个流而不是字节数组,因为它可能很大。
目前,我使用以下代码片段返回流:
HttpHeaders httpHeaders = createHttpHeaders();
IOUtils.copy(inputStream, httpServletResponse.getOutputStream());
return new ResponseEntity(httpHeaders, HttpStatus.OK);
不幸的是,这不允许Spring HttpServletResponse
数据实际填充响应中的HTTP标头。 这是有道理的,因为我的代码在Spring收到2981932561661953030之前就已写入ResponseEntity
。
以某种方式返回2981932561661953030和ResponseEntity
并让Spring处理它会很好。 它还可以与函数的其他路径平行,在该路径上我可以成功返回2981932561661953030。反正我可以用Spring完成此操作吗?
另外,我确实尝试在ResponseEntity
中返回HttpServletResponse
,以查看Spring是否会接受它。
return new ResponseEntity(inputStream, httpHeaders, HttpStatus.OK);
但是它抛出了这个异常:
org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
我可以通过直接设置2981932561661951953024上的所有内容来使函数正常工作,但是我只想用Spring来做到这一点。