小编sid*_*ate的帖子

Spring MVC - 在JSP视图中没有获得价值

首先,我是Spring MVC世界的新手.

我做了一个简单的程序,其中Spring MVC将处理GET请求并设置一个名为"message"的变量.此变量应在JSP中显示设置值,但未按预期执行.代码正在编译并运行正常.能告诉你,这里做错了什么?

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_2_5.xsd"
    id="WebApp_ID" version="2.5">

    <display-name>Archetype Created Web Application</display-name>

    <servlet>
        <servlet-name>loginDispacher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

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

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

loginDispacher-servlet.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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <context:component-scan base-package="com.sandeep" />

    <!-- View resolver -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>
Run Code Online (Sandbox Code Playgroud)

Authorization.java

@Controller
@RequestMapping("/authorization")
public class Authorization {
    String message = "This is …
Run Code Online (Sandbox Code Playgroud)

java spring jsp spring-mvc

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

将嵌套循环转换为Java 8流

我有以下嵌套for循环,我需要转换为声明代码.

for (String variable : variables ){
      boolean validAttribute = false;
      if(variable.equals(SOME_CONSTANT)){
          validAttribute = true;
      }
      else {
         for(String attrName: attrNames){
            if(variableName.equals(attrName)){
                validAttribute = true;
                break;
            }
         }
      }
      if(!validAttribute){
          return false;
      }
 }
Run Code Online (Sandbox Code Playgroud)

我能够实现它如何使用flatMap.但是,在第一个不匹配的条目中,循环使用的早期似乎并不高效.还有其他更简单的方法吗?

(以下代码似乎很难理解)

List<String> inValidVariables = attrNames.stream().flatMap(attrName -> variableNames.stream()
                            .filter(variableName -> !variableName.equals(attrName) && !variableName.equals(SOME_CONSTANT)))
                            .collect(Collectors.toList());
 return inValidVariables.size() ==0;
Run Code Online (Sandbox Code Playgroud)

java for-loop java-8

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

测试中未抛出 MaxUploadSizeExceededException

我有一个简单的 spring 应用程序,带有一个需要多部分文件的控制器。出于测试目的,我将MaxUploadSize大小设置为仅 50 个字节。当我在 tomcat 中部署战争时,我得到了MaxUploadSizeExceededException更大文件的预期,但是如果我在单元测试中使用相同的文件,那么测试将不起作用。


配置

@Configuration
@EnableWebMvc
@ComponentScan(basePackageClasses = {...})
public class MyApplication extends WebMvcConfigurerAdapter {

  @Bean
  public CommonsMultipartResolver multipartResolver() {
    CommonsMultipartResolver commonsMultipartResolver =
        new CommonsMultipartResolver();
    commonsMultipartResolver.setDefaultEncoding("utf-8");
    commonsMultipartResolver.setMaxUploadSize(50);
    return commonsMultipartResolver;
  }
}

@RestController
@RequestMapping("/metadata")
public class MyController {

  @RequestMapping(method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
      produces = MediaType.APPLICATION_JSON_VALUE)
  public String metadata(@RequestParam MultipartFile file)  {
     //some processing...
  }
}
Run Code Online (Sandbox Code Playgroud)

测试

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = MyApplication.class)
public class MyControllerTest {
...
@Test
  public void testDocx() throws …
Run Code Online (Sandbox Code Playgroud)

java junit spring multipartform-data spring-mvc

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

MongoError:“ doc参数必须是文档数组”

我试图编写一个有角度的应用程序,将来自全接触式API的信息作为json并将其插入到mongodb中。我可以成功获取json文件,但是当我尝试将其插入到mongodb中时,我遇到了各种错误。我解决了许多错误,但我卡在这一个。任何帮助表示赞赏。

ERROR:


