工作中遇到的一些问题,有些解决方案来自网络,Mark之,持续更新
用HttpURLConnection去读取某个网页的内容时,老是会发生这个403错误,而直接用firefox访问这个网站时就没问题。
java代码HttpURLConnection去连的话 http header 中的User-Agent就为空,解决方法就是在连接之前先设置这个属性:
URL url = new URL(""); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestProperty("User-agent","Mozilla/4.0"); conn.setRequestMethod("POST"); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
进入class目录,这里为bin目录:
D:\workspace\workspace\test\bin>jar cvfe test.jar com.sample.Sample .
这边表示打包后的jar文件名为test.jar,该jar包的主方法为com.sample.Sample,当然Sample.java中需要有main方法:
package com.sample; public class Sample { public static void main(String[] args) { System.out.println(System.getProperty("java.version")); } }
将会在test.jar的META-INF/MANIFEST.MF中看到
Manifest-Version: 1.0 Created-By: 1.6.0_25 (Sun Microsystems Inc.) Main-Class: com.sample.Sample
由于已经位于bin目录,这里将当前目录(.)作为打包的内容。
运行该jar
D:\workspace\workspace\test\bin>java -jar test.jar 1.6.0_25
考虑某些场景,比如某个请求必须要servlet访问。但是该servlet中有其他资源,如datasource,但是用spring配置集成,现在问题就是需要在servlet中访问spring依赖注入的资源。需要做的就是将web容器实例化的servlet对象绑定到spring容器的context上下文中 ,这样就可以在servlet中去访问spring容器注入的对象。
在spring中提供了相应的绑定方法:
WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc)
其他该怎么配置还怎么配置,比如web.xml中:
<!-- spring config --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
<!-- target servlet --> <servlet> <servlet-name>test-user</servlet-name> <servlet-class>com.sample.tec.sales.web.UserDaoServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>test-user</servlet-name> <url-pattern>/test-user</url-pattern> </servlet-mapping>
其他在spring配置文件注入接口就不再赘述,见UserDaoServlet中的
private LoginService userService; ............... protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println(UserDaoServlet.class.getName() + ".ROOT"); WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); userService = (LoginService) ctx.getBean("userService"); userService.foo(); }
把eclipse中的【Windows】-【Preferences】-【Java】-【Install JREs】改为JDK,而不用JRE如果还不行就把jre删除