  MongoError {name: "MongoError", message: "docs parameter must be an array of documents", driver: true, stack: "MongoError: docs parameter must be an array of doc…(http://localhost:4200/vendor.bundle.js:71114:10)"}driver: truemessage: "docs parameter must be an array of documents"name: "MongoError"stack: "MongoError: docs parameter must be an array of documents?    at Function.webpackJsonp.../../../../mongodb-core/lib/error.js.MongoError.create (http://localhost:4200/vendor.bundle.js:33916:11)?    at Collection.webpackJsonp.../../../../mongodb/lib/collection.js.Collection.insertMany (http://localhost:4200/vendor.bundle.js:44864:32)?    at http://localhost:4200/main.bundle.js:57:20?    at Db.webpackJsonp.../../../../mongodb/lib/db.js.Db.collection (http://localhost:4200/vendor.bundle.js:49750:20)?    at Object.webpackJsonp.../../../../../routes/kisiler.js.exports.kisiEkle (http://localhost:4200/main.bundle.js:54:9)?    at http://localhost:4200/main.bundle.js:366:18?    at Request.requested [as _callback] (http://localhost:4200/vendor.bundle.js:21598:5)?    at Request.self.callback (http://localhost:4200/vendor.bundle.js:70137:22)?    at Request.webpackJsonp.../../../../events/events.js.EventEmitter.emit (http://localhost:4200/vendor.bundle.js:20324:17)?    at Request.<anonymous> (http://localhost:4200/vendor.bundle.js:71114:10)"__proto__: Error
    at Object.../../../../mongodb-core/lib/error.js (http://localhost:4200/vendor.bundle.js:33927:24)
    at …
Run Code Online (Sandbox Code Playgroud)

javascript json mongodb fullcontact

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

如何初始化仅适用于Android的react-native项目?

我可以为Android初始化react-native应用程序吗?我在Mac上执行了以下操作

npx react-native init AwesomeProject
Run Code Online (Sandbox Code Playgroud)

但因cocoapods相关错误而失败。

Error: Failed to install CocoaPods dependencies for iOS project, which is required by this template.
Run Code Online (Sandbox Code Playgroud)

现在据我所知,iOS 应用程序需要 cocoapods,我不想花时间调查这些错误。

android cocoapods react-native

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

具有太多类的命令模式

我们的遗留代码具有依赖于事件和对象类型的if else块的长代码

if(event == A && objectType == O1){
.....
}
else if (event == A && objectType == O2){
 ....
}
else if (....)
....
....
Run Code Online (Sandbox Code Playgroud)

随着越来越多的条件的引入,我正在考虑用每个条件的Command模式替换这个逻辑.但是所需的类数量是(事件数量)*(对象类型的数量).有没有更简单的方法来重构这段代码?

java design-patterns

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

ES6文件内容中的字符串插值

我遇到了ES6中的字符串插值功能。如果我在代码中定义了原始字符串,它将起作用。但是我想从文件中读取原始字符串,然后替换占位符。怎么做?

file.txt

   hello ${customer.name} 
Run Code Online (Sandbox Code Playgroud)

节点JS

   var customer = {name: 'sid'};
   var data = fs.readFileSync("file.txt","utf8");
   // what should go here so that data is 'Hello sid'?
Run Code Online (Sandbox Code Playgroud)

javascript node.js ecmascript-6

5
推荐指数
2
解决办法
2819
查看次数

Mongodb $ lookup动态集合

我有以下架构,其中项目类型可能有所不同,并在中提到connections.kind

var userSchema = new Schema({
  name: String,
  connections: [{
    kind: String,
    item: { type: ObjectId, refPath: 'connections.kind' }
  }]
});

var organizationSchema = new Schema({ name: String });
Run Code Online (Sandbox Code Playgroud)

我正在尝试进行动态查找,以便填充item对象。但这似乎不起作用。

db.users.aggregate([
    {
        $lookup:{
            from: '$connections.kind',
            localField: 'connections.item',
            foreignField: '_id',
            as: 'items'
        }
    }
])
Run Code Online (Sandbox Code Playgroud)

我知道我可以用mongoose.populate,但是想知道是否可以使用$ lookup

mongoose mongodb node.js

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

模拟 @AuthenticationPrincipal 参数

我有 spring-security-oauth2 应用程序,它是一个资源服务器。我们有一个自定义PrincipalExtractor类来构建自定义主体对象。此自定义主体对象不会扩展PrincipalUserDetails

class CustomUser{
//some custom fields
}

class CustomPrincipalExtractor implements PrincipalExtractor{
  @Override 
  public CustomUser extractPrincipal(Map<String, Object> map){
    return new CustomUser(map);
  }
}


class SomeController{
  @GetMapping
  public ResponseEntity(@AuthenticationPrincipal CustomUser user){
     //able to get user object 
  }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码工作正常。现在我想测试控制器,但无法传递 CustomUser 实例。

@SpringBootTest
@AutoConfigureMockMvc
public class SomeControllerTest{
   @Autowired
   private MockMvc mockMvc;

  @Test
  public void test(){
    mockMvc.perform(get(...).principal(CANNOT pass CustomUser as it does not implement Principal))
  }
}
Run Code Online (Sandbox Code Playgroud)

我查看了一些其他要求自定义HandlerMethodArgumentResolver但不确定如何配置自动配置的 MockMvc 的解决方案

java spring spring-security spring-boot spring-security-oauth2

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

Java 8 compute()和computeIfPresent()来检查现有值

我有这段代码:

if (notificationSend.get(key) != null && notificationSend.get(key).equals(value)) {
   return true;
} else {
   notificationSend.put(key, value);
   return false;
}
Run Code Online (Sandbox Code Playgroud)

我想知道是否有可能使用Jav8增强功能重构它compute(),computeIfPresent()或者computeIfAbsent()

java collections hashmap java-8

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